Filter (functional programming)

A filter, in functional programming, is usually used to test each element of a list. A built-in variable, also known as a predicate (often typed out as "pred"), may represent each element being tested. If the boolean test result was true, those elements become part of a new list.

Depending on the language, the code can be arranged differently. <syntaxhighlight lang="text" enclose="none">filter pred list</syntaxhighlight>; in Haskell[1] and Scheme.[2] <syntaxhighlight lang="text" enclose="none">filter(pred, array)</syntaxhighlight>; in Julia, Python,[3] PHP, and R. <syntaxhighlight lang="text" enclose="none">array.filter(pred)</syntaxhighlight>; in JavaScript, Kotlin, and V (Vlang).[4]

Examples

In the below, <syntaxhighlight lang="text" enclose="none">even</syntaxhighlight> and <syntaxhighlight lang="text" enclose="none">it</syntaxhighlight> are predicates. Filter is used to create a new array.

<syntaxhighlight lang="haskell"> array = [1, 2, 3, 4, 5, 6] filter (even) array -- [2, 4, 6] </syntaxhighlight>

<syntaxhighlight lang="c"> array := [1, 2, 3, 4, 5, 6] new_array := array.filter(it % 2 == 0) // [2, 4, 6] </syntaxhighlight>

References

  1. filter in the Haskell Standard Prelude
  2. filter in SRFI 1
  3. "Built-in Functions — Python 3.9.0 documentation". docs.python.org. Retrieved 2020-10-28.
  4. Rao, Navule Pavan Kumar (December 10, 2021). Getting Started with V Programming. pp. 100–101. ASIN B09FKK3JL7. ISBN 978-1839213434. OCLC 1290492862.