Hacker News new | ask | show | jobs
by continuational 3238 days ago
Monad is just an interface with these methods:

    pure :: a -> List a
    flatten :: List (List a) -> List a
    map :: (a -> b) -> List a -> List b
The above types are for lists, but you can substitute your own type constructor for List.

For lists, the implementation is as follows:

    pure x = [x]

    flatten [] = []
    flatten (x:xs) = x ++ flatten xs

    map f [] = []
    map f (x:xs) = f x : map f xs
A flatMap method can be defined once for all monads:

    flatMap f m = flatten (map f m)
This method is sometimes called "bind" and is written ">>=" in Haskell (where pure is also called "return" and flatten is also called "join"):

    m >>= f = flatMap f m
The methods are related by the monad laws - you can look them up if you're interested, but they're not required to gain an intuition.