Personal tools

Simple monad examples

From HaskellWiki

(Difference between revisions)
Jump to: navigation, search
m (Simple Monad Examples moved to Simple monad examples)
m (Fixed grammar (it's -> its))
 
(3 intermediate revisions by 3 users not shown)
Line 1: Line 1:
This page is designed to show some simple examples of using monads.
+
This page is designed to show some simple examples of using [[monad]]s, specifically using [[Maybe]].
   
 
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:
 
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:
Line 11: Line 11:
 
<haskell>Just 6</haskell>
 
<haskell>Just 6</haskell>
   
All you really need to know, is that the >>= operator either returns "Nothing" if it is passed "Nothing" on it's left-hand side; or if it's left-hand side is a "Just ..." it strips off the just, and passes the contents into the function supplied on it's right-hand side. Simple!
+
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:
 
Some simple exercises:
Line 21: Line 21:
 
Nothing >>= (\ x -> if (x == 0) then fail "zero" else Just (x + 1) )
 
Nothing >>= (\ x -> if (x == 0) then fail "zero" else Just (x + 1) )
 
</haskell>
 
</haskell>
  +
  +
----
  +
More examples can be found in the reference guide [http://members.chello.nl/hjgtuyl/tourdemonad.html A tour of the Haskell Monad functions], by Henk-Jan van Tuyl.
  +
----
  +
[[Category:Monad]]

Latest revision as of 19:54, 30 April 2012

This page is designed to show some simple examples of using monads, specifically using Maybe.

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:

Just 6

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.