O'Reilly logo

Haskell Cookbook by Yogesh Sajanikar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Create a new project list-as-monad using the simple Stack template.
  2. Open src/Main.hs and edit it.
  3. Add the following import for monad:
        import Control.Monad
  1. Write a function that takes an integer x and 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)
  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)
  1. Write a partitioning function using list comprehension. The same function is also written using the monadic syntax:
 partition :: (a -> b -> Bool) -> [a] -> [b] -> [(a,b)] partition f xs ys = [ (x, y) | x <- xs, y <- ys, f x y] partition1 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required