Filter (higher-order function)

In functional programming, filter is a higher-order function that processes a data structure (usually a list) in some order to produce a new data structure containing exactly those elements of the original data structure for which a given predicate returns the boolean value.

Example
In Haskell, the code example

evaluates to the list 2, 4, …, 10 by applying the predicate  to every element of the list of integers 1, 2, …, 10 in that order and creating a new list of those elements for which the predicate returns the boolean value true, thereby giving a list containing only the even members of that list. Conversely, the code example evaluates to the list 1, 3, …, 9 by collecting those elements of the list of integers 1, 2, …, 10 for which the predicate  returns the boolean value false (with   being the function composition operator).

Visual example
Below, you can see a view of each step of the filter process for a list of integers  according to the function :$$f(x) = \begin{cases} \mathrm{True} &\text{ if } x \equiv 0 \pmod{2}\\ \mathrm{False} & \text{ if } x \equiv 1 \pmod{2}. \end{cases}$$

This function express that if $$x$$ is even the return value is $$\mathrm{True}$$, otherwise it's $$\mathrm{False}$$. This is the predicate.

Language comparison
Filter is a standard function for many programming languages, e.g., Haskell, OCaml, Standard ML, or Erlang. Common Lisp provides the functions  and. Scheme Requests for Implementation (SRFI) 1 provides an implementation of filter for the language Scheme. C++ provides the algorithms  (mutating) and   (non-mutating); C++11 additionally provides   (non-mutating). Smalltalk provides the  method for collections. Filter can also be realized using list comprehensions in languages that support them.

In Haskell,  can be implemented like this:

Here,  denotes the empty list,   the list concatenation operation, and   denotes a list conditionally holding a value, , if the condition   holds (evaluates to  ).

Variants
Filter creates its result without modifying the original list. Many programming languages also provide variants that destructively modify the list argument instead for faster performance. Other variants of filter (e.g., Haskell and  ) are also common. A common memory optimization for purely functional programming languages is to have the input list and filtered result share the longest common tail (tail-sharing).