Haskell Monad
With Applicative you can combine several independent wrapped values. But often the next step depends on the result of the previous one: look up a user, then use that user's ID to look up their orders. If each lookup returns a Maybe, fmap gives you a Maybe (Maybe Order), nested one level too deep. Monad adds exactly the operation that solves this, called bind and written >>=.
class Applicative m => Monad m where
(>>=) :: m a -> (a -> m b) -> m b
return :: a -> m a -- the same as purem >>= f takes a wrapped value, feeds the value inside to f, and f returns a new wrapped value. No nesting.
Bind with Maybe
import qualified Data.Map as Map
users :: Map.Map String Int -- username -> user id
users = Map.fromList [("ada", 1), ("alan", 2)]
orders :: Map.Map Int [String] -- user id -> order list
orders = Map.fromList [(1, ["laptop", "mouse"])]
ordersFor :: String -> Maybe [String]
ordersFor name = Map.lookup name users >>= \uid -> Map.lookup uid orders
main :: IO ()
main = do
print (ordersFor "ada")
print (ordersFor "alan") -- user exists, but has no orders
print (ordersFor "grace") -- no such user
print (fmap (\uid -> Map.lookup uid orders) (Map.lookup "ada" users)) -- nested!Just ["laptop","mouse"]
Nothing
Nothing
Just (Just ["laptop","mouse"])
The last line shows the problem >>= solves: with fmap, the result is a Maybe inside a Maybe.
For Maybe, bind is defined like this:
Nothing >>= _ = Nothing
Just x >>= f = f xSo a chain of >>= short-circuits at the first Nothing.
Chains of steps
Each step can use the results of all earlier steps. This is what Applicative alone can't do:
safeDiv :: Double -> Double -> Maybe Double
safeDiv _ 0 = Nothing
safeDiv a b = Just (a / b)
safeSqrt :: Double -> Maybe Double
safeSqrt x
| x < 0 = Nothing
| otherwise = Just (sqrt x)
-- sqrt (a / b) - 1, then divide 10 by that
compute :: Double -> Double -> Maybe Double
compute a b =
safeDiv a b >>= \q ->
safeSqrt q >>= \r ->
safeDiv 10 (r - 1)
main :: IO ()
main = do
print (compute 36 4) -- sqrt 9 = 3, 10 / 2
print (compute 1 0) -- division by zero
print (compute (-8) 2) -- negative square root
print (compute 4 4) -- sqrt 1 = 1, 10 / 0Just 5.0
Nothing
Nothing
Nothing
do notation is bind in disguise
Those nested lambdas are hard to read. do notation is syntactic sugar for exactly the same thing: each x <- action line becomes action >>= \x -> ….
safeDiv :: Double -> Double -> Maybe Double
safeDiv _ 0 = Nothing
safeDiv a b = Just (a / b)
safeSqrt :: Double -> Maybe Double
safeSqrt x = if x < 0 then Nothing else Just (sqrt x)
compute :: Double -> Double -> Maybe Double
compute a b = do
q <- safeDiv a b
r <- safeSqrt q
safeDiv 10 (r - 1)
main :: IO ()
main = print (map (uncurry compute) [(36, 4), (1, 0), (-8, 2), (100, 1)])[Just 5.0,Nothing,Nothing,Just 1.1111111111111112]
do notation |
Desugars to |
|---|---|
do { x <- m; rest } |
m >>= \x -> do { rest } |
do { m; rest } |
m >> do { rest } (result of m ignored) |
do { let y = e; rest } |
let y = e in do { rest } |
do { m } |
m |
The >> operator ("then") runs one action after another and ignores the first result.
The same code, different monads
The power of the Monad abstraction is that do means something different, but sensible, for each type:
| Monad | What >>= means |
|---|---|
Maybe |
continue only if there is a value |
Either e |
continue only on Right; stop with the first Left |
[] (list) |
continue with every value: all combinations |
IO |
run the action, then continue with its result |
State s |
thread a state value through the steps (later lesson) |
The list monad deserves a demo: each <- picks every element in turn, so do works like a list comprehension:
pairsSummingTo :: Int -> [(Int, Int)]
pairsSummingTo n = do
x <- [1 .. n]
y <- [x .. n]
if x + y == n then return (x, y) else []
knightMoves :: (Int, Int) -> [(Int, Int)]
knightMoves (c, r) = do
(dc, dr) <- [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)]
let (c', r') = (c + dc, r + dr)
if c' `elem` [1 .. 8] && r' `elem` [1 .. 8] then return (c', r') else []
main :: IO ()
main = do
print (pairsSummingTo 6)
print (knightMoves (1, 1))
print (length (knightMoves (1, 1) >>= knightMoves)) -- squares after two moves (with repeats)[(1,5),(2,4),(3,3)]
[(2,3),(3,2)]
12
Useful monadic helpers (Control.Monad)
import Control.Monad (forM, forM_, when, unless, replicateM, foldM, zipWithM_)
main :: IO ()
main = do
forM_ [1, 2, 3] $ \i -> putStrLn ("step " ++ show i)
squares <- forM [1, 2, 3] (\i -> return (i * i))
print squares
when (sum squares > 10) $ putStrLn "big total"
unless (null squares) $ putStrLn "not empty"
print (replicateM 2 "ab") -- list monad: all 2-letter words
print (foldM (\acc x -> if x > 0 then Just (acc + x) else Nothing) 0 [1, 2, 3])
print (foldM (\acc x -> if x > 0 then Just (acc + x) else Nothing) 0 [1, -2, 3])
zipWithM_ (\i name -> putStrLn (show i ++ ". " ++ name)) [1 :: Int ..] ["gold", "silver"]step 1
step 2
step 3
[1,4,9]
big total
not empty
["aa","ab","ba","bb"]
Just 6
Nothing
1. gold
2. silver
The Monad laws
Lawful monads satisfy three laws, which make do blocks behave as you would expect (you can inline or extract steps freely):
| Law | Statement |
|---|---|
| Left identity | return a >>= f is f a |
| Right identity | m >>= return is m |
| Associativity | (m >>= f) >>= g is m >>= (\x -> f x >>= g) |
Tip: Don't look for a deeper metaphor ("a monad is a burrito"). A monad is simply a type with a sensible
>>=that obeys these laws. Understanding comes from using several concrete ones:Maybe,Either, lists,IOandState.
Test yourself
What is the type of >>=?
m a -> (a -> b) -> m bm a -> (a -> m b) -> m b(a -> m b) -> a -> m bm (a -> b) -> m a -> m b
What is Just 4 >>= \x -> if x > 3 then Just (x * 2) else Nothing?
Just 8NothingJust (Just 8)8
What is do { x <- [1, 2]; y <- "ab"; return (x, y) }?
[(1,'a'),(2,'b')][(1,'a'),(1,'b'),(2,'a'),(2,'b')](1,'a')- A type error