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. Open src/Main.hs and add the following definitions to it. For each function such as sum, we will create two versions--sumrwhich uses foldr, and suml, which uses foldl.
  2. Use both, right and left folds to sum up the numerical contents of a list to write functions sumr and suml  as follows:
        sumr :: Num a => [a] -> a        sumr xs = foldr (+) 0 xs        suml :: Num a => [a] -> a        suml xs = foldl (+) 0 xs
  1. Similarly, use right and left folds to calculate product of all elements in the list. This should results in functions productr and productl respectively:
        productr :: Num a => [a] -> a        productr xs = foldr (*) 1 xs        productl :: Num a => [a] -> a        productl xs = foldl (*) 1 xs
  1. Define map using the folds mapr and mapl:
 mapr :: (a -> b) ...

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