-
Notifications
You must be signed in to change notification settings - Fork 5
Notes for Week 16 Monads Part 2
newmana edited this page Apr 1, 2012
·
17 revisions
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.
Write the list comprehension given in question 1 in terms of >>= and >>.
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.
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
ex1 = do
x <- [1..50]
guard ('7' `elem` show x)
guard (x > 20)
return (x * x)
results = [729,1369,2209]
ok1 = ex1 == results
ex2 = do
[1..50] >>= (\x -> guard ('7' `elem` show x) >> guard (x > 20) >> return (x * x))
results = [729,1369,2209]
ok2 = ex2 == results
(<==<) :: (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
//TODO