Simple monad examples
m (Fixed grammar (it's -> its))
|(2 intermediate revisions by 2 users not shown)|
Latest revision as of 19:54, 30 April 2012
I personally found that I reached monad-enlightenment once I contrived this simple example while playing around to see the "guts" of a monadic expression:
Just 5 >>= (\ x -> if (x == 0) then fail "zero" else Just (x + 1) )
Which results in:
All you really need to know, is that the >>= operator either returns "Nothing" if it is passed "Nothing" on its left-hand side; or if its left-hand side is a "Just ..." it strips off the just, and passes the contents into the function supplied on its right-hand side. Simple!
Some simple exercises:
What would the following snippets resolve to?
Just 0 >>= (\ x -> if (x == 0) then fail "zero" else Just (x + 1) ) Nothing >>= (\ x -> if (x == 0) then fail "zero" else Just (x + 1) )
More examples can be found in the reference guide A tour of the Haskell Monad functions, by Henk-Jan van Tuyl.