What is a monad? And who needs Haskell anyway?

I guess if Rust were able to express the monad typeclass (trait), it would look something like this

trait<T, F, U> Monad<T>
where
    F: Fn(T) -> Monad<U>
{
    fn bind(self, f: F) -> Monad<U>;
    // ... other stuff
}

// Every type has to provide a specific implementation of `bind`
// that makes sense for the specific type. The implementation must obey
// the monadic laws.

// Here is how `Vec<T>` would implement `bind`.
impl<T, F, U> Monad<T> for Vec<T>
where
    F: Fn(T) -> Vec<U>
{
    fn bind(self, f: F) -> Vec<U> {
        self.into_iter().flat_map(f).collect()
    }
}

Being a monad requires implementing a bind method (which satisfies some laws). What this does varies from monad to monad, according to what the behavior needs to be (implicit passing of state and sequential computation for IO, short-circuiting for Option/Result...). The implementation for Vec is just flat_map, because that is the monadic behavior of a vector (see Wikipedia for instance).

Maybe, what might help you understand is to realize that "monad" is not any specific data structure, it's a class of objects that respect some structural property. "Monad" lives in the same universe as semigroup, monoid, group, vector space, ring, algebra, module, field, etc... It's a class of objects with some operations that respect some properties.
The integers with the addition are a group, the vectors with a specific implementation of join/bind are a monad.

1 Like