Friday, June 29, 2012

The Nomadic Monad or: How I Learned to Stop Worrying and Love the Burrito (Part 1)

This is the first in a series of posts about monads (part 2, part 3). I happen to be a .NET developer, so I'll use C# in my examples, but the concept should apply to any language that has first-class functions.

So why should I care about monads? Aren't they only found in those weird academic languages (like Haskell) that nobody actually uses in production code? Actually, no. If you're a .NET developer like me, you've already been using monads. For almost 5 years.

I first became aware of the existence of the concept of monads after attending Kevin Hazard's CodeMash 2011 talk, What the Math Geeks Don't Want You to Know about F#. Somewhere amid the concepts of pattern matching, closures, and discriminated unions, he mentioned monads. What he said was something the line of, "...then there are monads - I'm not going to get into them because this is an intro-level talk." This caught my attention, and, since I had never heard of monads, I wrote a single word - monad - in my notebook. And forgot about it as soon as I got home. Several months later, somebody mentioned monads in a tweet. I thought to myself, "Hmmm, haven't I heard that word before?" Then I forgot about it again. Several months after that, I came across it again on Twitter. This time, I got fed up with myself - there was a concept out there that I was completely ignorant of. It was time to educate myself. Thus, my quest began.

So what is a monad? And what do they have to do with burritos? First, and least importantly, burritos. If you spend any non-trivial amount of time googling monads, you will undoubtedly come across someone comparing them to burritos. Go ahead, google "monad" "burrito" - I get 847,000 results. Interesting, but not really relevant to what a monad is. For that, let's go the source of all knowledge, Wikipedia. I've taken the liberty of bulletizing its definition of a monad:

  • Formally, a monad consists of a type constructor M and two operations, bind and return.
  • The operations must fulfill several properties to allow the correct composition of monadic functions (i.e. functions that use values from the monad as their arguments or return value).
  • In most contexts, a value of type M a can be thought of as an action that returns a value of type a.
  • The return operation takes a value from a plain type a and puts it into a monadic container of type M a.
  • The bind operation chains a monadic value of type M a with a function of type a → M b to create a monadic value of type M b, effectively creating an action that chooses the next action based on the results of previous actions.

Wait, what?! This doesn't exactly make sense at first. But have no fear, it will all come together. Beginning with the next post, I'll begin dissecting each bullet point. Trust me - it'll all make sense by the end.

No comments:

Post a Comment