(monads.txt) Monads ====== Monad is a constructor class given in the Prelude as: class Monad m where (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b return :: a -> m a fail :: String -> m a -- Minimal complete definition: -- (>>=), return m >> k = m >>= \_ -> k fail s = error s I like to think of the elements of a monad as "actions", and the monad operators provide ways of combining actions. Actions often in volve a computation that yields a value while implicitly changing some underlying "state". Some monads (e.g. List), however, don't really fit this metaphor. The infix operator >>= is sometimes called "bind", though I prefer the name "chain" that I used in the reader.sml example. It combines two actions in sequence, where the second action depends on the value produced by the first action. >> is a variation where the second action is independent of the value produced by the first. Monad Laws: The algebraic equations that are assumed for proper monads are: return a >>= k = k a m >>= return = m m >>= (\x -> k x >>= h) = (m >>= k) >>= h m1 >> (m2 >> m3) = (m1 >> m2) >> m3 Some examples from the Prelude: [These two examples don't fit the "action" metaphor.] Maybe monad: instance Monad Maybe where (Just x) >>= k = k x Nothing >>= k = Nothing return = Just fail s = Nothing List monad: instance Monad [] where m >>= k = concat (map k m) return x = [x] fail s = [] Example: The reader type with the operations return and chain from reader.sml was a monad (except for the nonstandard naming). Example: A state monad data State s a = ST (s -> (a,s)) -- State : * -> * -> * instance Monad (State s) where -- State s : * -> * return x = ST(\s -> (x,s)) (ST m) >>= f = ST(\s -> let (x,s') = m s ST f' = f x in f' s') ---------------------------------------------------------------------- The IO monad <See Language Specification> ---------------------------------------------------------------------- A Counter Monad <Counter.hs>