Skip to content

Notes for Week 16 Monads Part 2

newmana edited this page Apr 1, 2012 · 17 revisions

Links:

Exercises:

Exercise 1

Write the following list comprehension in Monadic do notation:

[(x*x) | x <- [1..50], '7' `elem` show x, x > 20]

verify that the results produced are equal to:

results = [729,1369,2209]

hint: MonadPlus and Guards.

Exercise 2

Write the list comprehension given in question 1 in terms of >>= and >>.

Exercise 3

Given the definition of <=<, prove the 3 monad laws apply to <=<:

import Control.Monad (Monad, (>>=))
(<=<) :: (Monad m) => (b -> m c) -> (a -> m b) -> (a -> m c)
f <=< g = (\x -> g x >>= f)

If you have issues using the <=< function, feel free to rename it.

Questions raised during the group:

What is <=< called?

(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m cSource
Left-to-right Kleisli composition of monads.
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m cSource
Right-to-left Kleisli composition of monads. (>=>), with the arguments flipped

Or RocketShip or TinTitRocketShip

Answers to Exercises:

Exercise 1

ex1 = do
    x <- [1..50]
    guard ('7' `elem` show x)
    guard (x > 20)
    return (x * x)

results = [729,1369,2209]
ok1 = ex1 == results

Exercise 2

ex2 = do
    [1..50] >>= (\x -> guard ('7' `elem` show x) >> guard (x > 20) >> return (x * x))

results = [729,1369,2209]
ok2 = ex2 == results

Exercise 3

(<==<) :: (Monad m) => (b -> m c) -> (a -> m b) -> (a -> m c)
f <==< g = (\x -> g x >>= f)

llid = return <==< (\x -> [x] ++ [1])
rlid = (\x -> [x] ++ [1])
leftid = llid 5 == rlid 5

lrid = (\x -> [x] ++ [1]) <==< return
rrid = (\x -> [x] ++ [1])
rightid = lrid 5 == rrid 5

lassoc = (\x -> [x] ++ [1]) <==< ((\y -> [y] ++ [2]) <==< (\z -> [z] ++ [3]))
rassoc = ((\x -> [x] ++ [1]) <==< (\y -> [y] ++ [2])) <==< (\z -> [z] ++ [3])
assoc = lassoc 5 == rassoc 5

Interesting Asides

//TODO

Clone this wiki locally