Lecture 15-2
filter
filter
keeps only the elements for which f
returns True
.
filter' :: (a -> Bool) -> [a] -> [a]
filter' _ [] = []
filter' f (x:xs)
| f x = x : rest
| otherwise = rest
where rest = filter' f xs
filter' even [1..10]
> [2,4,6,8,10]
In comparison to map
which applies a function to each element in a list. filter
will apply a boolean test to each element in the list and if it fails it will remove the element from the list.
Combining map
& filter
square_even :: [Int] -> [Int]
square_even list = map (^2) (filter even list)
square_even [1..10]
> [4,16,36,64,100]
Higher Order Programming
map
and filter
are examples of higher order programming. This style:
- De-emphasises recursion.
- Focuses on applying functions to lists.
- Are available in imperative languages (Python C++).
There is a whole family of higher order programming functions available in Haskell.
Exercises
onlyDiv3 = filter (\x -> mod x 3 == 0)
onlyLower = filter (\x -> elem x ['a'..'z'])
noEven = map (filter odd)