Sunday, 12 August 2007

Learning about (Computational) Monads

I am interested in acquiring programming idioms -- or if you like patterns -- that facilitate a clear and disciplined approach to organizing state. As applications grow large and certain operations transform state in a large-scale fashion, it becomes harder to understand and modify program behavior.

Perhaps monads offer a better way, but I don't really get them yet ...

What are Monads?

I think Leibniz invented the term monad to describe some kind of indivisible fundamental entity in his philosophy: Presumably the term atom was too Greek for him. Anyway: I do not mean philosophical monads, or biological monads, or mathematical -- category theory -- monads (although now we are getting warmer).

Right now I mean computational monads, the ones so beloved of Haskell programmers, but potentially of use elsewhere.
A monad is a family of types M t, based on a polymorphic type constructor M, with functions

return :: t -> M t
(>>=) :: M t -> (t -> M u) -> M u


return a >>f = f a
m >>= return = m
m >>= (\a -> (f a) >>=g) = (m >>= f) >>= g
This definition gave me flashbacks to Pure Mathematics Honours (4th year University) where I encountered some classes so abstract as to seem totally detached from reality: "Hello Banach Spaces and Algrebras!"

How to get it

But having survived a mathematics education and having a ridiculously high sense of self-efficacy I know how to get through this kind of obstacle. There are two methods:
  1. Abstractions first: Treat this as a game where the rules are given, and play with them until they become familiar and seem natural.
  2. Empirical approach: Walk in the footsteps of the discoverers by building some practical experience first, so that the abstractions begin to make sense.
Better still, work from both ends. Anyway, both approaches require doing, as opposed to reading, and I am starting with the following tutorial:

You Could Have Invented Monads! (And Maybe You Already Have)

which seems to be helping, and belongs to the latter camp.

More later ...

No comments: