Filter (higher-order function)
Encyclopedia
In functional programming
, filter is a higher-order function
that processes a data structure
(typically 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 true.
, the code example
filter even [1..10]
evaluates to the list 2, 4,…10 by applying the predicate
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 predicate
s, e.g.
Haskell,
Objective Caml
,
Standard ML
,
or Erlang.
Common Lisp
provides the functions
SRFI 1
provides an implementation of filter for the Scheme programming language
.
Smalltalk
provides the
In Haskell,
filter :: (a -> Bool) -> [a] -> [a]
filter _ [] = []
filter p (x:xs) | p x = x : filter p xs
| otherwise = filter p xs
Here,
programming languages is to have the input list and filtered result share the longest common tail (tail-sharing).
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...
, filter is a higher-order function
Higher-order function
In mathematics and computer science, higher-order functions, functional forms, or functionals are functions which do at least one of the following:*take one or more functions as an input*output a function...
that processes a data structure
Data structure
In computer science, a data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently.Different kinds of data structures are suited to different kinds of applications, and some are highly specialized to specific tasks...
(typically 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 true.
Example
In HaskellHaskell (programming language)
Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...
, the code example
filter even [1..10]
evaluates to the list 2, 4,…10 by applying the predicate
even
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 examplefilter (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 predicate
even
returns the boolean value false (with .
being the function composition operator).Implementation
Filter is a standard function for many programming languageProgramming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....
s, e.g.
Haskell,
Objective Caml
Objective Caml
OCaml , originally known as Objective Caml, is the main implementation of the Caml programming language, created by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy and others in 1996...
,
Standard ML
Standard ML
Standard ML is a general-purpose, modular, functional programming language with compile-time type checking and type inference. It is popular among compiler writers and programming language researchers, as well as in the development of theorem provers.SML is a modern descendant of the ML...
,
or Erlang.
Common Lisp
Common Lisp
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...
provides the functions
remove-if
and remove-if-not
.SRFI 1
Scheme Requests for Implementation
Scheme Requests for Implementation is an effort to coordinate libraries and extensions of standard Scheme, necessitated by Scheme's minimalistic design, and particularly the lack of a standard library prior to R6RS...
provides an implementation of filter for the Scheme programming language
Scheme programming language
Scheme is one of the two main dialects of the programming language Lisp. Unlike Common Lisp, the other main dialect, Scheme follows a minimalist design philosophy specifying a small standard core with powerful tools for language extension. Its compactness and elegance have made it popular with...
.
Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...
provides the
select:
method for collections. Filter can also be realized using list comprehensions in languages that support them.In Haskell,
filter
can be implemented like this:filter :: (a -> Bool) -> [a] -> [a]
filter _ [] = []
filter p (x:xs) | p x = x : filter p xs
| otherwise = filter p xs
Here,
[]
denotes the empty list, and :
denotes the concatenation operator used to create a new list from a given value and an existing list.Language | Filter | Notes | |
---|---|---|---|
C# 3.0 | ienum.Where(pred) | Where is an extension method ienum is an IEnumerable Similarly in all .NET languages |
|
Common Lisp Common Lisp Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers... |
(remove-if inverted-pred list) (remove-if (complement pred) list) (remove-if-not pred list) |
The function remove-if-not has been deprecated in favor of the equivalent remove-if where the predicate is complemented. Thus the filter (remove-if-not #'oddp '(0 1 2 3)) should be written (remove-if (complement #'oddp) '(0 1 2 3)) or more simply: (remove-if #'evenp '(0 1 2 3)) where evenp returns the inverted value of oddp. | |
D D (programming language) The D programming language is an object-oriented, imperative, multi-paradigm, system programming language created by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++... |
std.algorithm.filter!(pred)(list) | ||
Erlang | lists:filter(Fun, List) | Or, via list comprehension: [ X |
X <- List, Fun(X) ] |
Haskell Haskell (programming language) Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the... |
filter pred list | > x <- list, pred x] | |
J J (programming language) The J programming language, developed in the early 1990s by Kenneth E. Iverson and Roger Hui, is a synthesis of APL and the FP and FL function-level languages created by John Backus.... |
(#~ pred) list | An example of a monadic hook. # is copy, ~ reverses arguments. (f g) y = y f (g y) | |
JavaScript JavaScript JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles.... 1.6 |
array.filter(pred) | ||
Mathematica Mathematica Mathematica is a computational software program used in scientific, engineering, and mathematical fields and other areas of technical computing... |
Select[list, pred] | ||
Objective-C Objective-C Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it... (Cocoa Cocoa (API) Cocoa is Apple's native object-oriented application programming interface for the Mac OS X operating system and—along with the Cocoa Touch extension for gesture recognition and animation—for applications for the iOS operating system, used on Apple devices such as the iPhone, the iPod Touch, and... in Mac OS X Mac OS X Mac OS X is a series of Unix-based operating systems and graphical user interfaces developed, marketed, and sold by Apple Inc. Since 2002, has been included with all new Macintosh computer systems... 10.4+) |
[array filteredArrayUsingPredicate:pred] | pred is an NSPredicate object, which may be limited in expressiveness | |
OCaml, Standard ML Standard ML Standard ML is a general-purpose, modular, functional programming language with compile-time type checking and type inference. It is popular among compiler writers and programming language researchers, as well as in the development of theorem provers.SML is a modern descendant of the ML... |
List.filter pred list | ||
PHP PHP PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document... |
array_filter(array, pred) | ||
Perl Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular... |
grep block list grep expr, list |
||
Python Python (programming language) Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive... |
filter(func, list) | Or, via list comprehension: [x for x in list if pred(x)] | |
Ruby Ruby (programming language) Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto... |
enum.find_all {block} enum.select {block} |
enum is an Enumeration | |
S/R R (programming language) R is a programming language and software environment for statistical computing and graphics. The R language is widely used among statisticians for developing statistical software, and R is widely used for statistical software development and data analysis.... |
Filter(pred,array) array[pred(array)] |
In the second case, pred must be a vectorized function | |
Scala | list.filter(pred) | Or, via for-comprehension: for(x <- list; if pred) yield x | |
Scheme R6RS, Clojure Clojure Clojure |closure]]") is a recent dialect of the Lisp programming language created by Rich Hickey. It is a general-purpose language supporting interactive development that encourages a functional programming style, and simplifies multithreaded programming.... |
(filter pred list) | ||
Smalltalk Smalltalk Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist... |
aCollection select: aBlock |
Variants
Filter creates its result without modifying the original list. Many programming languages also provide variants that destructively modify the list argument instead for performance reasons. Other variants of filter (like e.g.dropWhile
and partition
) are also common. A common memory optimization for purely functionalPurely functional
Purely functional is a term in computing used to describe algorithms, data structures or programming languages that exclude destructive modifications...
programming languages is to have the input list and filtered result share the longest common tail (tail-sharing).