Friday 29 April 2016

Haskell: >> : Chain IO actions


Haskell provides >> function, to chain IO actions.
Prelude> :t (>>)
(>>) :: Monad m => m a -> m b -> m b

if x and y are IO actions, then (x >> y) is the action that performs x, dropping the result, then performs y and returns its result.

Sample.hs
main = putStrLn "Hello Haskell" >> putStrLn "You are very Crazy!!!!" >> putStrLn "Let me try"

$ ghc Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, Sample.o )
Linking Sample ...
$ 
$ ./Sample
Hello Haskell
You are very Crazy!!!!
Let me try


All the statements in the do block are internally combined using >>, >>=.

Sample.hs
main = do
    putStrLn "Hello Haskell"
    putStrLn "You are very Crazy!!!!"
    putStrLn "Let me try"


Above code snippet translated like below using binding operator (>>).
main = putStrLn "Hello Haskell" >> putStrLn "You are very Crazy!!!!" >> putStrLn "Let me try"


Note
'>>' binding operator ignores the value of its first action and returns result of its second action only.




Previous                                                 Next                                                 Home

No comments:

Post a Comment