Haskell/Understanding monads/Solutions/List

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Bunny invasion[edit | edit source]

1.

Prelude> ["bunny", "rabbit"] >>= generation
["bunny","bunny","bunny","rabbit","rabbit","rabbit"]

Each element gives rise to three copies of itself. The order of the copies matches the order of the original elements.

2.

themselvesTimes :: [Int] -> [Int]
themselvesTimes ns = ns >>= \n -> replicate n n

List comprehensions[edit | edit source]

1.

(<*>) for lists takes a list of functions and a list of values that can be passed to the functions. It then applies each function to all of the values, and gives back all results thus generated in a single list.

2.

fs <*> xs = [ f x | f <- fs, x <- xs ]

Note that the order of the generators matters when writing the list comprehension above. To see the difference, try both (\fs xs -> [ f x | f <- fs, x <- xs ]) [(2*),(3*)] [1,2] and (\fs xs -> [ f x | x <- xs, f <- fs ]) [(2*),(3*)] [1,2] in GHCi.