Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Filter (higher-order function)

From Wikipedia, the free encyclopedia
Computer programming function

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.

Example

[edit]

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

Visual example

[edit]

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 :f(x)={True if x0(mod2)False if x1(mod2).{\displaystyle 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 ifx{\displaystyle x} is even the return value isTrue{\displaystyle \mathrm {True} }, otherwise it'sFalse{\displaystyle \mathrm {False} }. This is the predicate.

applying filter function processing steps
View of processing steps when applying filter function on a list

Language comparison

[edit]

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

Filter in various languages
LanguageFilterNotes
APL(predarray)/array
or
pred{/⍨⍺⍺}array
The second example is an APLdop.
C# 3.0ienum.Where(pred)
or
Thewhere clause
Where is an extension method
ienum is an IEnumerable
Similarly in all .NET languages
CFMLobj.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)
(remove-if (complementpred)list)
(remove-if-notpredlist)
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)
std::copy_if(begin,end,result,pred) (C++11)
in header <algorithm>
begin,end,result are iterators
predicate is reversed
Dstd.algorithm.filter!(pred)(list)
Erlanglists:filter(Fun,List)Or, vialist comprehension:[ X || X <- List, Fun(X) ]
Groovylist.findAll(pred)
HaskellfilterpredlistOr, vialist comprehension:[x | x <-list,pred x]
Haxelist.filter(pred)
Lambda.filter(list,pred)
Or, vialist comprehension:[x | x <-list,pred x]
J(#~pred)listAn example of a monadic hook. # is copy, ~ reverses arguments.(f g) y = y f (g y)
Juliafilter(pred,array)The filter function also acceptsdict datatype. Or, vialist comprehension:[x forx inarray ifpred(x)]
Java 8+stream.filter(pred)
JavaScript 1.6array.filter(pred)
Kotlinarray.filter(pred)
MathematicaSelect[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 MLList.filterpredlist
PARI/GPselect(expr,list)The order of arguments is reversed in v. 2.4.2.
Perlgrepblocklist
grepexpr,list
PHParray_filter(array,pred)
Prologfilter(+Closure,+List,-List)Since ISO/IEC 13211-1:1995/Cor.2:2012[11] the core standard contains closure application viacall/N[12]
Pythonfilter(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.
Rubyenum.find_all {block}
enum.select {block}
enum is an Enumeration
Rustiterator.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,RFilter(pred,array)
array[pred(array)]
In the second case,pred must be a vectorized function
Scalalist.filter(pred)Or, via for-comprehension:for(x <-list; ifpred) yield x
Scheme R6RS(filterpredlist)
(removeinverted predlist)
(partitionpredlistlist)
SmalltalkaCollection select:aBlock
Swiftarray.filter(pred)
filter(sequence,pred)
XPath,XQuerylist[block]
filter(list, func)
Inblock the context item. holds the current value

Variants

[edit]

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

See also

[edit]

References

[edit]
  1. ^filter in the Haskell Standard Prelude
  2. ^filter in theOCaml standard library modulelist
  3. ^"The List structure".The Standard ML Basis Library. Retrieved2007-09-25.
  4. ^filter/2 in the Erlang STDLIB Reference Manual documentation of the modulelists
  5. ^abFunctionREMOVE, REMOVE-IF, REMOVE-IF-NOT, DELETE, DELETE-IF, DELETE-IF-NOT in theCommon Lisp HyperSpec
  6. ^filter in SRFI 1
  7. ^remove_if andremove_copy_if in the SGIStandard Template Library (STL) spec
  8. ^clojure.core/filter on ClojureDocs
  9. ^FunctionCOMPLEMENT in theCommon Lisp HyperSpec
  10. ^FunctionEVENP, ODDP in theCommon Lisp HyperSpec
  11. ^ISO/IEC 13211-1:1995/Cor 2:2012
  12. ^"Draft technical corrigendum 2".
  13. ^"Built-in Functions — Python 3.9.0 documentation".docs.python.org. Retrieved2020-10-28.
  14. ^Haskell filterdropWhile
  15. ^Haskell filterpartition
Retrieved from "https://en.wikipedia.org/w/index.php?title=Filter_(higher-order_function)&oldid=1291975447"
Category:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp