2 ms·
That's the abstract. For the concrete, here's the standard pile of examples. Note that all of these have ways to create or interact with them other than the m
by dllthomas 12y ago
That's the abstract. For the concrete, here's the standard pile of examples. Note that all of these have ways to create or interact with them other than the monad interface, but those differ from example to example (often substantially). Monad captures one similarity, there are differences as well.
The list monad represents nondeterministic computation ("nondeterministic" in the sense of representing all possibilities, not in the sense of picking a random one).
List:
return x = [x]
bind xs f = concat (map f xs)
Maybe represents computation with the possibility of failure.
Maybe:
return x = Just x
bind Nothing _ = Nothing
bind (Just x) f = f x
State carries some data that can be read and updated in the context of the computation.
State:
return x = \ s -> (x, s)
bind m f = \ s -> case m s of (x, s') -> f x s'
A Parser, from parsec, is a bit complicated internally for flexibility and error handling, but the gist is that it represents a parser action that may consume a portion of the input stream and produces a value.
Parser:
return x: a parser that consumes nothing and produces x
bind m f: a parser that runs parser m, passes the output to
function f, and runs the resulting parser
Functions that all take the same type can be treated as a monad. This is often codified into Reader, to make things clearer.
((->) r):
return x = \ _ -> x
bind m f = \ r -> f (m r) r
And of course famously IO, representing actions that produce a value and may interact with the world at large, forms a monad.
IO:
return x: an action which does nothing and produces x
bind m f: an action which, when executed, executes m, applies f
to the value produced, and then executes the result of f