Monads¶

Motivation: Division Evaluator¶

Consider expression evaluation handling potential division by zero:

In [20]:
data Expr = Val Int | Div Expr Expr

eval :: Expr -> Int
eval (Val n) = n
eval (Div e1 e2) = eval e1 `div` eval e2
In [22]:
eval (Div (Val 2) (Val 0)) -- This will throw a divide by zero exception
divide by zero

To address this problem, we define the following division operation:

In [ ]:
safediv :: Int -> Int -> Maybe Int
safediv _ 0 = Nothing
safediv n m = Just (n `div` m)

We now modify our eval function:

In [ ]:
eval' :: Expr -> Maybe Int
eval' (Val n) = Just n
eval' (Div e1 e2) = 
    case eval' e1 of
        Nothing -> Nothing
        Just v1 -> case eval' e2 of
            Nothing -> Nothing
            Just v2 -> safediv v1 v2
In [ ]:
eval' (Div (Val 2) (Val 0)) -- This will return Nothing
Nothing
In [ ]:
eval' (Div (Val 20) (Val 5))
Just 4

Code is a bit clumsy, but solves our problem!

Can we use applicative style and compact the code?

Maybe is an applicative.

In [ ]:
eval'' :: Expr -> Maybe Int
eval'' (Val n) = pure n
eval'' (Div e1 e2) = pure safediv <*> eval'' e1 <*> eval'' e2
Use <$>
Found:
pure safediv <*> eval'' e1
Why Not:
(safediv <$> eval'' e1)
<interactive>:3:27: error: [GHC-83865]
    • Couldn't match type ‘Maybe Int’ with ‘Int’
      Expected: Int -> Int -> Int
        Actual: Int -> Int -> Maybe Int
    • In the first argument of ‘pure’, namely ‘safediv’
      In the first argument of ‘(<*>)’, namely ‘pure safediv’
      In the first argument of ‘(<*>)’, namely ‘pure safediv <*> eval'' e1’

This approach does not work because of the type error! Even if we designed safediv to be of type Int -> Int -> Int, we could have pure safediv of type Maybe (Int -> Int -> Int) which does not help with the problem!

eval''' does not fit the pattern of effectful programming captured by Applicatives!

Going back to the verbose solution, eval', we can absstract out the following operator:

In [ ]:
(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
Nothing >>= _ = Nothing
Just x  >>= f = f x

This is called the "bind" operator. It propagates failure and applies f on success.

In [ ]:
eval''' :: Expr -> Maybe Int
eval''' (Val n) = Just n
eval''' (Div e1 e2) = eval''' e1 >>= \v1 ->
                      eval''' e2 >>= \v2 ->
                      safediv v1 v2
  • Evaluate e1 and call it's result v1
  • Evaluate e2 and call it's result v2
  • Finally, call safediv on v1 and v2

This can be generalized as follows:

m1 >>= \x1 ->
m2 >>= \x2 ->
...
mn >>= \xn ->
f x1 x2 ... xn

Special "do" notation for this pattern:

do
    x1 <- m1
    x2 <- m2
    ...
    xn <- mn
    f x1 x2 ... xn

Using the do notation, we can finalize the eval function:

In [ ]:
eval :: Expr -> Maybe Int
eval (Val n) = Just n
eval (Div e1 e2) = do
    v1 <- eval e1
    v2 <- eval e2
    safediv v1 v2 

Haskell's Monad declaration:

In [ ]:
class Applicative m => Monad m where
    return :: a -> m a
    (>>=) :: m a -> (a -> m b) -> m b

    return = pure

Examples¶

In [ ]:
instance Monad Maybe where
    -- (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
    Nothing  >>= _ = Nothing
    (Just x) >>= f = f x

The >>= operator propogates failure Nothing and applies f to argument inside the structure.

In [ ]:
instance Monad [] where
    -- (>>=) :: [a] -> (a -> [b]) -> [b]
    xs >>= f = [y | x <- xs, y <- f x]

The >>= operator applies f to every element in the list and collects the answers in a list!

In [ ]:
pairs :: [a] -> [b] -> [(a, b)]
pairs xs ys = do
    x <- xs
    y <- ys
    return (x, y)
In [ ]:
pairs [1, 2] ['a', 'b']
[(1,'a'),(1,'b'),(2,'a'),(2,'b')]

Generic Functions¶

Functions can be defined to work over any Monad!

In [35]:
--mymapM :: Monad m => (a -> m b) -> [a] -> m [b]
mymapM f [] = return []
mymapM f (x:xs) = do
    y <- f x
    ys <- mymapM f xs
    return (y:ys)
In [36]:
import Data.Char

conv :: Char -> Maybe Int
conv c 
    | isDigit c = Just (digitToInt c)
    | otherwise = Nothing
In [37]:
mapM conv "1234"
Just [1,2,3,4]
In [38]:
mapM conv "12a4"
Nothing
In [39]:
mapM conv (Just '1')
Just (Just 1)
In [48]:
--filterM :: Monad m => (a -> m Bool) -> [a] -> m [a]
filterM p [] = return []
filterM p (x:xs) = do
    b <- p x
    ys <- filterM p xs
    return (if b then x:ys else ys)
In [50]:
filterM (\x -> [True, False]) [1, 2, 3] 
-- This will return all possible combinations of filtering the list [1, 2, 3] 
-- based on the predicate that returns both True and False for each element. 
-- The result will be a list of lists containing all combinations of elements 
-- that are kept or discarded. POWER SET!!
Use const
Found:
\ x -> [True, False]
Why Not:
const [True, False]
<interactive>:1:1: error: [GHC-39999]
    • Could not deduce ‘Monad []’ arising from a use of ‘filterM’
      from the context: Num a bound by the inferred type of it :: Num a => [[a]] at <interactive>:1:1-39
    • In the expression: filterM (\ x -> [True, False]) [1, 2, 3]
      In an equation for ‘it’: it = filterM (\ x -> [True, False]) [1, 2, 3]
In [53]:
-- join :: Monad m => m (m a) -> m a
join mmx = do
    mx <- mmx
    x <- mx
    return x
Redundant return
Found:
do mx <- mmx x <- mx return x
Why Not:
do mx <- mmx mx
In [ ]:
join [[1,2],[3,4],[5,6]] -- should give [1,2,3,4,5,6]
<interactive>:1:1: error: [GHC-39999]
    • Could not deduce ‘Monad []’ arising from a use of ‘join’
      from the context: Num b bound by the inferred type of it :: Num b => [b] at <interactive>:1:1-24
    • In the expression: join [[1, 2], [3, 4], [5, 6]]
      In an equation for ‘it’: it = join [[1, 2], [3, 4], [5, 6]]
In [55]:
join (Just (Just 1)) -- should give Just 1
<interactive>:1:1: error: [GHC-39999]
    • Could not deduce ‘Monad Maybe’ arising from a use of ‘join’
      from the context: Num b bound by the inferred type of it :: Num b => Maybe b at <interactive>:1:1-20
    • In the expression: join (Just (Just 1))
      In an equation for ‘it’: it = join (Just (Just 1))

Monadic Laws¶

return x >>= f = f x

mx >>= return  = mx

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