3. Monads

Created Saturday 23 August 2014

Overview

Monad Examples

GHCi> flatMap [1,7,11] (\x -> [x, x+1])
Result: [1,2,7,8,11,12]
GHCi> bindMaybe Nothing (\x ->
if (x==0)
then Nothing
else Just (2*x))
Result: Nothing
GHCi> bindMaybe (Just 0) (\x ->
if (x==0)
then Nothing
else Just (2*x))
Result: Nothing
GHCi> bindMaybe (Just 1) (\x ->
if (x==0)
then Nothing
else Just (2*x))
Result: 2

Common Functionality for All Monads

return :: a -> IO a
return :: a -> [a]
return :: a -> Maybe a
bind :: IO a -> (a -> IO b) -> IO b
bind :: [a] -> (a -> [b]) -> [b]
bind :: Maybe a -> (a -> Maybe b) -> Maybe b
join :: IO (IO a) -> IO a
**join :: a -> [a]**
join :: Maybe (Maybe a) -> Maybe a
join mmx = bind mmx id

Monad Type Class

class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
join :: Monad m => m (m a) -> m a
join mmx = mmx >>= id

do-Notation

addM :: Monad m => m Int -> m Int -> m Int
addM mx my =
mx >>= (\x -> my >>= (\y -> return (x + y)))
addM' :: Monad m => m Int -> m Int -> m Int
addM' mx my = do
x <- mx
y <- my
return (x + y)
EXAMPLE
people = ["Alice", "Bob", "Eve"]
items = ["car", "puppy"]
missing = do
person <- people --will extract all elements to apply all the following actions to them
item <- items --the same (refer to the flatMap)
return (person ++ " lost a " ++ item)



Backlinks: