A simple do syntax example converted to>> = syntax

How is it reverse2linesconverted to syntax >>=? Just as addOneIntconverted to addOneInt'?

addOneInt :: IO () 
addOneInt = do line <- getLine
               putStrLn (show (1 + read line :: Int))      


addOneInt' :: IO ()
addOneInt' = getLine >>= \line ->
             putStrLn (show ( 1 + read line :: Int))  

reverse2lines :: IO () 
reverse2lines = 
 do line1 <- getLine 
    line2 <- getLine
    putStrLn (reverse line2) 
    putStrLn (reverse line1)

Please also read the next question and its valuable answers.

+1
source share
3 answers

You can safely bring him out of what you already know. Start with a full bracket in addOneInt':

addOneInt' = getLine >>= (\line ->
             putStrLn (show (1 + read line :: Int)) )

Then you reverse2linescan be equivalently written as

reverse2lines = 
 do { line1 <- getLine ;
      do { line2 <- getLine ;
           do { putStrLn (reverse line2) ;
                do { putStrLn (reverse line1) } } } }

Applying the one-step transformation that you have already used for addOneInt, as many times as necessary, you would get

reverse2lines' :: IO ()
reverse2lines' = 
    getLine  >>=  (\line1 ->
      getLine  >>=  (\line2 ->
        putStrLn (reverse line2)  >>
          putStrLn (reverse line1) ) )

- , , .

monad fail, , (line1, line2) , .

+5

x <- m m >>= \x -> ..., , m, m >> ...

reverse2lines :: IO () 
reverse2lines = getLine 
                >>= \line1 -> getLine 
                >>= \line2 -> putStrLn (reverse line2)
                >> putStrLn (reverse line1)

- fail . , , IO.

+4

Here is the code from Will, a very nice answer, using only >>=:

reverse2lines' :: IO () 
reverse2lines' = 
    getLine >>= (\line1 -> 
        getLine >>= (\line2 -> 
            putStrLn (reverse line2) >>= (\_ ->
               putStrLn (reverse line1) )))

Lesson learned: The sequence in docorresponds simply to the embedding of lambda expressions.

+1
source

Source: https://habr.com/ru/post/1536642/


All Articles