Friday, 3 June 2016

Haskell: Monads

In simple terms, a monad is used to chain operations in specific way. Technically, a monad is basically just a type that supports the >>= operator.

For example, following program group statements using >>=, with out using do block.


Sample.hs
main = putStrLn "Enter your name"
       >> getLine
       >>= \name -> putStrLn ("Your name is " ++ name)

$ ghc Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, Sample.o )
Linking Sample ...
$ 
$ ./Sample
Enter your name
Krishna
Your name is Krishna

Example 2
Take list of numbers from 1 to 10. Double the number if it is odd, triple the number if it is even.

We can do this by using >>= like below.


[1..10] >>= (\x -> if odd x then [x*2] else [x*3])
Prelude> [1..10] >>= (\x -> if odd x then [x*2] else [x*3])
[2,6,6,12,10,18,14,24,18,30]


Previous                                                 Next                                                 Home

No comments:

Post a Comment