Filter is a very common higher-order function.
Filter is kind of like map, in that it takes a function and a list and applies the function to all the elements in the list. The difference is the output. Where map uses the function to transform each element in the list, filter uses the function to determine whether an element should be included in the list that it returns.
Here’s a simple example in Python (try it!):
def isEven(x):
return x % 2 == 0
list = [1, 2, 3, 4, 5]
evens = filter(isEven, list)
print evens
The printed output is [2, 4]
.
Like map and fold, filter is often used in declarative code where a loop might be used in code that has a more imperative style. And like map and fold, when you get used it, filter can make your code simpler than it might be with a loop.