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

Filter function

The filter function is implemented similarly to map. However, there are some differences, which are given as follows:

  • The filter behavior is similar to map as explained earlier. However, notice the use of multiple pattern guards:
        filter f (x:xs)        | f x = x : filter f xs        | otherwise = filter f xs
  • Each guard is evaluated, and if it is evaluated to True, then the expression on the right-hand side is evaluated. 
  • Note the use of otherwise in the guard. The function otherwise always evaluates to True and is used to represent default behavior when everything in the guard evaluates to False.
We have used the library function odd to test whether a number is odd. Also, notice the use of let in the do block. In the do block, let ...

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