Nested do syntax

In this question, the Answer will answer the following code (let's call it code A):

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

can be converted to the following (let's call it code B):

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

I'm confused. I understand, for example, that

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

can be converted to:

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

But I don’t understand how nested conversion works do. In other words, I do not understand how a person comes from code Ato code B? What are the rules governing this transformation?

Where are these rules described / explained / indicated?

Can someone explain what is happening with this conversion ( codeAto codeB) here?

For example, what does it mean do { command1; do {command2 } }? How do I interpret this? What is his definition?

In other words,

What's the difference between

do {command1;command2} and

do {command1; do {command2}}?

Also, what is the difference between

do {command1; do{command2};command3} and

do {command1;do {command2; do {command3}}}?

Thanks for reading.

+4
1

do : . , :

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

:

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

:

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

do :

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

, , , , :

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

, , , . , desugaring do ( ), , .

, , do : , , , , do.

+5

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


All Articles