Converting the do notation to bind notation

  • A+
Category:Languages

How do I convert the below Haskell do notation to the bind (>>=) notation?

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

I am a Haskell beginner with decent knowledge and I tried something like

getLine >>= (/line1 -> getLine >>= (/line2 -> putStrLn $ reverse(line2))) 

but I am not able to include the print statement for the other line i.e. line1. Kindly help me to understand this concept properly.


You're almost there: you need to use >>.

getLine >>= (/line1 ->  getLine >>= (/line2 ->  putStrLn (reverse line2) >> putStrLn (reverse line1) )) 

Note that >> ... is equivalent to >>= (/_ -> ...), so you can also use that if you prefer.

Similarly, your block

 do line1 <- getLine     line2 <- getLine     putStrLn (reverse line2)     putStrLn (reverse line1) 

is equivalent to

 do line1 <- getLine     line2 <- getLine     _ <- putStrLn (reverse line2)     putStrLn (reverse line1) 

Essentially, any entry in the block (but the last one) which has no explicit <- uses >> (or, if you prefer, has an implicit _ <- in front).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: