20-CS-4003-001 | Organization of Programming Languages | Fall 2017 |
---|---|---|
Monads |
Basics
x // y = x >>= (\a -> y >>= (\b -> if b == 0 then Nothing else Just (a / b))) {- the above in do notation x // y = do a <- x b <- y if b == 0 then Nothing else Just (a / b) -} |
- |
A monad is a construction that embeds a type system corresponding to a
given type system into the underlying type system whereby it acts the
same way and in place of the underlying type system. That is, all
significant aspects of the underlying type system are preserved while
new features particular to the monad are added.
The Monad is a type class over four functions as seen from executing Prelude> :info Monad class Monad m where (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b return :: a -> m a fail :: String -> m aThese are named and defined as follows:
There must be a type constructor that defines, for every underlying type, how to obtain a corresponding monadic type. The name of the monad represents the type constructor. If m is the name of the monad and t is a data type, then m t is the corresponding type in the monad.
Example: data Maybe a = Nothing | Just a instance Monad Maybe where Nothing >>= f = Nothing Just x >>= f = f x return x = Just x fail _ = NothingThe following axioms must be obeyed by any Monad:
Alternative do notation. Example: a = do x <- [3,4] [1..4] return xis a = [3,4] >>= (\x -> [1..4] >>= (\_ -> return x))which works because lists are monads!! The above returns [3,3,3,3,4,4,4,4]. Here is what happens: [1..4] >>= (\_ -> return x)means return value x for each object in [1..4] - but x is determined from the list [3..4]. The following: a = [3,4] >>= (\x -> [1..4] >>= (\y -> return (x+y)))returns [4,5,6,7,5,6,7,8] Definition of the list type as a Monad: instance Monad [] where m >>= f = concatMap f m return x = [x] fail s = [] To the left is an implementation of a safe division operation |