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
Type | Effect |
---|---|
a -> Maybe b | Exceptions |
a -> [b] | Non-dertminism |
a -> ST b | Internal State |
a -> IO b | Input/Output |
Whats the point of monads?
- Supports pure programming with effects
- Use of monads is explicit in types
- Can generalise functions to any effect