Filter: Difference between revisions

7,335 bytes added ,  1 year ago
m
syntax highlighting fixup automation
m (→‎{{header|NGS}}: Cosmetics)
m (syntax highlighting fixup automation)
Line 14:
=={{header|11l}}==
 
<langsyntaxhighlight lang="11l">V array = Array(1..10)
V even = array.filter(n -> n % 2 == 0)
print(even)</langsyntaxhighlight>
 
{{out}}
Line 24:
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun filter-evens (xs)
(cond ((endp xs) nil)
((evenp (first xs))
(cons (first xs) (filter-evens (rest xs))))
(t (filter-evens (rest xs)))))</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE PTR="CARD"
 
INT value ;used in predicate
Line 138:
PrintE("Select all non negative numbers:")
PrintArray(src,srcSize)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Filter.png Screenshot from Atari 8-bit computer]
Line 162:
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang="actionscript">var arr:Array = new Array(1, 2, 3, 4, 5);
var evens:Array = new Array();
for (var i:int = 0; i < arr.length(); i++) {
if (arr[i] % 2 == 0)
evens.push(arr[i]);
}</langsyntaxhighlight>
 
'''Actionscript 3'''
<langsyntaxhighlight lang="actionscript">var arr:Array = new Array(1, 2, 3, 4, 5);
arr = arr.filter(function(item:int, index:int, array:Array) {
return item % 2 == 0;
});
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Text_Io; use Ada.Text_Io;
 
