Skip to main content

9. Monads IV

06/03/23

Monanic Version of map

mapm :: Monad m => (a -> m b) -> m[b]
mapm f [] = return []
mapm f (x:xs) = do y <- f x
ys <- mapm f xs
return (y:ys)
conv :: Char -> Maybe Int
conv c | isDigit c = Just (digitToInt c)
| otherwise = Nothing
concat :: [[a]] -> [a]
concat xss = [x | xs <- xss, x <- xs]

join :: Monad m => m (m a) -> m a
join mmx = do mx <- mmx
x <- mx
return x

Monad Laws

return x >>= f = ? Goal is to figure out what type should be at ?

return x >>= f = f x

Right hand side

mx >>= return = mx

Bind operator with itself

Associativity property

(mx >>= f) >>= g
=
mx >>= (\x -> (f x >>= g))

These are fundamental properties for monads

Effectful Programming

TypeEffect
a -> Maybe bExceptions
a -> [b]Non-dertminism
a -> ST bInternal State
a -> IO bInput/Output

Whats the point of monads?

  1. Supports pure programming with effects
  2. Use of monads is explicit in types
  3. Can generalise functions to any effect