Infunctional programming,filter is ahigher-order function that processes adata structure (usually alist) in some order to produce a new data structure containing exactly those elements of the original data structure for which a givenpredicate returns theBoolean valuetrue
.
InHaskell, the code example
filtereven[1..10]
evaluates to the list 2, 4, …, 10 by applying the predicateeven
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
filter(not.even)[1..10]
evaluates to the list 1, 3, …, 9 by collecting those elements of the list of integers 1, 2, …, 10 for which the predicateeven
returns the Boolean value false (with.
being thefunction composition operator).
Below, you can see a view of each step of the filter process for a list of integersX = [0, 5, 8, 3, 2, 1]
according to the function :
This function express that if is even the return value is, otherwise it's. This is the predicate.
Filter is a standard function for manyprogramming languages, e.g.,Haskell,[1]OCaml,[2]Standard ML,[3]orErlang.[4]Common Lisp provides the functionsremove-if
andremove-if-not
.[5]Scheme Requests for Implementation (SRFI) 1 provides an implementation of filter for the languageScheme.[6]C++ provides thealgorithmsremove_if
(mutating) andremove_copy_if
(non-mutating);C++11 additionally providescopy_if
(non-mutating).[7]Smalltalk provides theselect:
method for collections. Filter can also be realized usinglist comprehensions in languages that support them.
In Haskell,filter
can be implemented like this:
filter::(a->Bool)->[a]->[a]filter_[]=[]filterp(x:xs)=[x|px]++filterpxs
Here,[]
denotes the empty list,++
the list concatenation operation, and[x | p x]
denotes a list conditionally holding a value,x
, if the conditionp x
holds (evaluates toTrue
).
Language | Filter | Notes |
---|---|---|
APL | (predarray)/array or pred | The second example is an APLdop. |
C# 3.0 | ienum.Where(pred) or The where clause | Where is an extension method ienum is an IEnumerable Similarly in all .NET languages |
CFML | obj.filter(func) | Whereobj is an array or a structure. Thefunc receives as an argument each element's value. |
Clojure | (filterpredicatelist)[8] | Or, vialist comprehension:(for [xlist :when (pred x)] x) |
Common Lisp | (remove-ifinverted-predlist) | The functionremove-if-not has been deprecated[5] in favor of the equivalentremove-if where the predicate is complemented.[9] Thus the filter(remove-if-not#'oddp'(0123)) should be written(remove-if(complement#'oddp)'(0123)) or more simply:(remove-if#'evenp'(0123)) whereevenp returns the inverted value ofoddp .[10] |
C++ | std::remove_copy_if(begin,end,result,prednot) | in header <algorithm> begin,end,result are iterators predicate is reversed |
D | std.algorithm.filter!(pred)(list) | |
Erlang | lists:filter(Fun,List) | Or, vialist comprehension:[ X || X <- List, Fun(X) ] |
Groovy | list.findAll(pred) | |
Haskell | filterpredlist | Or, vialist comprehension:[x | x <-list,pred x] |
Haxe | list.filter(pred) Lambda.filter(list,pred) | Or, vialist comprehension:[x | x <-list,pred x] |
J | (#~pred)list | An example of a monadic hook. # is copy, ~ reverses arguments.(f g) y = y f (g y) |
Julia | filter(pred,array) | The filter function also acceptsdict datatype. Or, vialist comprehension:[x forx inarray ifpred(x)] |
Java 8+ | stream.filter(pred) | |
JavaScript 1.6 | array.filter(pred) | |
Kotlin | array.filter(pred) | |
Mathematica | Select[list,pred] | |
Objective-C (Cocoa in MacOS X 10.4+) | [array filteredArrayUsingPredicate:pred] | pred is anNSPredicate object, which may be limited in expressiveness |
F#,OCaml,Standard ML | List.filterpredlist | |
PARI/GP | select(expr,list) | The order of arguments is reversed in v. 2.4.2. |
Perl | grepblocklist | |
PHP | array_filter(array,pred) | |
Prolog | filter(+Closure,+List,-List) | Since ISO/IEC 13211-1:1995/Cor.2:2012[11] the core standard contains closure application viacall/N [12] |
Python | filter(func,list) | Or, vialist comprehension:[x for x inlist ifpred(x)] . In Python 3,filter was changed to return aniterator rather than a list.[13] The complementary functionality, returning an iterator over elements for which the predicate is false, is also available in the standard library asfilterfalse in theitertools module. |
Ruby | enum.find_all {block} | enum is an Enumeration |
Rust | iterator.filter(pred) | iterator is anIterator and thefilter method returns a new iterator;pred is a function (specificallyFnMut ) that receives the iterator's item and returns abool |
S,R | Filter(pred,array) | In the second case,pred must be a vectorized function |
Scala | list.filter(pred) | Or, via for-comprehension:for(x <-list; ifpred) yield x |
Scheme R6RS | (filterpredlist) (removeinverted predlist) (partitionpredlistlist) | |
Smalltalk | aCollection select:aBlock | |
Swift | array.filter(pred) | |
XPath,XQuery | list[block] filter(list, func) | Inblock the context item. holds the current value |
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., HaskelldropWhile
[14] andpartition
[15]) are also common. A commonmemory optimization forpurely functional programming languages is to have the input list and filtered result share the longest common tail (tail-sharing).
filter
in the Haskell Standard Preludefilter
in theOCaml standard library modulelist
filter/2
in the Erlang STDLIB Reference Manual documentation of the modulelists
filter
in SRFI 1remove_if
andremove_copy_if
in the SGIStandard Template Library (STL) spec