Line 208:
begin
Print(Evens(Foo));
end Array_Selection;</langsyntaxhighlight>
Here is a non-recursive solution:
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Array_Selection is
Line 237:
Put (Evens ((1,2,3,4,5,6,7,8,9,10)));
New_Line;
end Array_Selection;</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer
even(integer e)
{
Line 290:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre> 0 2 4 6 8</pre>
Line 298:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<langsyntaxhighlight lang="algol68">MODE TYPE = INT;
 
PROC select = ([]TYPE from, PROC(TYPE)BOOL where)[]TYPE:
Line 320:
 
# Or as a simple one line query #
print((select((1,4,9,16,25,36,49,64,81,100), (TYPE x)BOOL: NOT ODD x ), new line))</langsyntaxhighlight>
{{out}}
<pre>
Line 331:
In the sample below, the ''select'' procedure's parameters do not include the parameters of ''where'' - they are commented out.<br>
Recent compilers (such as Awe) require the parameter types be specified and so the parameters to ''where'' should be uncommented when compilling with Awe.
<langsyntaxhighlight lang="algolw">begin
% sets the elements of out to the elements of in that return true from applying the where procedure to them %
% the bounds of in must be 1 :: inUb - out must be at least as big as in and the number of matching %
Line 357:
write()
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 364:
 
=={{header|AmigaE}}==
<langsyntaxhighlight lang="amigae">PROC main()
DEF l : PTR TO LONG, r : PTR TO LONG, x
l := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Line 370:
SelectList({x}, l, r, `Mod(x,2)=0)
ForAll({x}, r, `WriteF('\d\n', x))
ENDPROC</langsyntaxhighlight>
 
=={{header|AntLang}}==
<langsyntaxhighlight AntLanglang="antlang">x:range[100]
{1- x mod 2}hfilter x</langsyntaxhighlight>
 
=={{header|Apex}}==
<langsyntaxhighlight Apexlang="apex">List<Integer> integers = new List<Integer>{1,2,3,4,5};
Set<Integer> evenIntegers = new Set<Integer>();
for(Integer i : integers)
Line 391:
system.assert(!evenIntegers.contains(3), '3 should not be a number in the set');
system.assert(evenIntegers.contains(4), '4 should be a number in the set');
system.assert(!evenIntegers.contains(5), '5 should not be a number in the set');</langsyntaxhighlight>
 
=={{header|APL}}==
<langsyntaxhighlight APLlang="apl"> (0=2|x)/x←⍳20
2 4 6 8 10 12 14 16 18 20</langsyntaxhighlight>
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">set array to {1, 2, 3, 4, 5, 6}
set evens to {}
repeat with i in array
if (i mod 2 = 0) then set end of evens to i's contents
end repeat
return evens</langsyntaxhighlight>Result is (a list):<pre>{2, 4, 6}</pre>
 
Here's how you might implement a more generic filter, passing a script object to represent the test that elements must pass (obviously overkill for this simple example):
 
<langsyntaxhighlight AppleScriptlang="applescript">to filter(inList, acceptor)
set outList to {}
repeat with anItem in inList
Line 423:
end script
 
filter({1,2,3,4,5,6}, isEven)</langsyntaxhighlight>
 
 
Line 435:
This allows for context-sensitive filters, which can take account of following or preceding elements in a sequence.
 
<langsyntaxhighlight AppleScriptlang="applescript">-------------------------- FILTER --------------------------
 
-- filter :: (a -> Bool) -> [a] -> [a]
Line 477:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<pre>{0, 2, 4, 6, 8, 10}</pre>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">arr: [1 2 3 4 5 6 7 8 9 10]
 
print select arr [x][even? x]</langsyntaxhighlight>
 
{{out}}
Line 491:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">array = 1,2,3,4,5,6,7
loop, parse, array, `,
{
Line 542:
 
 
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
Line 550:
 
'''One-liner:'''
<langsyntaxhighlight lang="awk">$ awk 'BEGIN{split("1 2 3 4 5 6 7 8 9",a);for(i in a)if(!(a[i]%2))r=r" "a[i];print r}'</langsyntaxhighlight>
{{out}}
<pre>4 6 8 2</pre>
 
'''Regular script:'''
<langsyntaxhighlight lang="awk">
BEGIN {
split("1 2 3 4 5 6 7 8 9",a);
Line 561:
print r
}
</syntaxhighlight>
</lang>
Same output.
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">
@echo off
setlocal enabledelayedexpansion
Line 624:
set /a length+=1
goto lengthloop
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 636:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> REM Create the test array:
items% = 1000
DIM array%(items%)
Line 669:
END
 
DEF FNfilter(A%) = ((A% AND 1) = 0)</langsyntaxhighlight>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
// Copy every value for which p(x) is true from in to out
Line 711:
writevec(arr, len)
wrch('*N')
$)</langsyntaxhighlight>
{{out}}
<pre>Numbers: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Line 718:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( :?odds
& ( 1 2 3 4 5 6 7 8 9 10 16 25 36 49 64 81 100:? (=.!sjt*1/2:/&!odds !sjt:?odds)$() ()
| !odds
)
)
</syntaxhighlight>
</lang>
<pre>1 3 5 7 9 25 49 81</pre>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">#Prints [2, 4, 6, 8, 10]
p 1.to(10).select { x | x % 2 == 0 }</langsyntaxhighlight>
 
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
blsq ) 1 13r@{2.%n!}f[
{2 4 6 8 10 12}
</syntaxhighlight>
</lang>
 
=={{header|BQN}}==
Line 741:
General filtering is done using the <code>/</code>(Replicate) function, which can fliter elements given a bitmask. We can make a modifier based on it to accept a function for filtering.
 
<langsyntaxhighlight lang="bqn">_filter ← {(𝔽𝕩)/𝕩}
Odd ← 2⊸|
 
Odd _filter 1‿2‿3‿4‿5</langsyntaxhighlight>
<syntaxhighlight lang="text">⟨ 1 3 5 ⟩</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 790:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Filtered even: 2 4 6 8 10
Line 797:
=={{header|C sharp|C#}}==
{{works with|.NET|1.1}}
<langsyntaxhighlight lang="csharp">ArrayList array = new ArrayList( new int[] { 1, 2, 3, 4, 5 } );
ArrayList evens = new ArrayList();
foreach( int i in array )
Line 805:
}
foreach( int i in evens )
System.Console.WriteLine( i.ToString() );</langsyntaxhighlight>
{{works with|.NET|2.0}}
<langsyntaxhighlight lang="csharp">List<int> array = new List<int>( new int[] { 1, 2, 3, 4, 5 } );
List<int> evens = array.FindAll( delegate( int i ) { return (i%2)==0; } );
foreach( int i in evens )
System.Console.WriteLine( i.ToString() );</langsyntaxhighlight>
{{works with|.NET|3.5}}
<langsyntaxhighlight lang="csharp">IEnumerable<int> array = new List<int>( new int[] { 1, 2, 3, 4, 5 } );
IEnumerable<int> evens = array.Where( delegate( int i ) { return (i%2)==0; } );
foreach( int i in evens )
System.Console.WriteLine( i.ToString() );</langsyntaxhighlight>
Replacing the delegate with the more concise lambda expression syntax.
<langsyntaxhighlight lang="csharp">int[] array = { 1, 2, 3, 4, 5 };
int[] evens = array.Where(i => (i % 2) == 0).ToArray();
 
foreach (int i in evens)
Console.WriteLine(i);</langsyntaxhighlight>
 
=={{header|C++}}==
 
<langsyntaxhighlight lang="cpp">#include <vector>
#include <algorithm>
#include <functional>
Line 842:
 
return 0;
}</langsyntaxhighlight>
 
 
{{works with|C++11}}
<langsyntaxhighlight lang="cpp">#include <vector>
#include <algorithm>
#include <iterator>
Line 862:
// print result
copy(evens.begin(), evens.end(), ostream_iterator<int>(cout, "\n"));
}</langsyntaxhighlight>
 
=={{header|Clean}}==
The standard environment is required for list and array comprehensions. We specify the types of the functions because array comprehensions are overloaded. Clean provides lazy, strict, and unboxed arrays.
 
<langsyntaxhighlight lang="clean">module SelectFromArray
 
import StdEnv</langsyntaxhighlight>
 
Create a lazy array where each element comes from the list 1 to 10.
 
<langsyntaxhighlight lang="clean">array :: {Int}
array = {x \\ x <- [1 .. 10]}</langsyntaxhighlight>
 
Create (and print) a strict array where each element (coming from another array) is even.
 
<langsyntaxhighlight lang="clean">Start :: {!Int}
Start = {x \\ x <-: array | isEven x}</langsyntaxhighlight>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="lisp">;; range and filter create lazy seq's
(filter even? (range 0 100))
;; vec will convert any type of seq to an array
(vec (filter even? (vec (range 0 100))))</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffee">[1..10].filter (x) -> not (x%2)</langsyntaxhighlight>
 
{{out}}
Line 903:
In this example, the goal is to find the even numbers. The most straight-forward function is to use remove-if-not, which removes elements from the list that does ''not'' pass the predicate. The predicate, in this case, tests to see if an element is even. Therefore, the remove-if-not acts like a filter:
 
<langsyntaxhighlight lang="lisp">(remove-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10))
> (2 4 6 8 10)</langsyntaxhighlight>
 
However, this function is non-destructive, meaning the function creates a brand new list. This might be too prohibitive for very large lists.
Line 911:
There is a destructive version that modifies the list in-place:
 
<langsyntaxhighlight lang="lisp">(delete-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10))
> (2 4 6 8 10)</langsyntaxhighlight>
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
# Cowgol has strict typing and there are no templates either.
Line 986:
i := i + 1;
end loop;
print_nl();</langsyntaxhighlight>
{{out}}
<pre>2 4 6 8 10
Line 992:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.algorithm: filter, equal;
 
Line 998:
auto evens = data.filter!(x => x % 2 == 0); // Lazy.
assert(evens.equal([2, 4, 6, 8, 10]));
}</langsyntaxhighlight>
===Tango Version===
{{libheader|Tango}}
<langsyntaxhighlight lang="d">import tango.core.Array, tango.io.Stdout;
 
void main() {
Line 1,010:
Stdout("Evens - ")( array[0 .. evens] ).newline; // The order of even elements is preserved
Stdout("Odds - ")( array[evens .. $].sort ).newline; // Unlike odd elements
}</langsyntaxhighlight>
{{out}}
<pre> Evens - [ 2, 4, 6, 8, 10 ]
Line 1,017:
=={{header|Delphi}}==
===Hand-coded version===
<langsyntaxhighlight Delphilang="delphi">program FilterEven;
 
{$APPTYPE CONSOLE}
Line 1,041:
Write(i:3);
Writeln;
end.</langsyntaxhighlight>
 
 
Line 1,050:
{{libheader| Types}}
{{libheader| Boost.Int}}
<langsyntaxhighlight Delphilang="delphi">program FilterEven;
 
{$APPTYPE CONSOLE}
Line 1,085:
Writeln('[' + Source.Comma + ']');
End.
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,096:
 
===Non-destructively===
<langsyntaxhighlight Dyalectlang="dyalect">func Array.Filter(pred) {
var arr = []
for x in this when pred(x) {
Line 1,105:
 
var arr = [1..20].Filter(x => x % 2 == 0)
print(arr)</langsyntaxhighlight>
 
{{out}}
Line 1,112:
 
===Destructively===
<langsyntaxhighlight Dyalectlang="dyalect">func Array.Filter(pred) {
var i = 0
while i < this.Length() {
Line 1,124:
var arr = [1..20]
arr.Filter(x => x % 2 == 0)
print(arr)</langsyntaxhighlight>
 
{{out}}
Line 1,134:
Idiomatic approach in Dy is to use non-strict iterators (which can be combined without intermedate data structures) and translate the result to an array if needed:
 
<langsyntaxhighlight Dyalectlang="dyalect">var xs = [1..20]
var arr = xs.Iterate().Filter(x => x % 2 == 0).Map(x => x.ToString())
print(arr.ToArray())</langsyntaxhighlight>
 
{{out}}
Line 1,145:
 
===Non-destructively===
<langsyntaxhighlight lang="dejavu">filter pred lst:
]
for value in copy lst:
Line 1,155:
= 0 % x 2
 
!. filter @even [ 0 1 2 3 4 5 6 7 8 9 ]</langsyntaxhighlight>
 
{{out}}
Line 1,162:
 
===Destructively===
<langsyntaxhighlight lang="dejavu">local :lst [ 0 1 2 3 4 5 6 7 8 9 ]
 
filter-destructively pred lst:
Line 1,177:
filter-destructively @even lst
 
!. lst</langsyntaxhighlight>
 
{{out}}
Line 1,187:
There are several ways this could be done.
 
<langsyntaxhighlight lang="e">pragma.enable("accumulator")
accum [] for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] { _.with(x) }</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">var result := []
for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] {
result with= x
}
result</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">def makeSeries := <elang:control.makeSeries>
makeSeries([1,2,3,4,5,6,7,8,9,10]).filter(fn x,_{x %% 2 <=> 0}).asList()</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">a[] = [ 1 2 3 4 5 6 7 8 9 ]
for i range len a[]
if a[i] mod 2 = 0
Line 1,207:
.
.
print b[]</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(iota 12) → { 0 1 2 3 4 5 6 7 8 9 10 11 }
 
Line 1,228:
→ (0 2 4 6 8 10 12 14 16 18 20 22)
 
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
Line 1,234:
===Using higher-order function (non-strict version)===
 
<langsyntaxhighlight lang="ela">open list
 
evenList = filter' (\x -> x % 2 == 0) [1..]</langsyntaxhighlight>
 
===Using comprehension (non-strict version)===
 
<langsyntaxhighlight lang="ela">evenList = [& x \\ x <- [1..] | x % 2 == 0]</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 5.0 :
<langsyntaxhighlight lang="elena">import system'routines;
import system'math;
import extensions;
Line 1,256:
 
evens.forEach:printingLn
}</langsyntaxhighlight>
Using strong typed collections and extensions:
<langsyntaxhighlight lang="elena">import system'collections;
import system'routines'stex;
import system'math;
Line 1,270:
.filterBy:(int n => n.mod:2 == 0)
.forEach:(int i){ console.printLine(i) }
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,278:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">iex(10)> numbers = Enum.to_list(1..9)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
iex(11)> Enum.filter(numbers, fn x -> rem(x,2)==0 end)
[2, 4, 6, 8]
iex(12)> for x <- numbers, rem(x,2)==0, do: x # comprehension
[2, 4, 6, 8]</langsyntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">Numbers = lists:seq(1, 5).
EvenNumbers = lists:filter(fun (X) -> X rem 2 == 0 end, Numbers).</langsyntaxhighlight>
 
Or using a list comprehension:
 
<langsyntaxhighlight lang="erlang">EvenNumbers = [X || X <- Numbers, X rem 2 == 0].</langsyntaxhighlight>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">sequence s, evens
s = {1, 2, 3, 4, 5, 6}
evens = {}
Line 1,302:
end if
end for
? evens</langsyntaxhighlight>
 
{{out}}
Line 1,309:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let lst = [1;2;3;4;5;6]
List.filter (fun x -> x % 2 = 0) lst;;
 
val it : int list = [2; 4; 6]</langsyntaxhighlight>
 
=={{header|Factor}}==
Line 1,318:
This code uses ''filter'' on an array.
 
<langsyntaxhighlight lang="factor">10 <iota> >array [ even? ] filter .
! prints { 0 2 4 6 8 }</langsyntaxhighlight>
 
''10 <iota>'' is already a sequence, so we can skip the conversion to array.
 
<langsyntaxhighlight lang="factor">10 <iota> [ even? ] filter .
! prints V{ 0 2 4 5 8 }</langsyntaxhighlight>
 
=== Destructive ===
This uses ''filter!'' to modify the original vector.
 
<langsyntaxhighlight lang="factor">USE: vectors
10 <iota> >vector [ even? ] filter! .
! prints V{ 0 2 4 5 8 }</langsyntaxhighlight>
 
To prove that ''filter!'' is destructive but ''filter'' is non-destructive, I assign the original vector to ''v''.
 
<langsyntaxhighlight lang="factor">USE: locals
10 <iota> >vector [| v |
v [ even? ] filter drop
Line 1,343:
] call
! V{ 0 1 2 3 4 5 6 7 8 9 } after filter
! V{ 0 2 4 6 8 } after filter!</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,359:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: sel ( dest 0 test src len -- dest len )
cells over + swap do ( dest len test )
i @ over execute if
Line 1,377:
: even? ( n -- ? ) 1 and 0= ;
 
evens 0 ' even? nums 6 sel .array \ 2 4 6</langsyntaxhighlight>
 
=={{header|Fortran}}==
 
<langsyntaxhighlight lang="fortran">module funcs
implicit none
contains
Line 1,389:
iseven = mod(x, 2) == 0
end function iseven
end module funcs</langsyntaxhighlight>
 
<langsyntaxhighlight lang="fortran">program Filter
use funcs
implicit none
Line 1,433:
end function filterwith
 
end program Filter</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Type FilterType As Function(As Integer) As Boolean
Line 1,498:
End
 
Data 1, 2, 3, 7, 8, 10, 11, 16, 19, 21, 22, 27</langsyntaxhighlight>
 
{{out}}
Line 1,508:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
b = array[1 to 100]
c = select[b, {|x| x mod 2 == 0}]
</syntaxhighlight>
</lang>
 
=={{header|Futhark}}==
{{incorrect|Futhark|Futhark's syntax has changed, so this example will not compile}}
 
<syntaxhighlight lang="futhark">
<lang Futhark>
fun main(as: []int): []int =
filter (fn x => x%2 == 0) as
</syntaxhighlight>
</lang>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=e73bc5db1e3bb56c598f89aa669a0825 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">sRandom As New String[]
'______________________________________________________________________________________________________
Public Sub Main()
Line 1,565:
Print sRandom.join(",")
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,574:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Built-in
 
Filtered([1 .. 100], IsPrime);
Line 1,583:
 
Filtered([1 .. 10], IsOddInt);
# [ 1, 3, 5, 7, 9 ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,625:
}
*pa = a[:last]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,636:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy"> def evens = [1, 2, 3, 4, 5].findAll{it % 2 == 0}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 1,642:
In Haskell, a list is often more basic than an array:
 
<langsyntaxhighlight lang="haskell">ary = [1..10]
evens = [x | x <- ary, even x]</langsyntaxhighlight>
or
<langsyntaxhighlight lang="haskell">evens = filter even ary</langsyntaxhighlight>
 
To do the same operation on an array, the simplest way it to convert it lazily into a list:
 
<langsyntaxhighlight lang="haskell">import Data.Array
 
ary = listArray (1,10) [1..10]
evens = listArray (1,n) l where
n = length l
l = [x | x <- elems ary, even x]</langsyntaxhighlight>
 
Note that the bounds must be known before creating the array, so the temporary list will be fully evaluated before the array is created.
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
 
every put(A := [],1 to 10) # make a list of 1..10
Line 1,668:
procedure iseven(x) #: return x if x is even or fail
if x % 2 = 0 then return x
end</langsyntaxhighlight>
 
=={{header|IDL}}==
The <tt>where()</tt> function can select elements on any logical expression. For example
 
<langsyntaxhighlight lang="idl">result = array[where(NOT array AND 1)]</langsyntaxhighlight>
 
=={{header|J}}==
'''Solution:'''<br>
With any verb (function) <code>f</code> that returns a boolean for each element of a vector <code>v</code>, the following is the generic solution:
<langsyntaxhighlight lang="j"> (#~ f) v</langsyntaxhighlight>
 
'''Examples:'''
<langsyntaxhighlight lang="j"> ] v=: 20 ?@$ 100 NB. vector of 20 random integers between 0 and 99
63 92 51 92 39 15 43 89 36 69 40 16 23 2 29 91 57 43 55 22
 
v #~ -.2| v
92 92 36 40 16 2 22</langsyntaxhighlight>
 
Or using the generic form suggested above:
<langsyntaxhighlight lang="j"> isEven=: 0 = 2&| NB. verb testing for even numbers
(#~ isEven) v
92 92 36 40 16 2 22</langsyntaxhighlight>
 
We might decide that we use this pattern so often that it is worthwhile creating a new adverb <code>select</code> that filters an array using the verb to its left.
<langsyntaxhighlight lang="j"> select=: adverb def '(#~ u)'
isPrime=: 1&p:
 
Line 1,701:
43 89 23 2 29 43
(isEven *. isPrime) select v
2</langsyntaxhighlight>
 
Destructive example:
 
<langsyntaxhighlight lang="j"> v=: isEven select v</langsyntaxhighlight>
 
(That said, note that in a highly parallel computing environment the destruction either happens after the filtering or you have to repeatedly stall the filtering to ensure that some sort of partially filtered result has coherency.)
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">int[] array = {1, 2, 3, 4, 5 };
List<Integer> evensList = new ArrayList<Integer>();
for (int i: array) {
if (i % 2 == 0) evensList.add(i);
}
int[] evens = evensList.toArray(new int[0]);</langsyntaxhighlight>
 
----
 
A Java 8 solution with stream and generic types:
<langsyntaxhighlight lang="java">public static <T> T[] filter(T[] input, Predicate<T> filterMethod) {
return Arrays.stream(input)
.filter(filterMethod)
.toArray(size -> (T[]) Array.newInstance(input.getClass().getComponentType(), size));
}</langsyntaxhighlight>
Methodcall:
<langsyntaxhighlight lang="java">Integer[] array = {1, 2, 3, 4, 5};
Integer[] result = filter(array, i -> (i % 2) == 0);</langsyntaxhighlight>
Warning: This solution works not with primitive types!<br/>
For arrays with a primitive type use the wrapper class.
 
=={{header|JavaFX Script}}==
<langsyntaxhighlight lang="javafx">def array = [1..100];
def evens = array[n | n mod 2 == 0];</langsyntaxhighlight>
 
=={{header|JavaScript}}==
===ES5===
The standard way is to use the [https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/filter Array.prototype.filter] function ({{works with|JavaScript|1.6}}):
<langsyntaxhighlight lang="javascript">var arr = [1,2,3,4,5];
var evens = arr.filter(function(a) {return a % 2 == 0});</langsyntaxhighlight>
 
Other ways:
<langsyntaxhighlight lang="javascript">var arr = [1,2,3,4,5];
var evens = [];
for (var i=0, ilen=arr.length; i<ilen; i++)
if (arr[i] % 2 == 0)
evens.push(arr[i]);</langsyntaxhighlight>
 
{{works with|Firefox|2.0}}
 
<langsyntaxhighlight lang="javascript">var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var evens = [i for (i in numbers) if (i % 2 == 0)];
 
Line 1,759:
}
 
var evens2 = [i for (i in range(100)) if (i % 2 == 0)];</langsyntaxhighlight>
 
{{libheader|Functional}}
<langsyntaxhighlight lang="javascript">Functional.select("+1&1", [1,2,3,4]) // [2, 4]</langsyntaxhighlight>
 
===ES6===
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,779:
 
// [2, 4, 6, 8]
})();</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[2, 4, 6, 8]</langsyntaxhighlight>
 
=={{header|jq}}==
jq's "select" filter is designed to make it easy to filter both arrays and streams:
<langsyntaxhighlight lang="jq">(1,2,3,4,5,6,7,8,9) | select(. % 2 == 0)</langsyntaxhighlight>
{{Out}}
2
Line 1,792:
6
8
<syntaxhighlight lang="jq">
<lang jq>
[range(1;10)] | map( select(. % 2 == 0) )
</syntaxhighlight>
</lang>
{{Out}}
[2,4,6,8]
Line 1,801:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">@show filter(iseven, 1:10)</langsyntaxhighlight>
 
{{out}}
Line 1,807:
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> / even is a boolean function
even:{0=x!2}
even 1 2 3 4 5
Line 1,821:
45 5 79 77 44 15 83 88 33 99
evens a
44 88</langsyntaxhighlight>
 
Alternative syntax:
<langsyntaxhighlight Klang="k"> {x[&0=x!2]}
{x[&even x]}</langsyntaxhighlight>
 
Destructive:
<langsyntaxhighlight Klang="k"> a:evens a
44 88</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.5-2
 
fun main(args: Array<String>) {
Line 1,844:
mutableList.retainAll { it % 2 == 0 }
println(mutableList.joinToString(" "))
}</langsyntaxhighlight>
 
{{out}}
Line 1,855:
=={{header|Lambdatalk}}==
 
<langsyntaxhighlight lang="scheme">
 
{def filter
Line 1,872:
-> 1 3 5 7 9 11 13 15 17 19
 
</syntaxhighlight>
</lang>
 
=={{header|Lang5}}==
<langsyntaxhighlight lang="lang5">: filter over swap execute select ;
10 iota "2 % not" filter . "\n" .
 
# [ 0 2 4 6 8 ]</langsyntaxhighlight>
 
=={{header|langur}}==
Line 1,884:
 
{{works with|langur|0.8.1}}
<langsyntaxhighlight lang="langur">val .arr = series 7
 
writeln " array: ", .arr
writeln "filtered: ", where f .x div 2, .arr</langsyntaxhighlight>
 
{{out}}
Line 1,894:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(original = array(1,2,3,4,5,6,7,8,9,10))
local(evens = (with item in #original where #item % 2 == 0 select #item) -> asstaticarray)
#evens</langsyntaxhighlight>
<pre>staticarray(2, 4, 6, 8, 10)</pre>
 
Modifying the original array
<langsyntaxhighlight lang=" lasso">local(original = array(1,2,3,4,5,6,7,8,9,10))
with item in #original where #item % 2 != 0 do #original ->removeall(#item)
#original</langsyntaxhighlight>
<pre>array(2, 4, 6, 8, 10)</pre>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">' write random nos between 1 and 100
' to array1 counting matches as we go
dim array1(100)
Line 1,926:
for n=1 to count
print array2(n)
next</langsyntaxhighlight>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="lisaac">+ a, b : ARRAY[INTEGER];
a := ARRAY[INTEGER].create_with_capacity 10 lower 0;
b := ARRAY[INTEGER].create_with_capacity 10 lower 0;
Line 1,939:
b.add_last item;
};
};</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to even? :n
output equal? 0 modulo :n 2
end
show filter "even? [1 2 3 4] ; [2 4]
 
show filter [equal? 0 modulo ? 2] [1 2 3 4]</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function filter(t, func)
local ret = {}
for i, v in ipairs(t) do
Line 1,960:
function even(a) return a % 2 == 0 end
 
print(unpack(filter({1, 2, 3, 4 ,5, 6, 7, 8, 9, 10}, even)))</langsyntaxhighlight>
 
The destructive version is even simpler, since tables are passed by reference:
 
<langsyntaxhighlight lang="lua">function filter(t, func)
for i, v in ipairs(t) do
if not func(v) then table.remove(t, i) end
Line 1,974:
local values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
filter(values, even)
print(unpack(values))</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
===Using Filter for arrays===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Print (1,2,3,4,5,6,7,8)#filter(lambda ->number mod 2=0)
}
Checkit
</syntaxhighlight>
</lang>
 
===Old style===
Line 1,996:
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Function GetEvenNumbers (A as array){
Line 2,048:
}
CheckIt
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
evennum:=proc(nums::list(integer))
return select(x->type(x, even), nums);
end proc;
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Check for even integers:
<langsyntaxhighlight Mathematicalang="mathematica">Select[{4, 5, Pi, 2, 1.3, 7, 6, 8.0}, EvenQ]</langsyntaxhighlight>
gives:
<syntaxhighlight lang Mathematica="mathematica">{4, 2, 6}</langsyntaxhighlight>
To check also for approximate number (like 8.0 in the example above) a possible solution is:
<langsyntaxhighlight Mathematicalang="mathematica">Select[{4, 5, Pi, 2, 1.3, 7, 6, 8.0}, Mod[#, 2] == 0 &]</langsyntaxhighlight>
gives:
<langsyntaxhighlight Mathematicalang="mathematica">{4, 2, 6, 8.}</langsyntaxhighlight>
notice that the function returns 8. not 8 (the dot indicates that it is a float number, not an integer).
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">function evens = selectEvenNumbers(list)
 
evens = list( mod(list,2) == 0 );
 
end</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight MATLABlang="matlab">>> selectEvenNumbers([0 1 2 3 4 5 6 7 8 9 10])
 
ans =
 
0 2 4 6 8 10</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">a: makelist(i, i, 1, 20);
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
 
Line 2,090:
 
sublist(a, lambda([n], mod(n, 3) = 0));
[3, 6, 9, 12, 15, 18]</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">arr = #(1, 2, 3, 4, 5, 6, 7, 8, 9)
newArr = for i in arr where (mod i 2 == 0) collect i</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<langsyntaxhighlight lang="min">(1 2 3 4 5 6 7 8 9 10) 'even? filter print</langsyntaxhighlight>
{{out}}
<pre>
Line 2,106:
=={{header|MiniScript}}==
We define a ''filter'' method on the list type that returns a new list containing elements filtered by the given function.
<langsyntaxhighlight MiniScriptlang="miniscript">list.filter = function(f)
result = []
for item in self
Line 2,119:
 
nums = [1, 2, 3, 4, 5, 6, 7, 9, 12, 15, 18, 21]
print nums.filter(@isEven)</langsyntaxhighlight>
 
The in-place version is simpler, and even allows the use of an unnamed filter function, defined right on the method call.
<langsyntaxhighlight MiniScriptlang="miniscript">list.filterInPlace = function(f)
for i in range(self.len-1, 0)
if not f(self[i]) then self.remove i
Line 2,134:
end function
 
print nums</langsyntaxhighlight>
 
=={{header|ML}}==
==={{header|Standard ML}}===
<langsyntaxhighlight lang="sml">val ary = [1,2,3,4,5,6];
List.filter (fn x => x mod 2 = 0) ary</langsyntaxhighlight>
==={{header|MLite}}===
MLite is similar to Standard ML, though '=>' becomes '=' and 'List.' is elided:
<langsyntaxhighlight lang="ocaml">val ary = [1,2,3,4,5,6];
filter (fn x = x mod 2 = 0) ary;</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">FILTERARRAY
;NEW I,J,A,B - Not making new, so we can show the values
;Populate array A
Line 2,152:
;Move even numbers into B
SET J=0 FOR I=1:1:10 SET:A(I)#2=0 B($INCREMENT(J))=A(I)
QUIT</langsyntaxhighlight>
Testing:<pre>WRITE
 
Line 2,175:
=={{header|Nemerle}}==
Lists have a built-in method for filtering:
<langsyntaxhighlight Nemerlelang="nemerle">def original = $[1 .. 100];
def filtered = original.Filter(fun(n) {n % 2 == 0});
WriteLine($"$filtered");</langsyntaxhighlight>
The following would work for arrays:
<langsyntaxhighlight Nemerlelang="nemerle">Filter[T] (a : array[T], f : T -> bool) : array[T]
{
def b = $[x | x in a, (f(x))];
b.ToArray()
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 5000
Line 2,249:
ry = Rexx[] clist.toArray(Rexx[clist.size()])
return ry
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,266:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">> (filter (fn (x) (= (% x 2) 0)) '(1 2 3 4 5 6 7 8 9 10))
(2 4 6 8 10)
</syntaxhighlight>
</lang>
 
=={{header|NGS}}==
<langsyntaxhighlight NGSlang="ngs">F even(x:Int) x % 2 == 0
 
evens = Arr(1...10).filter(even)</langsyntaxhighlight>
 
=={{header|Nial}}==
<langsyntaxhighlight lang="nial">filter (= [0 first, mod [first, 2 first] ] ) 0 1 2 3 4 5 6 7 8 9 10
=0 2 4 6 8 10</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import sequtils
 
let values = toSeq(0..9)
Line 2,298:
var v2 = toSeq(0..9)
v2.keepItIf(it mod 2 != 0)
echo "Odd values: ", v2</langsyntaxhighlight>
 
{{out}}
Line 2,307:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
use Structure;
 
Line 2,327:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
{{works with|Cocoa|Mac OS X 10.6+}}
<langsyntaxhighlight lang="objc">NSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:3],
Line 2,337:
[NSNumber numberWithInt:5], nil];
NSArray *evens = [numbers objectsAtIndexes:[numbers indexesOfObjectsPassingTest:
^BOOL(id obj, NSUInteger idx, BOOL *stop) { return [obj intValue] % 2 == 0; } ]];</langsyntaxhighlight>
 
{{works with|Cocoa|Mac OS X 10.5+}}
<langsyntaxhighlight lang="objc">NSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:3],
Line 2,346:
[NSNumber numberWithInt:5], nil];
NSPredicate *isEven = [NSPredicate predicateWithFormat:@"modulus:by:(SELF, 2) == 0"];
NSArray *evens = [numbers filteredArrayUsingPredicate:isEven];</langsyntaxhighlight>
 
{{works with|GNUstep}}
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface NSNumber ( ExtFunc )
Line 2,380:
[pool release];
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
It is easier to do it with a list:
<langsyntaxhighlight lang="ocaml">let lst = [1;2;3;4;5;6]
let even_lst = List.filter (fun x -> x mod 2 = 0) lst</langsyntaxhighlight>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">arr = [1:100];
evennums = arr( mod(arr, 2) == 0 );
disp(evennums);</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<syntaxhighlight lang Oforth="oforth">100 seq filter(#isEven)</langsyntaxhighlight>
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(filter even? '(1 2 3 4 5 6 7 8 9 10))
</syntaxhighlight>
</lang>
=={{header|ooRexx}}==
<langsyntaxhighlight lang="oorexx"> Call random ,,1234567
a=.array~new
b=.array~new
Line 2,431:
Say 'Filtered values (destructive filtering):' a~makestring(line,' ')
Exit
filter: Return arg(1)//2=0</langsyntaxhighlight>
{{out}}
<pre>Unfiltered values: 1412 2244 6778 4002 439 3335 5877 8273 7882 1469
Line 2,439:
=={{header|Oz}}==
It is easier to do it with a list:
<langsyntaxhighlight lang="oz">declare
Lst = [1 2 3 4 5]
LstEven = {Filter Lst IsEven}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
{{PARI/GP select}}
<langsyntaxhighlight lang="parigp">iseven(n)=n%2==0
select(iseven, [2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17])</langsyntaxhighlight>
 
Or in anonymous form
<langsyntaxhighlight lang="parigp">select(n -> n%2==0, [2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17])</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 2,457:
{{works with|Delphi}}<br>
{{works with|Turbo Pascal}}
<langsyntaxhighlight lang="pascal">const
 
numbers:array[0..9] of integer = (0,1,2,3,4,5,6,7,8,9);
Line 2,465:
writeln( 'The number ',numbers[x],' is odd.');
else
writeln( 'The number ',numbers[x],' is even.');</langsyntaxhighlight>
 
The odd() function is a standard library function of pascal as is the function even().
Line 2,471:
=={{header|Peloton}}==
Fixed length English dialect
<langsyntaxhighlight lang="sgml"><@ LETCNWLSTLIT>numbers|1 2 3 4 5 6 7 8 9 10 11 12</@>
<@ DEFLST>evens</@>
<@ ENULSTLIT>numbers|
Line 2,478:
<@ LETLSTELTLST>evens|...</@>
</@>
</@></langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my @a = (1, 2, 3, 4, 5, 6);
my @even = grep { $_%2 == 0 } @a;</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
===basic task===
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">even<span style="color: #0000FF;">(<span style="color: #004080;">integer</span> <span style="color: #000000;">i<span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">remainder<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">2<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?<span style="color: #7060A8;">filter<span style="color: #0000FF;">(<span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">10<span style="color: #0000FF;">)<span style="color: #0000FF;">,<span style="color: #000000;">even<span style="color: #0000FF;">)
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,501:
The following discusses possible destructive/in situ behaviours (in excruciatingly painstaking detail). Phix is reference counted so the distinction between destructive and
non-destructive is somewhat subtle. The following code (builtin filter routine) acts both ways.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">even<span style="color: #0000FF;">(<span style="color: #004080;">integer</span> <span style="color: #000000;">i<span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">remainder<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">2<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0</span>
Line 2,515:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main<span style="color: #0000FF;">(<span style="color: #0000FF;">)
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,523:
</pre>
It will help to explain what is going on by looking at a couple of longhand (and greatly simplified) versions, first an explicitly non-destructive one
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">lhnd_filter<span style="color: #0000FF;">(<span style="color: #004080;">sequence</span> <span style="color: #000000;">a<span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">fn<span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{<span style="color: #0000FF;">}</span>
Line 2,533:
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function
<!--</langsyntaxhighlight>-->
Clearly the above is non-destructive. It makes no attempt to modify a, but builds a new result, and it is fair to say that in some cases the above may be the fastest approach due to fewer reference count updates. However the following may or may not be destructive:
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">lhd_filter<span style="color: #0000FF;">(<span style="color: #004080;">sequence</span> <span style="color: #000000;">a<span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">fn<span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
Line 2,557:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main<span style="color: #0000FF;">(<span style="color: #0000FF;">)
<!--</langsyntaxhighlight>-->
In the t = lhd_filter(s) call, s is preserved because of copy-on-write semantics. Modifying a does not modify s, because it has a reference count of 2 the first attempt to modify it triggers copy-on-write and safely makes a top-level copy. In the s = lhd_filter(s) call however, s is automatically passed by reference, ie the local s is <no value> over the duration of the call and parameter a of lhd_filter() contains the only reference to the previous content of s, and no copy-on-write occurs. Technically modifying a is still not modifying s, but since it has a reference count of 1 it modifies the data that used to be referenced by s, and will again rsn, in situ.
Note: adding t = s before the s = lhd_filter(s) call would make it non-destructive again, as t must be preserved and there is now a reference count >1 on that data. Also note that automatic pass-by-reference only occurs for routine-local variables.
Line 2,566:
=={{header|PHL}}==
 
<langsyntaxhighlight lang="phl">module var;
 
extern printf;
Line 2,576:
 
return 0;
]</langsyntaxhighlight>
 
=={{header|PHP}}==
Using a standard loop
<langsyntaxhighlight lang="php">$arr = range(1,5);
$evens = array();
foreach ($arr as $val){
if ($val % 2 == 0) $evens[] = $val);
}
print_r($evens);</langsyntaxhighlight>
 
Using a filter function
<langsyntaxhighlight lang="php">function is_even($var) { return(!($var & 1)); }
$arr = range(1,5);
$evens = array_filter($arr, "is_even");
print_r($evens);</langsyntaxhighlight>
 
=={{header|Picat}}==
List comprehension is probably the best way of filtering:
<langsyntaxhighlight Picatlang="picat">[I : I in 1..20, I mod 2 == 0]</langsyntaxhighlight>
 
A more general version of filtering is to use <code>call/1</code> with a defined predicate (here <code>p/1</code>):
<langsyntaxhighlight Picatlang="picat">go =>
L = 1..20,
A = filter(L,p).
Line 2,604:
p(N) => N mod 2 == 0.
 
filter(A,F) = [N : N in A, call(F,N)].</langsyntaxhighlight>
 
This general version might be slower since using <code>call/1</code> has some overhead.
Line 2,610:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(filter '((N) (not (bit? 1 N)))
(1 2 3 4 5 6 7 8 9) )</langsyntaxhighlight>
{{out}}
<pre>-> (2 4 6 8)</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">(subscriptrange):
filter_values: procedure options (main); /* 15 November 2013 */
declare a(20) fixed, b(*) fixed controlled;
Line 2,643:
end filter;
 
end filter_values;</langsyntaxhighlight>
Results:
<pre>
Line 2,656:
Most natural solution in Pop11 would probably use list. Below we accumulate filtered elements on the stack and then allocate array for the result:
 
<langsyntaxhighlight lang="pop11">;;; Generic filtering procedure which selects from ar elements
;;; satisfying pred
define filter_array(ar, pred);
Line 2,670:
;;; Use it
filter_array({1, 2, 3, 4, 5},
procedure(x); not(testbit(x, 0)); endprocedure) =></langsyntaxhighlight>
 
=={{header|PostScript}}==
{{libheader|initlib}}
<langsyntaxhighlight lang="postscript">
[1 2 3 4 5 6 7 8 9 10] {2 mod 0 eq} find
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">$array = -15..37
$array | Where-Object { $_ % 2 -eq 0 }</langsyntaxhighlight>
 
=={{header|Prolog}}==
===findall===
<langsyntaxhighlight lang="prolog">evens(D, Es) :- findall(E, (member(E, D), E mod 2 =:= 0), Es).</langsyntaxhighlight>
 
Usage:
 
<langsyntaxhighlight lang="prolog">?- evens([1,2,3,4,5,6,7,8,9,10],E).
E = [2, 4, 6, 8, 10]</langsyntaxhighlight>
 
===Anonymous functions===
Works with SWI-Prolog and <b>module(lambda)</b> written by <b>Ulrich Neumerkel</b>, "lambda.pl" can be found there : http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl
<langsyntaxhighlight Prologlang="prolog">?- use_module(library(lambda)).
true.
 
?- include((\X^(X mod 2 =:= 0)), [1,2,3,4,5,6,7,8,9], L).
L = [2,4,6,8].</langsyntaxhighlight>
 
===filter and anonymous functions===
Works with SWI-Prolog and <b>module(lambda)</b> written by <b>Ulrich Neumerkel</b>, "lambda.pl" can be found there : http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl
<langsyntaxhighlight lang="prolog">:- use_module(lambda).
 
%% filter(Pred, LstIn, LstOut)
Line 2,710:
filter(Pred, T, L1),
( call(Pred,H) -> L = [H|L1]; L = L1).
</syntaxhighlight>
</lang>
Usage :
<langsyntaxhighlight lang="prolog"> ?- filter(\X^(X mod 2 =:= 0), [1,2,3,4,5,6,7,8,9], L).
L = [2,4,6,8] .
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Dim Tal.i(9)
Dim Evens.i(0)
 
Line 2,743:
For i=0 To ArraySize(Evens())
Print(Str(Evens(i))+" ")
Next</langsyntaxhighlight>
 
{{out}}
Line 2,755:
{{works with|Python|2.4}}
 
<langsyntaxhighlight lang="python">values = range(10)
evens = [x for x in values if not x & 1]
ievens = (x for x in values if not x & 1) # lazy
# alternately but less idiomatic:
evens = filter(lambda x: not x & 1, values)</langsyntaxhighlight>
 
Alternative using the slice syntax with its optional "stride" expression:
 
<langsyntaxhighlight lang="python">values = range(10)
evens = values[::2]</langsyntaxhighlight>
 
This works for all versions of Python (at least as far back as 1.5). Lists (arrays) can be "sliced" by indexing them with a range (lower and upper bounds). Thus mylist[1:9] evaluates into a list from the second item (excluding the first item which is mylist[0], of course) up to but not including the ninth item. In Python the expression mylist[:] is synonymous with mylist[0:len(mylist)] ... returning a copy of the complete list. also mylist[:x] returns the first x items from the list and negative numbers can be used such that mylist[-x:] returns the last x items from the list. The relatively obscure and optional stride expression can skip items and/or force the evaluation from the end of the list downward towards it's lower elements. Thus mylist[::-1] returns a reversed copy of the list, mylist[::2] returns all even elements, mylist[1::2] returns all odd elements, and so on.
Line 2,772:
One can also assign to a slice (of a list or other mutable indexed object. Thus the following:
 
<langsyntaxhighlight lang="python">values = range(10)
values[::2] = [11,13,15,17,19]
print values
11, 1, 13, 3, 15, 5, 17, 7, 19, 9</langsyntaxhighlight>
 
 
Or in functional terms, by descending generality and increasing brevity:
{{works with|Python|3}}
<langsyntaxhighlight lang="python">'''Functional filtering - by descending generality and increasing brevity'''
 
from functools import (reduce)
Line 2,874:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>By descending generality and increasing brevity:
Line 2,885:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ [] ]'[ rot
witheach
[ tuck over do iff
Line 2,896:
[] 10 times [ 10 random join ]
say "Ten arbitrary digits: " dup echo cr
say "Only the even digits: " only even echo cr</langsyntaxhighlight>
 
{{out}}
Line 2,905:
===Destructively===
 
<langsyntaxhighlight Quackerylang="quackery"> [ ]'[ over size times
[ over i peek
over do if
Line 2,915:
[] 10 times [ i join ] shuffle
say "Ten shuffled digits: " dup echo cr
say "Less the odd digits: " without odd echo cr</langsyntaxhighlight>
 
{{out}}
Line 2,923:
 
=={{header|Q}}==
<langsyntaxhighlight lang="q">x where 0=x mod 2</langsyntaxhighlight>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">a <- 1:100
evennums <- a[ a%%2 == 0 ]
print(evennums)</langsyntaxhighlight>
 
=={{header|Racket}}==
The classic way:
<syntaxhighlight lang="racket">
<lang Racket>
-> (filter even? '(0 1 2 3 4 5 6 7 8 9))
'(0 2 4 6 8)
</syntaxhighlight>
</lang>
getting the list of non-evens too:
<syntaxhighlight lang="racket">
<lang Racket>
-> (partition even? '(0 1 2 3 4 5 6 7 8 9))
'(0 2 4 6 8)
'(1 3 5 7 9)
</syntaxhighlight>
</lang>
Finally, using a for loop, similar to list comprehension:
<syntaxhighlight lang="racket">
<lang Racket>
-> (for/list ([x '(0 1 2 3 4 5 6 7 8 9)] #:when (even? x)) x)
'(0 2 4 6 8)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,952:
{{works with|Rakudo|2018.03}}
 
<syntaxhighlight lang="raku" perl6line>my @a = 1..6;
my @even = grep * %% 2, @a;</langsyntaxhighlight>
 
Alternatively:
 
<syntaxhighlight lang="raku" perl6line>my @a = 1..6;
my @even = @a.grep(* %% 2);</langsyntaxhighlight>
 
Destructive:
 
<syntaxhighlight lang="raku" perl6line>my @a = 1..6;
@a .= grep(* %% 2);</langsyntaxhighlight>
 
=={{header|Raven}}==
<langsyntaxhighlight lang="raven">[ 0 1 2 3 4 5 6 7 8 9 ] as nums
group nums each
dup 1 & if drop
list as evens</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">a: [] repeat i 100 [append a i] ; Build and load array.
 
evens: [] repeat element a [if even? element [append evens element]]
 
print mold evens</langsyntaxhighlight>
 
{{out}}
Line 2,985:
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red []
orig: [] repeat i 10 [append orig i]
?? orig
Line 2,994:
remove-each ele orig [odd? ele] ;; destructive
?? orig
</syntaxhighlight>
</lang>
{{out}}
<pre>orig: [1 2 3 4 5 6 7 8 9 10]
Line 3,005:
===using two arrays===
This example uses two arrays. &nbsp; The &nbsp; '''random''' &nbsp; BIF is used to generate the numbers.
<langsyntaxhighlight lang="rexx">/*REXX program selects all even numbers from an array and puts them ──► a new array.*/
parse arg N seed . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 50 /*Not specified? Then use the default.*/
Line 3,023:
do k=1 for # /*display all the NEW numbers. */
say right('new.'k, 20) "=" right(new.k, 9) /*display a line (an array element). */
end /*k*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
Programming note: &nbsp; the REXX statement
<langsyntaxhighlight lang="rexx"> if old.j//2 \== 0 then iterate</langsyntaxhighlight>
could've been replaced with
<langsyntaxhighlight lang="rexx"> if old.j//2 then iterate</langsyntaxhighlight>
but that would've assumed the numbers are integers &nbsp; (no matter what form they're expressed in).<br>
As it happens, the REXX program uses the numbers generated from the &nbsp; '''random''' &nbsp; BIF, &nbsp; which are integers.
Line 3,062:
===using one array with a control array===
This version uses a control array, which isn't fully populated &nbsp; (in REXX terms, a sparse array.)
<langsyntaxhighlight lang="rexx">/*REXX program finds all even numbers from an array, and marks a control array. */
parse arg N seed . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 50 /*Not specified? Then use the default.*/
Line 3,078:
if !.k then iterate /*if it's marked as not even, skip it.*/
say right('array.'k, 20) "=" right(@.k, 9) /*display a even number, filtered array*/
end /*k*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
For the following input: &nbsp; &nbsp; <tt> , 1234567 </tt>
 
Line 3,088:
 
This method doesn't need as much memory to hold the sparse array.
<langsyntaxhighlight lang="rexx">/*REXX program finds all even numbers from an array, and marks the not even numbers.*/
parse arg N seed . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 50 /*Not specified? Then use the default.*/
Line 3,104:
if @.k=='' then iterate /*if it's marked not even, then skip it*/
say right('array.'k, 20) "=" right(@.k, 9) /*display a line (an array element). */
end /*k*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
For the following input: &nbsp; &nbsp; <tt> , 1234567 </tt>
 
Line 3,110:
 
=={{header|Ring}}==
<syntaxhighlight lang="text">
aList = [1, 2, 3, 4, 5, 6]
bArray = list(3)
Line 3,123:
next
return bArray
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
Enumerable#select is the filter that returns a new Array.
 
<langsyntaxhighlight lang="ruby"># Enumerable#select returns a new array.
ary = [1, 2, 3, 4, 5, 6]
even_ary = ary.select {|elem| elem.even?}
Line 3,136:
range = 1..6
even_ary = range.select {|elem| elem.even?}
p even_ary # => [2, 4, 6]</langsyntaxhighlight>
 
=== Destructive ===
Array#select! is the destructive version which modifies the original Array.
 
<langsyntaxhighlight lang="ruby">ary = [1, 2, 3, 4, 5, 6]
ary.select! {|elem| elem.even?}
p ary # => [2, 4, 6]</langsyntaxhighlight>
 
Shorthand:
 
<langsyntaxhighlight lang="ruby">ary = [1, 2, 3, 4, 5, 6]
ary.select!(&:even?)
p ary # => [2, 4, 6]</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">dim a1(100)
count = 100
for i = 1 to 100
Line 3,170:
for i = 1 to count
print a2(i)
next</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn main() {
println!("new vec filtered: ");
let nums: Vec<i32> = (1..20).collect();
Line 3,184:
nums.retain(|x| x % 2 == 0);
println!("{:?}", nums);
}</langsyntaxhighlight>
 
{{out}}
Line 3,197:
In this example, [1...10] is a list of the integers from 1 to 10. The comprehend expression walks over this list and selects only the even elements. The result of the comprehend expression is a new list with only the even elements. Then an iterate statement is used to walk over the list of even elements and print them out.
 
<langsyntaxhighlight Salmonlang="salmon">iterate(x; comprehend(y; [1...10]; y % 2 == 0) (y))
x!;</langsyntaxhighlight>
 
Here's a version that walks an array destructively removing the non-even elements:
 
<langsyntaxhighlight Salmonlang="salmon">variable my_array := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
variable write_position := 0;
iterate (read_position; [0...9])
Line 3,216:
my_array := my_array[0...write_position - 1];
iterate(x; my_array)
x!;</langsyntaxhighlight>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MARRAY{T} < $ARR{T} is
include ARRAY{T};
 
Line 3,241:
#OUT + "\n";
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">(1 to 100).filter(_ % 2 == 0)</langsyntaxhighlight>
 
=={{header|Scheme}}==
Filter function definition:
<langsyntaxhighlight lang="scheme">
(define filter
(lambda (fn lst)
Line 3,259:
(iter rest (cons item result))
(iter rest result)))))))
</syntaxhighlight>
</lang>
Usage in the interactive prompt:
<langsyntaxhighlight lang="scheme">> (filter even? '(1 2 3 4 5 6 7 8 9 10))
(2 4 6 8 10)</langsyntaxhighlight>
Or as a function:
<langsyntaxhighlight lang="scheme">(define (select-even lst)
(filter even? lst))
 
(select-even '(1 2 3 4 5 6 7 8 9 10))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">var array integer: arr is [] (1, 2, 3, 4, 5);
var array integer: evens is 0 times 0;
var integer: number is 0;
Line 3,278:
evens &:= [] (number);
end if;
end for;</langsyntaxhighlight>
 
=={{header|SequenceL}}==
Filters are primarily written in SequenceL using partial Indexed Functions.<br>
<langsyntaxhighlight lang="sequencel">evens(x(1))[i] := x[i] when x[i] mod 2 = 0;</langsyntaxhighlight>
 
{{out}}
Line 3,291:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var arr = [1,2,3,4,5];
 
# Creates a new array
Line 3,299:
# Destructive (at variable level)
arr.grep! {|i| i %% 2};
say arr.dump; # => [2, 4]</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">#(1 2 3 4 5) select: [| :number | number isEven].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Creates a new array:
<langsyntaxhighlight lang="smalltalk">#(1 2 3 4 5) select: [:number | number even]</langsyntaxhighlight>
or for short:
<langsyntaxhighlight lang="smalltalk">#(1 2 3 4 5) select:#even</langsyntaxhighlight>
Destructive modification is not possible for literal constants (these are immutable);
in addition, Arrays are fix sized collections. It is also considered very bad style, to modify passed in arguments this way. Thus constructing a new Array object (as above) is the only correct solution.
Line 3,316:
 
{{works with|MS SQL}}
<langsyntaxhighlight lang="sql">--Create the original array (table #nos) with numbers from 1 to 10
create table #nos (v int)
declare @n int set @n=1
Line 3,329:
-- Clean up so you can edit and repeat:
drop table #nos
drop table #evens</langsyntaxhighlight>
 
'{{works with|MySQL}}
<langsyntaxhighlight lang="sql">create temporary table nos (v int);
insert into nos values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
create temporary table evens (v int);
Line 3,338:
select * from evens order by v; /*2,4,6,8,10*/
drop table nos;
drop table evens;</langsyntaxhighlight>
 
Or to be shorter, you could create the table evens directly from the query result :
<langsyntaxhighlight lang="sql">create temporary table evens select * from nos where v%2=0;</langsyntaxhighlight>
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">mata
a=2,9,4,7,5,3,6,1,8
 
Line 3,352:
// Select the indices of even elements of a
selectindex(mod(a,2):==0)
end</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">let numbers = [1,2,3,4,5,6]
let even_numbers = numbers.filter { $0 % 2 == 0 }
println(even_numbers)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,364:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set l {56 21 71 27 39 62 87 76 82 94 45 83 65 45 28 90 52 44 1 89}
 
puts [lmap x $l {if {$x % 2} continue; set x}]</langsyntaxhighlight>
{{out}}
<pre>56 62 76 82 94 28 90 52 44</pre>
<br>
Inplace way, quite the inefficient contraption compared to mapping:
<langsyntaxhighlight lang="tcl">proc lreplaceip {_list args} {
upvar 1 $_list list
set list [lreplace $list[set list {}] {*}$args]
Line 3,386:
}
 
puts $l</langsyntaxhighlight>
{{out}}
<pre>56 62 76 82 94 28 90 52 44</pre>
Explanation: https://wiki.tcl-lang.org/page/lreplace, section "Performance: Modifying a List In-Place"<br>
Proof by timing removal of the end element of lists of different lengths:
<langsyntaxhighlight lang="tcl">proc lreplaceip {_list args} {
upvar 1 $_list list
set list [lreplace $list[set list {}] {*}$args]
Line 3,410:
puts " lreplace: [time {set l [lreplace $l end end]}]"
puts " lreplaceip: [time {lreplaceip l end end}]"
}</langsyntaxhighlight>
{{out}}
<pre>1e5
Line 3,423:
 
=={{header|Toka}}==
<langsyntaxhighlight lang="toka">10 cells is-array table
10 cells is-array even
{
Line 3,435:
} is copy-even
10 0 [ i i table array.put ] countedLoop
table 10 copy-even</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
arr="1'4'9'16'25'36'49'64'81'100",even=""
Line 3,446:
ENDLOOP
PRINT even
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,455:
{{works with|Bash}}
 
<langsyntaxhighlight lang="bash">a=(1 2 3 4 5)
unset e[@]
for ((i=0;i<${#a[@]};i++)); do
[ $((a[$i]%2)) -eq 0 ] && e[$i]="${a[$i]}"
done</langsyntaxhighlight>
 
Or, using '''grep''':
 
<langsyntaxhighlight lang="bash">a=(1 2 3 4 5)
read -a e -d\n < <(printf '%s\n' "${a[@]}" | grep '[02468]$')</langsyntaxhighlight>
 
Either way, to display the results:
 
<langsyntaxhighlight lang="bash">echo "${a[@]}"
echo "${e[@]}"</langsyntaxhighlight>
 
{{out}}
Line 3,476:
 
=={{header|UnixPipes}}==
<langsyntaxhighlight lang="bash">yes \ | cat -n | while read a; do ; expr $a % 2 >/dev/null && echo $a ; done</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 3,490:
predicate <code>p</code> is to write <code>p*~</code>, as shown below.
 
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 3,497:
#cast %nL
 
y = (not remainder\2)*~ x</langsyntaxhighlight>
 
{{out}}
Line 3,509:
of other ways to do it.
Selecting according to a binary predicate can be done like this.
<langsyntaxhighlight Ursalalang="ursala">z = (not remainder)~| (36,<1,2,3,4,5,6,7,8,9,10,11,12>)</langsyntaxhighlight>
The value of <code>z</code> will be the divisors of 36 appearing in the list.
<pre>
Line 3,526:
modified by appending an <code>F</code>, it becomes a selection filter.
For example
<langsyntaxhighlight Ursalalang="ursala">shortcut = ~&ihBF x</langsyntaxhighlight>
using the <code>x</code> defined above will evaluate to
<pre>
Line 3,534:
 
=={{header|V}}==
<langsyntaxhighlight lang="v">[even? dup 2 / >int 2 * - zero?].
 
[1 2 3 4 5 6 7 8 9] [even?] filter
=[2 4 6 8]</langsyntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 3,587:
Private Function IsEven(Number As Long) As Boolean
IsEven = (CLng(Right(CStr(Number), 1)) And 1) = 0
End Function</langsyntaxhighlight>
 
{{Out}}
Line 3,595:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
test_arr_1 = Array(1,2,3,4,5,6,7,8,9,10)
test_arr_2 = Array(1,2,3,4,5,6,7,8,9,10)
Line 3,642:
ReDim Preserve arr(UBound(arr)-count)
filter_destruct = Join(arr,",")
End Function</langsyntaxhighlight>
 
{{Out}}
Line 3,657:
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
<langsyntaxhighlight lang="vbnet">Module Filter
 
Sub Main()
Line 3,698:
 
End Module
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,728:
 
=={{header|Vlang}}==
<langsyntaxhighlight lang="vlang">fn reduce(mut a []int){
mut last := 0
for e in a {
Line 3,745:
reduce(mut nums)
println('dest: $nums')
}</langsyntaxhighlight>
{{out}}
<pre>orig: [5,4,8,2,4,6,5,6,34,12,21]
Line 3,752:
 
=={{header|WDTE}}==
<langsyntaxhighlight WDTElang="wdte">let a => import 'arrays';
let s => import 'stream';
 
Line 3,759:
-> s.collect
-- io.writeln io.stdout
;</langsyntaxhighlight>
 
{{out}}
Line 3,767:
 
=={{header|Wrapl}}==
<langsyntaxhighlight lang="wrapl">VAR a <- ALL 1:to(10);</langsyntaxhighlight>
<tt>a</tt> will be the list <tt>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</tt>
<langsyntaxhighlight lang="wrapl">VAR e <- ALL a:values \ $ % 2 = 0;</langsyntaxhighlight>
<tt>e</tt> will be the list <tt>[2, 4, 6, 8, 10]</tt>
 
=={{header|Wren}}==
<langsyntaxhighlight lang="ecmascript">var a = [1, 4, 17, 8, -21, 6, -11, -2, 18, 31]
System.print("The original array is : %(a)")
 
Line 3,792:
System.print("\nAfter a destructive filter :-")
System.print("The even numbers are : %(evens)")
System.print("The original array is now : %(a)")</langsyntaxhighlight>
 
{{out}}
Line 3,811:
There is no 'sizeof' operator, unfortunately.
 
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
proc Filter(A, B, Option); \Select all even numbers from array A
Line 3,838:
[IntOut(0, Array(I)); ChOut(0, ^ )];
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 3,847:
 
=={{header|XQuery}}==
<langsyntaxhighlight lang="xquery">
(: Sequence of numbers from 1 to 10 :)
let $array := (1 to 10)
Line 3,865:
<long>{$long}</long>
</result>
</syntaxhighlight>
</lang>
 
{{out}}
<langsyntaxhighlight lang="xml">
<?xml version="1.0" encoding="UTF-8"?>
<result>
Line 3,874:
<long>2 4 6 8 10</long>
</result>
</syntaxhighlight>
</lang>
 
=={{header|XSLT}}==
<langsyntaxhighlight lang="xml"><xsl:for-each select="nodes[@value mod 2 = 0]">
<xsl:value-of select="@value" />
</xsl:for-each></langsyntaxhighlight>
 
=={{header|Z80 Assembly}}==
{{untested}}
<langsyntaxhighlight lang="z80">TestArray_Metadata:
byte 4,4 ;4 rows, 4 columns.
TestArray:
Line 3,919:
djnz loop_filterEvenValues
 
ret ;return to basic</langsyntaxhighlight>
 
{{out}}
Line 3,928:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">T(1,4,9,16,25,36,"37",49,64,81,100, True,self)
.filter(fcn(n){(0).isType(n) and n.isOdd})
//-->L(1,9,25,49,81)</langsyntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang="zxbasic">10 LET items=100: LET filtered=0
20 DIM a(items)
30 FOR i=1 TO items
Line 3,946:
120 NEXT i
130 DIM a(1): REM To free memory (well, almost all)
140 DEF FN m(a,b)=a-INT (a/b)*b</langsyntaxhighlight>
10,333

edits