List as monad
In this recipe, we will revisit list and look at it as a monad. List is a monad, and we will work with a few examples of how to work with a list with monadic syntax and functions.
How to do it...
- Create a new project
list-as-monadusing thesimpleStack template. - Open
src/Main.hsand edit it. - Add the following import for monad:
import Control.Monad
- Write a function that takes an integer
xand returns a list of all integers starting with x ([x, x+1, x+2,...]):
nexts :: Num a => a -> [a]
nexts x = do
x : nexts (x+1)- Write a function that takes two lists and returns all ordered pairs from this list:
pairs :: [a] -> [b] -> [(a,b)]
pairs xs ys = do
x <- xs
y <- ys
return (x,y)- Write a partitioning function using
listcomprehension. The same function is also written using the monadic syntax:
partition :: (a -> b -> Bool) -> [a] -> [b] -> [(a,b)]
partition f xs ys = [ (x...