Haskell/Understanding monads/Solutions/List

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

Bunny invasion[edit | edit source]


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

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


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

List comprehensions[edit | edit source]


(<*>) 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.


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.