Skip to content

Instantly share code, notes, and snippets.

@JoeyEremondi
Created June 4, 2015 00:44
Show Gist options
  • Save JoeyEremondi/5def805fb799fd25d6e9 to your computer and use it in GitHub Desktop.
Save JoeyEremondi/5def805fb799fd25d6e9 to your computer and use it in GitHub Desktop.
I'm going to talk about Monads as they are used in programming, without reference to the category theory (in no small part because I don't understand it entirely myself).
Monads are present in many languages, with various names. Elm has them as [Tasks](http://elm-lang.org/blog/announce/0.15.elm), and F# has them as [Computation Expressions](https://msdn.microsoft.com/en-us/library/dd233182.aspx). You could write something equivalent in JavaScript, Python, or any language supporting higher-order functions.
To understand what they are, you need to understand what a type constructor is. A type constructor is something which, when given a specific type as an argument, forms a type.
In Haskell notation, `List` is a type constructor. It's not a full type, because you don't know what it is a list of. `List Int` is a type, as is `List Bool`, or `List (List Double)`. This is similar to generics in Java or Templates in C++: you can't have just a List, you need `List<int>` or something like that.
Now, "monad" is an abstract type, just like "set" or "tree" or "dictionary." It has a set of operations that must be present for something to be called a Monad, but the implementation of these changes for each specific instance of a monad.
So, the typeclass (Haskell-term for abstract type) of monad consists of:
* A type-constructor `M`
* A "lift" operation with type `a -> M a`. In Haskell this is called `return`, but that's a terrible name because it is NOT the same as a function return. Note that `a` is a type variable in the lift type: for any type `a`, it takes a value of type `a` and returns a `M a`.
* A "bind" operation with type `M a -> (a -> M b) -> M b`. This is a "sequencing" operation, and is really what makes monads interesting. It lets us sequence various operations together, applying functions to the "value" encased in a monad. I'll explain more about this below.
There are also some laws that a monad has to follow to be well behaved, but usually these aren't focused on.
So, what is a monad actually useful for? It lets us write a computation which keeps track of context and performs some magic with that context, without having to worry about that.
You can also see that, by the type of bind, Monads really don't work without higher order functions. So any language that doesn't let you pass a function as a parameter can't do much with monads.
Remember, a monad is abstract. Let's look at some instances of it. A popular one is the List monad. This lets us
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment