Llayland’s Food, Oracle, and Haskell

January 21, 2009

Understanding Monads I

Filed under: Haskell — llayland @ 5:39 am

It turns out that understanding monads is even harder than finding the time to write about monads. I don’t want to waste this opportunity, so I’m just going to make it up as I go along.

For me to really have a motivation to understand something, I need to see a need for it. So just what good are monads anyways? The first thing I thought of was you can view monads as models to evaluate functions, that are  defined with the monadic operators, under. Admittedly this is stupidly simple example but I’m at the stupidly simple stage of learning:

> let failOn0 n = n >>= \x -> if x == 0 then fail “zero” else return x

This seems tailor made to evaluate under the Maybe monad which models possible failure:

> failOn0 (Just 1)
Just 1
> failOn0 (Just 0)

You could also evaluate under the List monad which models non-deterministic choice. Basically, you get back all possible results:

> failOn0 [1,2,3]
> failOn0 [0,2,3]
> failOn0 [0,0,0]

Finally you could evaluate it under the Identity monad which models variable substitution.  This one is a little different because it can really fail:

> failOn0 (Id 1)
Id 1

>failOn0 (Id 0)

*** Exception: zero

So I can write one function and evaluate it several different ways.  That’s enough of a reason for me to dig in deeper.  Now I’d suggest reading Monads as containers for good explanation of writing simple monads. Then I would write Identity Monad and the Tree Monad on paper. I would follow that up by writing the reductions for several examples of fmap, join, and >>= on paper.  And yes, I really do mean on paper.

I just finish the paper exercizes today and I think I have a good handle it. I think I can almost tackle part II where I will get into more of the usefulness of monads, conditioning myself to what >>= really means, and the state monad.

Create a free website or blog at WordPress.com.