# Simple monad examples

### From HaskellWiki

(Difference between revisions)

m (Simple Monad Examples moved to Simple monad examples) |
m (link) |
||

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. |

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: |

## Revision as of 04:20, 19 March 2006

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

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 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!

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) )