Haskell/Understanding monads/IO, Exercises 2

Haskell

Generalize the bunny invasion example in the list monad chapter for an arbitrary number of generations.

— Wikibooks

——————————

import Control.Monad

generation = replicate 3
gen n = foldr (<=<) return (replicate n generation)

---

["bunny"] >>= gen n

Additional notes:

m >>= g ≡ join (fmap g m)
xs >>= f = concat (map f xs) -- for the List Monad

---

f >=> g
= (\x -> f x) >>= g
= concat (map g (\x -> f x))


---


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

xs >>= (return >=> g >=> h)
((xs >>= return) >>= g) >>= h


---


xs >>= return
= concat (map f xs)
= concat (map return xs)
= concat (map return ["bunny"])
= concat ([return "bunny"])
= concat ([["bunny"]])
= ["bunny"]


---


-- foldr f acc []     = acc
-- foldr f acc (x:xs) = f x (foldr f acc xs)

-- foldr (<=<) return (replicate n generation)

foldr (<=<) return [h,g]
= (<=<) h (foldr (<=<) return [g])
= (<=<) h ((<=<) g (foldr return []))
= (<=<) h ((<=<) g return)
= h <=< g <=< return


--- 


compose :: [b -> [b]] -> b -> [b]
compose = foldr (<=<) return

foldr (<=<) return (replicate n generation)
= compose (replicate n generation)

— Me@2015-07-08 11:29:40 PM

2015.07.15 Wednesday (c) All rights reserved by ACHK