WHAT’S IN A MONAD?

In Haskell, Monad is a typeclass. Here’s what it looks like:

class Monad m where

  (>>=) :: m a -> (a -> m b) -> m b

  return :: a -> m a

Granted, at a glance this doesn’t explain much. But the important thing is to recognize that a monad is a particular typeclass, in other words, Monad describes a particular class of types. It is the class of types that support the two rather cryptic functions (>>=) (this is usually pronounced “bind”) and return.

To illustrate the requirements that are declared by the Monad typeclass, here’s an implementation of a C# interface with a very similar set of two functions:

public interface IMonad<A> {

  IMonad<A> Return(A val);

  IMonad<b> Bind<b>(Func<A, IMonad<b>> g);

}

That looks much simpler! The Return function takes a value of type A and returns an IMonad<A>. It wraps the value in the monad, so to speak. The Bind function takes a delegate as an argument, which can receive a value of type A and returns an IMonad<B>. Bind itself also returns an IMonad<B>. In reality this interface is usually not used because the formalization it provides is regarded as too strict. For example, the process of wrapping a value in a monad, as described earlier by the Return function, might be implemented as a constructor call in object oriented C#. The two functions also could be implemented as static methods, perhaps extension methods, elsewhere, instead of being instance methods in the type itself.

To summarize the theoretical part: a monad ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.