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 ...