Filter: Difference between revisions

From Rosetta Code
Content added Content deleted
(add BQN)
 
(48 intermediate revisions by 27 users not shown)
Line 14: Line 14:
=={{header|11l}}==
=={{header|11l}}==


<lang 11l>V array = Array(1..10)
<syntaxhighlight lang="11l">V array = Array(1..10)
V even = array.filter(n -> n % 2 == 0)
V even = array.filter(n -> n % 2 == 0)
print(even)</lang>
print(even)</syntaxhighlight>


{{out}}
{{out}}
<pre>
<pre>
[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]
</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program filterdes64.s */

/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

/************************************/
/* Initialized data */
/************************************/
.data
szMessResult: .asciz "Start array : "
szMessResultFil: .asciz "Filter array : "
szMessResultdest: .asciz "Same array : "
szMessStart: .asciz "Program 64 bits start.\n"
szCarriageReturn: .asciz "\n"
szFiller: .asciz " "
.align 4
arrayNumber: .quad 1,2,3,4,5,6,7,8,9,10
.equ LGARRAY, (. - arrayNumber) / 8
/************************************/
/* UnInitialized data */
/************************************/
.bss
.align 4
arrayNumberFil: .skip 8 * LGARRAY // result array
sZoneConv: .skip 24
/************************************/
/* code section */
/************************************/
.text
.global main
main:
ldr x0,qAdrszMessStart // display start message
bl affichageMess
ldr x0,qAdrszMessResult // display message
bl affichageMess
ldr x5,qAdrarrayNumber // start array address
mov x4,#0 // index
1:
ldr x0,[x5,x4,lsl #3] // load a value
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsZoneConv
bl affichageMess // display value
ldr x0,qAdrszFiller
bl affichageMess
add x4,x4,#1 // increment index
cmp x4,#LGARRAY // end array ?
blt 1b // no -> loop
ldr x0,qAdrszCarriageReturn
bl affichageMess
ldr x6,qAdrarrayNumberFil // adrress result array
mov x4,#0 // index
mov x3,#0 // index result
2:
ldr x0,[x5,x4,lsl #3] // load a value
tst x0,#1 // odd ?
bne 3f
str x0,[x6,x3,lsl #3] // no -> store in result array
add x3,x3,#1 // and increment result index
3:
add x4,x4,#1 // increment array index
cmp x4,#LGARRAY // end ?
blt 2b // no -> loop
ldr x0,qAdrszMessResultFil
bl affichageMess
mov x4,#0 // init index
4: // display filter result array
ldr x0,[x6,x4,lsl #3]
ldr x1,qAdrsZoneConv
bl conversion10
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrszFiller
bl affichageMess
add x4,x4,#1
cmp x4,x3
blt 4b
ldr x0,qAdrszCarriageReturn
bl affichageMess
// array destruction
mov x4,#0 // index
mov x3,#0 // index result
5:
ldr x0,[x5,x4,lsl #3] // load a value
tst x0,#1 // odd ?
bne 7f
cmp x3,x4 // index = no store
beq 6f
str x0,[x5,x3,lsl #3] // store in free item on same array
6:
add x3,x3,#1 // and increment result index
7:
add x4,x4,#1 // increment array index
cmp x4,#LGARRAY // end ?
blt 5b // no -> loop
ldr x0,qAdrszMessResultdest
bl affichageMess
mov x4,#0 // init index
8: // display array
ldr x0,[x5,x4,lsl #3]
ldr x1,qAdrsZoneConv
bl conversion10
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrszFiller
bl affichageMess
add x4,x4,#1
cmp x4,x3
blt 8b
ldr x0,qAdrszCarriageReturn
bl affichageMess

100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessStart: .quad szMessStart
qAdrarrayNumber: .quad arrayNumber
qAdrszMessResult: .quad szMessResult
qAdrarrayNumberFil: .quad arrayNumberFil
qAdrszMessResultFil: .quad szMessResultFil
qAdrszMessResultdest: .quad szMessResultdest
qAdrsZoneConv: .quad sZoneConv
qAdrszFiller: .quad szFiller
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"


</syntaxhighlight>
{{Out}}
<pre>
Program 64 bits start.
Start array : 1 2 3 4 5 6 7 8 9 10
Filter array : 2 4 6 8 10
Same array : 2 4 6 8 10
</pre>
</pre>


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang Lisp>(defun filter-evens (xs)
<syntaxhighlight lang="lisp">(defun filter-evens (xs)
(cond ((endp xs) nil)
(cond ((endp xs) nil)
((evenp (first xs))
((evenp (first xs))
(cons (first xs) (filter-evens (rest xs))))
(cons (first xs) (filter-evens (rest xs))))
(t (filter-evens (rest xs)))))</lang>
(t (filter-evens (rest xs)))))</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>DEFINE PTR="CARD"
<syntaxhighlight lang="action!">DEFINE PTR="CARD"


INT value ;used in predicate
INT value ;used in predicate
Line 138: Line 293:
PrintE("Select all non negative numbers:")
PrintE("Select all non negative numbers:")
PrintArray(src,srcSize)
PrintArray(src,srcSize)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Filter.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Filter.png Screenshot from Atari 8-bit computer]
Line 162: Line 317:


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang actionscript>var arr:Array = new Array(1, 2, 3, 4, 5);
<syntaxhighlight lang="actionscript">var arr:Array = new Array(1, 2, 3, 4, 5);
var evens:Array = new Array();
var evens:Array = new Array();
for (var i:int = 0; i < arr.length(); i++) {
for (var i:int = 0; i < arr.length(); i++) {
if (arr[i] % 2 == 0)
if (arr[i] % 2 == 0)
evens.push(arr[i]);
evens.push(arr[i]);
}</lang>
}</syntaxhighlight>


'''Actionscript 3'''
'''Actionscript 3'''
<lang actionscript>var arr:Array = new Array(1, 2, 3, 4, 5);
<syntaxhighlight lang="actionscript">var arr:Array = new Array(1, 2, 3, 4, 5);
arr = arr.filter(function(item:int, index:int, array:Array) {
arr = arr.filter(function(item:int, index:int, array:Array) {
return item % 2 == 0;
return item % 2 == 0;
});
});
</syntaxhighlight>
</lang>


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
<syntaxhighlight lang="ada">with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Text_Io; use Ada.Text_Io;


Line 208: Line 363:
begin
begin
Print(Evens(Foo));
Print(Evens(Foo));
end Array_Selection;</lang>
end Array_Selection;</syntaxhighlight>
Here is a non-recursive solution:
Here is a non-recursive solution:
<lang ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;


procedure Array_Selection is
procedure Array_Selection is
Line 237: Line 392:
Put (Evens ((1,2,3,4,5,6,7,8,9,10)));
Put (Evens ((1,2,3,4,5,6,7,8,9,10)));
New_Line;
New_Line;
end Array_Selection;</lang>
end Array_Selection;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>integer
<syntaxhighlight lang="aime">integer
even(integer e)
even(integer e)
{
{
Line 290: Line 445:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> 0 2 4 6 8</pre>
<pre> 0 2 4 6 8</pre>
Line 298: Line 453:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{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}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<lang algol68>MODE TYPE = INT;
<syntaxhighlight lang="algol68">MODE TYPE = INT;


PROC select = ([]TYPE from, PROC(TYPE)BOOL where)[]TYPE:
PROC select = ([]TYPE from, PROC(TYPE)BOOL where)[]TYPE:
Line 320: Line 475:


# Or as a simple one line query #
# 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))</lang>
print((select((1,4,9,16,25,36,49,64,81,100), (TYPE x)BOOL: NOT ODD x ), new line))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 331: Line 486:
In the sample below, the ''select'' procedure's parameters do not include the parameters of ''where'' - they are commented out.<br>
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.
Recent compilers (such as Awe) require the parameter types be specified and so the parameters to ''where'' should be uncommented when compilling with Awe.
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% sets the elements of out to the elements of in that return true from applying the where procedure to them %
% 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 %
% the bounds of in must be 1 :: inUb - out must be at least as big as in and the number of matching %
Line 357: Line 512:
write()
write()
end.
end.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 364: Line 519:


=={{header|AmigaE}}==
=={{header|AmigaE}}==
<lang amigae>PROC main()
<syntaxhighlight lang="amigae">PROC main()
DEF l : PTR TO LONG, r : PTR TO LONG, x
DEF l : PTR TO LONG, r : PTR TO LONG, x
l := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Line 370: Line 525:
SelectList({x}, l, r, `Mod(x,2)=0)
SelectList({x}, l, r, `Mod(x,2)=0)
ForAll({x}, r, `WriteF('\d\n', x))
ForAll({x}, r, `WriteF('\d\n', x))
ENDPROC</lang>
ENDPROC</syntaxhighlight>


=={{header|AntLang}}==
=={{header|AntLang}}==
<lang AntLang>x:range[100]
<syntaxhighlight lang="antlang">x:range[100]
{1- x mod 2}hfilter x</lang>
{1- x mod 2}hfilter x</syntaxhighlight>


=={{header|Apex}}==
=={{header|Apex}}==
<lang Apex>List<Integer> integers = new List<Integer>{1,2,3,4,5};
<syntaxhighlight lang="apex">List<Integer> integers = new List<Integer>{1,2,3,4,5};
Set<Integer> evenIntegers = new Set<Integer>();
Set<Integer> evenIntegers = new Set<Integer>();
for(Integer i : integers)
for(Integer i : integers)
Line 391: Line 546:
system.assert(!evenIntegers.contains(3), '3 should not be a number in the set');
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(4), '4 should be a number in the set');
system.assert(!evenIntegers.contains(5), '5 should not be a number in the set');</lang>
system.assert(!evenIntegers.contains(5), '5 should not be a number in the set');</syntaxhighlight>


=={{header|APL}}==
=={{header|APL}}==
<lang APL> (0=2|x)/x←⍳20
<syntaxhighlight lang="apl"> (0=2|x)/x←⍳20
2 4 6 8 10 12 14 16 18 20</lang>
2 4 6 8 10 12 14 16 18 20</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
<lang applescript>set array to {1, 2, 3, 4, 5, 6}
<syntaxhighlight lang="applescript">set array to {1, 2, 3, 4, 5, 6}
set evens to {}
set evens to {}
repeat with i in array
repeat with i in array
if (i mod 2 = 0) then set end of evens to i's contents
if (i mod 2 = 0) then set end of evens to i's contents
end repeat
end repeat
return evens</lang>Result is (a list):<pre>{2, 4, 6}</pre>
return evens</syntaxhighlight>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):
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):


<lang AppleScript>to filter(inList, acceptor)
<syntaxhighlight lang="applescript">to filter(inList, acceptor)
set outList to {}
set outList to {}
repeat with anItem in inList
repeat with anItem in inList
Line 423: Line 578:
end script
end script


filter({1,2,3,4,5,6}, isEven)</lang>
filter({1,2,3,4,5,6}, isEven)</syntaxhighlight>




Line 435: Line 590:
This allows for context-sensitive filters, which can take account of following or preceding elements in a sequence.
This allows for context-sensitive filters, which can take account of following or preceding elements in a sequence.


<lang AppleScript>-------------------------- FILTER --------------------------
<syntaxhighlight lang="applescript">-------------------------- FILTER --------------------------


-- filter :: (a -> Bool) -> [a] -> [a]
-- filter :: (a -> Bool) -> [a] -> [a]
Line 477: Line 632:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<pre>{0, 2, 4, 6, 8, 10}</pre>
<pre>{0, 2, 4, 6, 8, 10}</pre>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program filterdes.s */

/************************************/
/* Constantes */
/************************************/
/* for constantes see task include a file in arm assembly */
.include "../constantes.inc"

/************************************/
/* Initialized data */
/************************************/
.data
szMessResult: .asciz "Start array : "
szMessResultFil: .asciz "Filter array : "
szMessResultdest: .asciz "Same array : "
szMessStart: .asciz "Program 32 bits start.\n"
szCarriageReturn: .asciz "\n"
.align 4
arrayNumber: .int 1,2,3,4,5,6,7,8,9,10
.equ LGARRAY, (. - arrayNumber) / 4
/************************************/
/* UnInitialized data */
/************************************/
.bss
.align 4
arrayNumberFil: .skip 4 * LGARRAY @ result array
sZoneConv: .skip 24
/************************************/
/* code section */
/************************************/
.text
.global main
main:
ldr r0,iAdrszMessStart @ display start message
bl affichageMess
ldr r0,iAdrszMessResult @ display message
bl affichageMess
ldr r5,iAdrarrayNumber @ start array address
mov r4,#0 @ index
1:
ldr r0,[r5,r4,lsl #2] @ load a value
ldr r1,iAdrsZoneConv
bl conversion10 @ décimal conversion
add r1,r1,r0 @ compute address end number
add r1,#2 @ add two characters
mov r0,#0 @ for limit the size of display number
strb r0,[r1] @ to store a final zero
ldr r0,iAdrsZoneConv
bl affichageMess @ display value
add r4,r4,#1 @ increment index
cmp r4,#LGARRAY @ end array ?
blt 1b @ no -> loop
ldr r0,iAdrszCarriageReturn
bl affichageMess
ldr r6,iAdrarrayNumberFil @ adrress result array
mov r4,#0 @ index
mov r3,#0 @ index result
2:
ldr r0,[r5,r4,lsl #2] @ load a value
tst r0,#1 @ odd ?
streq r0,[r6,r3,lsl #2] @ no -> store in result array
addeq r3,r3,#1 @ and increment result index
add r4,r4,#1 @ increment array index
cmp r4,#LGARRAY @ end ?
blt 2b @ no -> loop
ldr r0,iAdrszMessResultFil
bl affichageMess
mov r4,#0 @ init index
3: @ display filter result array
ldr r0,[r6,r4,lsl #2]
ldr r1,iAdrsZoneConv
bl conversion10
add r1,r1,r0
add r1,#2
mov r0,#0
strb r0,[r1]
ldr r0,iAdrsZoneConv
bl affichageMess
add r4,r4,#1
cmp r4,r3
blt 3b
ldr r0,iAdrszCarriageReturn
bl affichageMess
@ array destruction
mov r4,#0 @ index
mov r3,#0 @ index result
4:
ldr r0,[r5,r4,lsl #2] @ load a value
tst r0,#1 @ even ?
bne 6f
cmp r3,r4 @ index = no store
beq 5f
str r0,[r5,r3,lsl #2] @ store in free item on same array
5:
add r3,r3,#1 @ and increment result index
6:
add r4,r4,#1 @ increment array index
cmp r4,#LGARRAY @ end ?
blt 4b @ no -> loop
ldr r0,iAdrszMessResultdest
bl affichageMess
mov r4,#0 @ init index
7: @ display array
ldr r0,[r5,r4,lsl #2]
ldr r1,iAdrsZoneConv
bl conversion10
add r1,r1,r0
add r1,#2
mov r0,#0
strb r0,[r1]
ldr r0,iAdrsZoneConv
bl affichageMess
add r4,r4,#1
cmp r4,r3
blt 7b
ldr r0,iAdrszCarriageReturn
bl affichageMess

100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessStart: .int szMessStart
iAdrarrayNumber: .int arrayNumber
iAdrszMessResult: .int szMessResult
iAdrarrayNumberFil: .int arrayNumberFil
iAdrszMessResultFil: .int szMessResultFil
iAdrszMessResultdest: .int szMessResultdest
iAdrsZoneConv: .int sZoneConv
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language ARM assembly*/
.include "../affichage.inc"

</syntaxhighlight>
{{Out}}
<pre>
Program 32 bits start.
Start array : 1 2 3 4 5 6 7 8 9 10
Filter array : 2 4 6 8 10
Same array : 2 4 6 8 10
</pre>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>arr: [1 2 3 4 5 6 7 8 9 10]
<syntaxhighlight lang="rebol">arr: [1 2 3 4 5 6 7 8 9 10]


print select arr [x][even? x]</lang>
print select arr [x][even? x]</syntaxhighlight>


{{out}}
{{out}}
Line 491: Line 802:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>array = 1,2,3,4,5,6,7
<syntaxhighlight lang="autohotkey">array = 1,2,3,4,5,6,7
loop, parse, array, `,
loop, parse, array, `,
{
{
Line 542: Line 853:




</syntaxhighlight>
</lang>


=={{header|AWK}}==
=={{header|AWK}}==
Line 550: Line 861:


'''One-liner:'''
'''One-liner:'''
<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}'</lang>
<syntaxhighlight 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}'</syntaxhighlight>
{{out}}
{{out}}
<pre>4 6 8 2</pre>
<pre>4 6 8 2</pre>


'''Regular script:'''
'''Regular script:'''
<lang awk>
<syntaxhighlight lang="awk">
BEGIN {
BEGIN {
split("1 2 3 4 5 6 7 8 9",a);
split("1 2 3 4 5 6 7 8 9",a);
Line 561: Line 872:
print r
print r
}
}
</syntaxhighlight>
</lang>
Same output.
Same output.


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>
<syntaxhighlight lang="dos">
@echo off
@echo off
setlocal enabledelayedexpansion
setlocal enabledelayedexpansion
Line 624: Line 935:
set /a length+=1
set /a length+=1
goto lengthloop
goto lengthloop
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 636: Line 947:


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> REM Create the test array:
<syntaxhighlight lang="bbcbasic"> REM Create the test array:
items% = 1000
items% = 1000
DIM array%(items%)
DIM array%(items%)
Line 669: Line 980:
END
END


DEF FNfilter(A%) = ((A% AND 1) = 0)</lang>
DEF FNfilter(A%) = ((A% AND 1) = 0)</syntaxhighlight>


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"


// Copy every value for which p(x) is true from in to out
// Copy every value for which p(x) is true from in to out
Line 711: Line 1,022:
writevec(arr, len)
writevec(arr, len)
wrch('*N')
wrch('*N')
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre>Numbers: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<pre>Numbers: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Line 718: Line 1,029:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>( :?odds
<syntaxhighlight 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)$() ()
& ( 1 2 3 4 5 6 7 8 9 10 16 25 36 49 64 81 100:? (=.!sjt*1/2:/&!odds !sjt:?odds)$() ()
| !odds
| !odds
)
)
)
)
</syntaxhighlight>
</lang>
<pre>1 3 5 7 9 25 49 81</pre>
<pre>1 3 5 7 9 25 49 81</pre>


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>#Prints [2, 4, 6, 8, 10]
<syntaxhighlight lang="brat">#Prints [2, 4, 6, 8, 10]
p 1.to(10).select { x | x % 2 == 0 }</lang>
p 1.to(10).select { x | x % 2 == 0 }</syntaxhighlight>


=={{header|Burlesque}}==
=={{header|Burlesque}}==


<lang burlesque>
<syntaxhighlight lang="burlesque">
blsq ) 1 13r@{2.%n!}f[
blsq ) 1 13r@{2.%n!}f[
{2 4 6 8 10 12}
{2 4 6 8 10 12}
</syntaxhighlight>
</lang>


=={{header|BQN}}==
=={{header|BQN}}==
Line 741: Line 1,052:
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.
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.


<lang bqn>_filter ← {(𝔽𝕩)/𝕩}
<syntaxhighlight lang="bqn">_filter ← {(𝔽𝕩)/𝕩}
Odd ← 2⊸|
Odd ← 2⊸|


Odd _filter 1‿2‿3‿4‿5</lang>
Odd _filter 1‿2‿3‿4‿5</syntaxhighlight>
<lang>⟨ 1 3 5 ⟩</lang>
<syntaxhighlight lang="text">⟨ 1 3 5 ⟩</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 790: Line 1,101:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Filtered even: 2 4 6 8 10
<pre>Filtered even: 2 4 6 8 10
Line 797: Line 1,108:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
{{works with|.NET|1.1}}
{{works with|.NET|1.1}}
<lang csharp>ArrayList array = new ArrayList( new int[] { 1, 2, 3, 4, 5 } );
<syntaxhighlight lang="csharp">ArrayList array = new ArrayList( new int[] { 1, 2, 3, 4, 5 } );
ArrayList evens = new ArrayList();
ArrayList evens = new ArrayList();
foreach( int i in array )
foreach( int i in array )
Line 805: Line 1,116:
}
}
foreach( int i in evens )
foreach( int i in evens )
System.Console.WriteLine( i.ToString() );</lang>
System.Console.WriteLine( i.ToString() );</syntaxhighlight>
{{works with|.NET|2.0}}
{{works with|.NET|2.0}}
<lang csharp>List<int> array = new List<int>( new int[] { 1, 2, 3, 4, 5 } );
<syntaxhighlight 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; } );
List<int> evens = array.FindAll( delegate( int i ) { return (i%2)==0; } );
foreach( int i in evens )
foreach( int i in evens )
System.Console.WriteLine( i.ToString() );</lang>
System.Console.WriteLine( i.ToString() );</syntaxhighlight>
{{works with|.NET|3.5}}
{{works with|.NET|3.5}}
<lang csharp>IEnumerable<int> array = new List<int>( new int[] { 1, 2, 3, 4, 5 } );
<syntaxhighlight 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; } );
IEnumerable<int> evens = array.Where( delegate( int i ) { return (i%2)==0; } );
foreach( int i in evens )
foreach( int i in evens )
System.Console.WriteLine( i.ToString() );</lang>
System.Console.WriteLine( i.ToString() );</syntaxhighlight>
Replacing the delegate with the more concise lambda expression syntax.
Replacing the delegate with the more concise lambda expression syntax.
<lang csharp>int[] array = { 1, 2, 3, 4, 5 };
<syntaxhighlight lang="csharp">int[] array = { 1, 2, 3, 4, 5 };
int[] evens = array.Where(i => (i % 2) == 0).ToArray();
int[] evens = array.Where(i => (i % 2) == 0).ToArray();


foreach (int i in evens)
foreach (int i in evens)
Console.WriteLine(i);</lang>
Console.WriteLine(i);</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==


<lang cpp>#include <vector>
<syntaxhighlight lang="cpp">#include <vector>
#include <algorithm>
#include <algorithm>
#include <functional>
#include <functional>
Line 842: Line 1,153:


return 0;
return 0;
}</lang>
}</syntaxhighlight>




{{works with|C++11}}
{{works with|C++11}}
<lang cpp>#include <vector>
<syntaxhighlight lang="cpp">#include <vector>
#include <algorithm>
#include <algorithm>
#include <iterator>
#include <iterator>
Line 862: Line 1,173:
// print result
// print result
copy(evens.begin(), evens.end(), ostream_iterator<int>(cout, "\n"));
copy(evens.begin(), evens.end(), ostream_iterator<int>(cout, "\n"));
}</lang>
}</syntaxhighlight>


=={{header|Clean}}==
=={{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.
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.


<lang clean>module SelectFromArray
<syntaxhighlight lang="clean">module SelectFromArray


import StdEnv</lang>
import StdEnv</syntaxhighlight>


Create a lazy array where each element comes from the list 1 to 10.
Create a lazy array where each element comes from the list 1 to 10.


<lang clean>array :: {Int}
<syntaxhighlight lang="clean">array :: {Int}
array = {x \\ x <- [1 .. 10]}</lang>
array = {x \\ x <- [1 .. 10]}</syntaxhighlight>


Create (and print) a strict array where each element (coming from another array) is even.
Create (and print) a strict array where each element (coming from another array) is even.


<lang clean>Start :: {!Int}
<syntaxhighlight lang="clean">Start :: {!Int}
Start = {x \\ x <-: array | isEven x}</lang>
Start = {x \\ x <-: array | isEven x}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==


<lang lisp>;; range and filter create lazy seq's
<syntaxhighlight lang="lisp">;; range and filter create lazy seq's
(filter even? (range 0 100))
(filter even? (range 0 100))
;; vec will convert any type of seq to an array
;; vec will convert any type of seq to an array
(vec (filter even? (vec (range 0 100))))</lang>
(vec (filter even? (vec (range 0 100))))</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffee>[1..10].filter (x) -> not (x%2)</lang>
<syntaxhighlight lang="coffee">[1..10].filter (x) -> not (x%2)</syntaxhighlight>


{{out}}
{{out}}
Line 903: Line 1,214:
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:
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:


<lang lisp>(remove-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10))
<syntaxhighlight lang="lisp">(remove-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10))
> (2 4 6 8 10)</lang>
> (2 4 6 8 10)</syntaxhighlight>


However, this function is non-destructive, meaning the function creates a brand new list. This might be too prohibitive for very large lists.
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: Line 1,222:
There is a destructive version that modifies the list in-place:
There is a destructive version that modifies the list in-place:


<lang lisp>(delete-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10))
<syntaxhighlight lang="lisp">(delete-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10))
> (2 4 6 8 10)</lang>
> (2 4 6 8 10)</syntaxhighlight>


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";


# Cowgol has strict typing and there are no templates either.
# Cowgol has strict typing and there are no templates either.
Line 986: Line 1,297:
i := i + 1;
i := i + 1;
end loop;
end loop;
print_nl();</lang>
print_nl();</syntaxhighlight>
{{out}}
{{out}}
<pre>2 4 6 8 10
<pre>2 4 6 8 10
Line 992: Line 1,303:


=={{header|D}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.algorithm: filter, equal;
import std.algorithm: filter, equal;


Line 998: Line 1,309:
auto evens = data.filter!(x => x % 2 == 0); // Lazy.
auto evens = data.filter!(x => x % 2 == 0); // Lazy.
assert(evens.equal([2, 4, 6, 8, 10]));
assert(evens.equal([2, 4, 6, 8, 10]));
}</lang>
}</syntaxhighlight>
===Tango Version===
===Tango Version===
{{libheader|Tango}}
{{libheader|Tango}}
<lang d>import tango.core.Array, tango.io.Stdout;
<syntaxhighlight lang="d">import tango.core.Array, tango.io.Stdout;


void main() {
void main() {
Line 1,010: Line 1,321:
Stdout("Evens - ")( array[0 .. evens] ).newline; // The order of even elements is preserved
Stdout("Evens - ")( array[0 .. evens] ).newline; // The order of even elements is preserved
Stdout("Odds - ")( array[evens .. $].sort ).newline; // Unlike odd elements
Stdout("Odds - ")( array[evens .. $].sort ).newline; // Unlike odd elements
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> Evens - [ 2, 4, 6, 8, 10 ]
<pre> Evens - [ 2, 4, 6, 8, 10 ]
Line 1,017: Line 1,328:
=={{header|Delphi}}==
=={{header|Delphi}}==
===Hand-coded version===
===Hand-coded version===
<lang Delphi>program FilterEven;
<syntaxhighlight lang="delphi">program FilterEven;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,041: Line 1,352:
Write(i:3);
Write(i:3);
Writeln;
Writeln;
end.</lang>
end.</syntaxhighlight>




Line 1,050: Line 1,361:
{{libheader| Types}}
{{libheader| Types}}
{{libheader| Boost.Int}}
{{libheader| Boost.Int}}
<lang Delphi>program FilterEven;
<syntaxhighlight lang="delphi">program FilterEven;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,085: Line 1,396:
Writeln('[' + Source.Comma + ']');
Writeln('[' + Source.Comma + ']');
End.
End.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,096: Line 1,407:


===Non-destructively===
===Non-destructively===
<lang Dyalect>func Array.filter(pred) {
<syntaxhighlight lang="dyalect">func Array.Filter(pred) {
var arr = []
var arr = []
for x in this when pred(x) {
for x in this when pred(x) {
arr.add(x)
arr.Add(x)
}
}
arr
arr
}
}


var arr = [1..20].filter(x => x % 2 == 0)
var arr = [1..20].Filter(x => x % 2 == 0)
print(arr)</lang>
print(arr)</syntaxhighlight>


{{out}}
{{out}}
Line 1,112: Line 1,423:


===Destructively===
===Destructively===
<lang Dyalect>func Array.filter(pred) {
<syntaxhighlight lang="dyalect">func Array.Filter(pred) {
var i = 0
var i = 0
while i < this.len() {
while i < this.Length() {
if !pred(this[i]) {
if !pred(this[i]) {
this.removeAt(i)
this.RemoveAt(i)
}
}
i += 1
i += 1
Line 1,123: Line 1,434:


var arr = [1..20]
var arr = [1..20]
arr.filter(x => x % 2 == 0)
arr.Filter(x => x % 2 == 0)
print(arr)</lang>
print(arr)</syntaxhighlight>


{{out}}
{{out}}
Line 1,134: Line 1,445:
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:
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:


<syntaxhighlight lang="dyalect">var xs = [1..20]
<lang Dyalect>func Iterator.filter(pred) {
var arr = xs.Iterate().Filter(x => x % 2 == 0).Map(x => x.ToString())
for x in this when pred(x) {
print(arr.ToArray())</syntaxhighlight>
yield x
}
}

func Iterator.select(proj) {
for x in this {
yield proj(x)
}
}

var xs = [1..20]
var arr = xs.iter().filter(x => x % 2 == 0).select(x => x.toString())
print(arr.toArray())</lang>


{{out}}
{{out}}
Line 1,157: Line 1,456:


===Non-destructively===
===Non-destructively===
<lang dejavu>filter pred lst:
<syntaxhighlight lang="dejavu">filter pred lst:
]
]
for value in copy lst:
for value in copy lst:
Line 1,167: Line 1,466:
= 0 % x 2
= 0 % x 2


!. filter @even [ 0 1 2 3 4 5 6 7 8 9 ]</lang>
!. filter @even [ 0 1 2 3 4 5 6 7 8 9 ]</syntaxhighlight>


{{out}}
{{out}}
Line 1,174: Line 1,473:


===Destructively===
===Destructively===
<lang dejavu>local :lst [ 0 1 2 3 4 5 6 7 8 9 ]
<syntaxhighlight lang="dejavu">local :lst [ 0 1 2 3 4 5 6 7 8 9 ]


filter-destructively pred lst:
filter-destructively pred lst:
Line 1,189: Line 1,488:
filter-destructively @even lst
filter-destructively @even lst


!. lst</lang>
!. lst</syntaxhighlight>


{{out}}
{{out}}
Line 1,199: Line 1,498:
There are several ways this could be done.
There are several ways this could be done.


<lang e>pragma.enable("accumulator")
<syntaxhighlight lang="e">pragma.enable("accumulator")
accum [] for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] { _.with(x) }</lang>
accum [] for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] { _.with(x) }</syntaxhighlight>


<lang e>var result := []
<syntaxhighlight lang="e">var result := []
for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] {
for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] {
result with= x
result with= x
}
}
result</lang>
result</syntaxhighlight>


<lang e>def makeSeries := <elang:control.makeSeries>
<syntaxhighlight 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()</lang>
makeSeries([1,2,3,4,5,6,7,8,9,10]).filter(fn x,_{x %% 2 <=> 0}).asList()</syntaxhighlight>


=={{header|EasyLang}}==
=={{header|EasyLang}}==


<syntaxhighlight lang="text">
<lang>a[] = [ 1 2 3 4 5 6 7 8 9 ]
a[] = [ 1 2 3 4 5 6 7 8 9 ]
for i range len a[]
for i = 1 to len a[]
if a[i] mod 2 = 0
if a[i] mod 2 = 0
b[] &= a[i]
b[] &= a[i]
.
.
.
.
print b[]</lang>
print b[]
</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(iota 12) → { 0 1 2 3 4 5 6 7 8 9 10 11 }
(iota 12) → { 0 1 2 3 4 5 6 7 8 9 10 11 }


Line 1,240: Line 1,541:
→ (0 2 4 6 8 10 12 14 16 18 20 22)
→ (0 2 4 6 8 10 12 14 16 18 20 22)


</syntaxhighlight>
</lang>


=={{header|Ela}}==
=={{header|Ela}}==
Line 1,246: Line 1,547:
===Using higher-order function (non-strict version)===
===Using higher-order function (non-strict version)===


<lang ela>open list
<syntaxhighlight lang="ela">open list


evenList = filter' (\x -> x % 2 == 0) [1..]</lang>
evenList = filter' (\x -> x % 2 == 0) [1..]</syntaxhighlight>


===Using comprehension (non-strict version)===
===Using comprehension (non-strict version)===


<lang ela>evenList = [& x \\ x <- [1..] | x % 2 == 0]</lang>
<syntaxhighlight lang="ela">evenList = [& x \\ x <- [1..] | x % 2 == 0]</syntaxhighlight>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<lang elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import system'math;
import system'math;
import extensions;
import extensions;
Line 1,265: Line 1,566:
auto array := new int[]{1,2,3,4,5};
auto array := new int[]{1,2,3,4,5};


var evens := array.filterBy:(n => n.mod:2 == 0).toArray();
var evens := array.filterBy::(n => n.mod(2) == 0).toArray();


evens.forEach:printingLn
evens.forEach(printingLn)
}</lang>
}</syntaxhighlight>
Using strong typed collections and extensions:
Using strong typed collections and extensions:
<lang elena>import system'collections;
<syntaxhighlight lang="elena">import system'collections;
import system'routines'stex;
import system'routines'stex;
import system'math;
import system'math;
Line 1,280: Line 1,581:


array
array
.filterBy:(int n => n.mod:2 == 0)
.filterBy::(int n => n.mod(2) == 0)
.forEach:(int i){ console.printLine(i) }
.forEach::(int i){ console.printLine(i) }
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,290: Line 1,591:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>iex(10)> numbers = Enum.to_list(1..9)
<syntaxhighlight lang="elixir">iex(10)> numbers = Enum.to_list(1..9)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
iex(11)> Enum.filter(numbers, fn x -> rem(x,2)==0 end)
iex(11)> Enum.filter(numbers, fn x -> rem(x,2)==0 end)
[2, 4, 6, 8]
[2, 4, 6, 8]
iex(12)> for x <- numbers, rem(x,2)==0, do: x # comprehension
iex(12)> for x <- numbers, rem(x,2)==0, do: x # comprehension
[2, 4, 6, 8]</lang>
[2, 4, 6, 8]</syntaxhighlight>


=={{header|Emacs Lisp}}==
{{trans|Common_Lisp}}
<syntaxhighlight lang="lisp">
(seq-filter (lambda (x) (= (% x 2))) '(1 2 3 4 5 6 7 8 9 10))
</syntaxhighlight>

{{out}}

<pre>
(2 4 6 8 10)
</pre>

=={{header|EMal}}==
<syntaxhighlight lang="emal">
writeLine(range(1, 11).filter(<int i|i % 2 == 0))
</syntaxhighlight>
{{out}}
<pre>
[2,4,6,8,10]
</pre>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>Numbers = lists:seq(1, 5).
<syntaxhighlight lang="erlang">Numbers = lists:seq(1, 5).
EvenNumbers = lists:filter(fun (X) -> X rem 2 == 0 end, Numbers).</lang>
EvenNumbers = lists:filter(fun (X) -> X rem 2 == 0 end, Numbers).</syntaxhighlight>


Or using a list comprehension:
Or using a list comprehension:


<lang erlang>EvenNumbers = [X || X <- Numbers, X rem 2 == 0].</lang>
<syntaxhighlight lang="erlang">EvenNumbers = [X || X <- Numbers, X rem 2 == 0].</syntaxhighlight>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>sequence s, evens
<syntaxhighlight lang="euphoria">sequence s, evens
s = {1, 2, 3, 4, 5, 6}
s = {1, 2, 3, 4, 5, 6}
evens = {}
evens = {}
Line 1,314: Line 1,637:
end if
end if
end for
end for
? evens</lang>
? evens</syntaxhighlight>


{{out}}
{{out}}
Line 1,321: Line 1,644:


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
<lang fsharp>let lst = [1;2;3;4;5;6]
<syntaxhighlight lang="fsharp">let lst = [1;2;3;4;5;6]
List.filter (fun x -> x % 2 = 0) lst;;
List.filter (fun x -> x % 2 = 0) lst;;


val it : int list = [2; 4; 6]</lang>
val it : int list = [2; 4; 6]</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
Line 1,330: Line 1,653:
This code uses ''filter'' on an array.
This code uses ''filter'' on an array.


<lang factor>10 <iota> >array [ even? ] filter .
<syntaxhighlight lang="factor">10 <iota> >array [ even? ] filter .
! prints { 0 2 4 6 8 }</lang>
! prints { 0 2 4 6 8 }</syntaxhighlight>


''10 <iota>'' is already a sequence, so we can skip the conversion to array.
''10 <iota>'' is already a sequence, so we can skip the conversion to array.


<lang factor>10 <iota> [ even? ] filter .
<syntaxhighlight lang="factor">10 <iota> [ even? ] filter .
! prints V{ 0 2 4 5 8 }</lang>
! prints V{ 0 2 4 5 8 }</syntaxhighlight>


=== Destructive ===
=== Destructive ===
This uses ''filter!'' to modify the original vector.
This uses ''filter!'' to modify the original vector.


<lang factor>USE: vectors
<syntaxhighlight lang="factor">USE: vectors
10 <iota> >vector [ even? ] filter! .
10 <iota> >vector [ even? ] filter! .
! prints V{ 0 2 4 5 8 }</lang>
! prints V{ 0 2 4 5 8 }</syntaxhighlight>


To prove that ''filter!'' is destructive but ''filter'' is non-destructive, I assign the original vector to ''v''.
To prove that ''filter!'' is destructive but ''filter'' is non-destructive, I assign the original vector to ''v''.


<lang factor>USE: locals
<syntaxhighlight lang="factor">USE: locals
10 <iota> >vector [| v |
10 <iota> >vector [| v |
v [ even? ] filter drop
v [ even? ] filter drop
Line 1,355: Line 1,678:
] call
] call
! V{ 0 1 2 3 4 5 6 7 8 9 } after filter
! V{ 0 1 2 3 4 5 6 7 8 9 } after filter
! V{ 0 2 4 6 8 } after filter!</lang>
! V{ 0 2 4 6 8 } after filter!</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==


<lang fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 1,371: Line 1,694:
}
}
}
}
</syntaxhighlight>
</lang>

=={{header|Fe}}==
<syntaxhighlight lang="clojure">
(= filter (fn (f lst)
(let res (cons nil nil))
(let tail res)
(while lst
(let item (car lst))
(if (f item) (do
(setcdr tail (cons item nil))
(= tail (cdr tail))))
(= lst (cdr lst)))
(cdr res)))

(print (filter (fn (x) (< 5 x)) '(1 4 5 6 3 2 7 9 0 8)))
</syntaxhighlight>
Outputs:
<syntaxhighlight lang="clojure">
(6 7 9 8)
</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: sel ( dest 0 test src len -- dest len )
<syntaxhighlight lang="forth">: sel ( dest 0 test src len -- dest len )
cells over + swap do ( dest len test )
cells over + swap do ( dest len test )
i @ over execute if
i @ over execute if
Line 1,389: Line 1,732:
: even? ( n -- ? ) 1 and 0= ;
: even? ( n -- ? ) 1 and 0= ;


evens 0 ' even? nums 6 sel .array \ 2 4 6</lang>
evens 0 ' even? nums 6 sel .array \ 2 4 6</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==


<lang fortran>module funcs
<syntaxhighlight lang="fortran">module funcs
implicit none
implicit none
contains
contains
Line 1,401: Line 1,744:
iseven = mod(x, 2) == 0
iseven = mod(x, 2) == 0
end function iseven
end function iseven
end module funcs</lang>
end module funcs</syntaxhighlight>


<lang fortran>program Filter
<syntaxhighlight lang="fortran">program Filter
use funcs
use funcs
implicit none
implicit none
Line 1,445: Line 1,788:
end function filterwith
end function filterwith


end program Filter</lang>
end program Filter</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Type FilterType As Function(As Integer) As Boolean
Type FilterType As Function(As Integer) As Boolean
Line 1,510: Line 1,853:
End
End


Data 1, 2, 3, 7, 8, 10, 11, 16, 19, 21, 22, 27</lang>
Data 1, 2, 3, 7, 8, 10, 11, 16, 19, 21, 22, 27</syntaxhighlight>


{{out}}
{{out}}
Line 1,520: Line 1,863:


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>
<syntaxhighlight lang="frink">
b = array[1 to 100]
b = array[1 to 100]
c = select[b, {|x| x mod 2 == 0}]
c = select[b, {|x| x mod 2 == 0}]
</syntaxhighlight>
</lang>


=={{header|Futhark}}==
=={{header|Futhark}}==
{{incorrect|Futhark|Futhark's syntax has changed, so this example will not compile}}
{{incorrect|Futhark|Futhark's syntax has changed, so this example will not compile}}


<syntaxhighlight lang="futhark">
<lang Futhark>
fun main(as: []int): []int =
fun main(as: []int): []int =
filter (fn x => x%2 == 0) as
filter (fn x => x%2 == 0) as
</syntaxhighlight>
</lang>

=={{header|FutureBasic}}==
Even elements from array added to new array.
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"

local fn EvenNumbersFromArrayToNewArray
CFArrayRef numbersArray = @[@1,@2,@3,@4,@5,@6,@7,@8,@9,@10,@11,@12]
PredicateRef isEvenPred = fn PredicateWithFormat( @"modulus:by:(SELF, 2) == 0" )
CFArrayRef evensArray = fn ArrayFilteredArrayUsingPredicate( numbersArray, isEvenPred )
NSLog( @"Array of odd and even numbers before sort:\n\t%@\n", numbersArray )
NSLog( @"New array of even numbers after sort:\n\t%@\n", evensArray )
end fn
fn EvenNumbersFromArrayToNewArray
NSLogScrollToTop
</syntaxhighlight>
Destructive version: Odd elemnts removed from mutable array.
<syntaxhighlight>
local fn OddNumbersRemovedFromArray
CFMutablearrayRef mutableNumbersArray = fn MutableArrayWithArray( @[@1,@2,@3,@4,@5,@6,@7,@8,@9,@10,@11,@12] )
NSLog( @"Mutable array of odd and even numbers before sort:\n\t%@\n", mutableNumbersArray )
PredicateRef isEvenPred = fn PredicateWithFormat( @"modulus:by:(SELF, 2) == 0" )
MutableArrayFilterUsingPredicate( mutableNumbersArray, isEvenPred )
NSLog( @"Mutable array with odd numbers removed:\n\t%@\n", mutableNumbersArray )
end fn

fn OddNumbersRemovedFromArray
NSLogScrollToTop

HandleEvents
</syntaxhighlight>
{{output}}
<pre style="height:20ex;">

Array of odd and even numbers before sort:
(
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12
)

New array of even numbers after sort:
(
2,
4,
6,
8,
10,
12
)

Mutable array of odd and even numbers before sort:
(
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12
)

Mutable array with odd numbers removed:
(
2,
4,
6,
8,
10,
12
)
</pre>





=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=e73bc5db1e3bb56c598f89aa669a0825 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=e73bc5db1e3bb56c598f89aa669a0825 Click this link to run this code]'''
<lang gambas>sRandom As New String[]
<syntaxhighlight lang="gambas">sRandom As New String[]
'______________________________________________________________________________________________________
'______________________________________________________________________________________________________
Public Sub Main()
Public Sub Main()
Line 1,577: Line 2,009:
Print sRandom.join(",")
Print sRandom.join(",")


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,586: Line 2,018:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap># Built-in
<syntaxhighlight lang="gap"># Built-in


Filtered([1 .. 100], IsPrime);
Filtered([1 .. 100], IsPrime);
Line 1,595: Line 2,027:


Filtered([1 .. 10], IsOddInt);
Filtered([1 .. 10], IsOddInt);
# [ 1, 3, 5, 7, 9 ]</lang>
# [ 1, 3, 5, 7, 9 ]</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,637: Line 2,069:
}
}
*pa = a[:last]
*pa = a[:last]
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,648: Line 2,080:


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy> def evens = [1, 2, 3, 4, 5].findAll{it % 2 == 0}</lang>
<syntaxhighlight lang="groovy"> def evens = [1, 2, 3, 4, 5].findAll{it % 2 == 0}</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
Line 1,654: Line 2,086:
In Haskell, a list is often more basic than an array:
In Haskell, a list is often more basic than an array:


<lang haskell>ary = [1..10]
<syntaxhighlight lang="haskell">ary = [1..10]
evens = [x | x <- ary, even x]</lang>
evens = [x | x <- ary, even x]</syntaxhighlight>
or
or
<lang haskell>evens = filter even ary</lang>
<syntaxhighlight lang="haskell">evens = filter even ary</syntaxhighlight>


To do the same operation on an array, the simplest way it to convert it lazily into a list:
To do the same operation on an array, the simplest way it to convert it lazily into a list:


<lang haskell>import Data.Array
<syntaxhighlight lang="haskell">import Data.Array


ary = listArray (1,10) [1..10]
ary = listArray (1,10) [1..10]
evens = listArray (1,n) l where
evens = listArray (1,n) l where
n = length l
n = length l
l = [x | x <- elems ary, even x]</lang>
l = [x | x <- elems ary, even x]</syntaxhighlight>


Note that the bounds must be known before creating the array, so the temporary list will be fully evaluated before the array is created.
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}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()


every put(A := [],1 to 10) # make a list of 1..10
every put(A := [],1 to 10) # make a list of 1..10
Line 1,680: Line 2,112:
procedure iseven(x) #: return x if x is even or fail
procedure iseven(x) #: return x if x is even or fail
if x % 2 = 0 then return x
if x % 2 = 0 then return x
end</lang>
end</syntaxhighlight>


=={{header|IDL}}==
=={{header|IDL}}==
The <tt>where()</tt> function can select elements on any logical expression. For example
The <tt>where()</tt> function can select elements on any logical expression. For example


<lang idl>result = array[where(NOT array AND 1)]</lang>
<syntaxhighlight lang="idl">result = array[where(NOT array AND 1)]</syntaxhighlight>

=={{header|Insitux}}==
<syntaxhighlight lang="insitux">> (filter even? [0 1 2 3 4])
[0 2 4]

> (var x [0 1 2 3 4])
[0 1 2 3 4]

> (var! x (filter even?)) ;replaces variable x by applying implicit closure
[0 2 4]
</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
'''Solution:'''<br>
'''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:
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:
<lang j> (#~ f) v</lang>
<syntaxhighlight lang="j"> (#~ f) v</syntaxhighlight>


'''Examples:'''
'''Examples:'''
<lang j> ] v=: 20 ?@$ 100 NB. vector of 20 random integers between 0 and 99
<syntaxhighlight 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
63 92 51 92 39 15 43 89 36 69 40 16 23 2 29 91 57 43 55 22


v #~ -.2| v
v #~ -.2| v
92 92 36 40 16 2 22</lang>
92 92 36 40 16 2 22</syntaxhighlight>


Or using the generic form suggested above:
Or using the generic form suggested above:
<lang j> isEven=: 0 = 2&| NB. verb testing for even numbers
<syntaxhighlight lang="j"> isEven=: 0 = 2&| NB. verb testing for even numbers
(#~ isEven) v
(#~ isEven) v
92 92 36 40 16 2 22</lang>
92 92 36 40 16 2 22</syntaxhighlight>


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.
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.
<lang j> select=: adverb def '(#~ u)'
<syntaxhighlight lang="j"> select=: adverb def '(#~ u)'
isPrime=: 1&p:
isPrime=: 1&p:


Line 1,713: Line 2,156:
43 89 23 2 29 43
43 89 23 2 29 43
(isEven *. isPrime) select v
(isEven *. isPrime) select v
2</lang>
2</syntaxhighlight>


Destructive example:
Destructive example:


<lang j> v=: isEven select v</lang>
<syntaxhighlight lang="j"> v=: isEven select v</syntaxhighlight>


(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.)
(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|Jakt}}==
<syntaxhighlight lang="jakt">
fn filter<T>(anon array: [T], anon filter_function: fn(anon value: T) -> bool) throws -> [T] {
mut result: [T] = []
for value in array {
if filter_function(value) {
result.push(value)
}
}
return result
}

fn main() {
mut numbers: [i64] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let filtered = filter(numbers, fn(anon x: i64) -> bool => x % 2 == 0)
println("{}", filtered)
}
</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>int[] array = {1, 2, 3, 4, 5 };
<syntaxhighlight lang="java">int[] array = {1, 2, 3, 4, 5 };
List<Integer> evensList = new ArrayList<Integer>();
List<Integer> evensList = new ArrayList<Integer>();
for (int i: array) {
for (int i: array) {
if (i % 2 == 0) evensList.add(i);
if (i % 2 == 0) evensList.add(i);
}
}
int[] evens = evensList.toArray(new int[0]);</lang>
int[] evens = evensList.toArray(new int[0]);</syntaxhighlight>


----
----


A Java 8 solution with stream and generic types:
A Java 8 solution with stream and generic types:
<lang java>public static <T> T[] filter(T[] input, Predicate<T> filterMethod) {
<syntaxhighlight lang="java">public static <T> T[] filter(T[] input, Predicate<T> filterMethod) {
return Arrays.stream(input)
return Arrays.stream(input)
.filter(filterMethod)
.filter(filterMethod)
.toArray(size -> (T[]) Array.newInstance(input.getClass().getComponentType(), size));
.toArray(size -> (T[]) Array.newInstance(input.getClass().getComponentType(), size));
}</lang>
}</syntaxhighlight>
Methodcall:
Methodcall:
<lang java>Integer[] array = {1, 2, 3, 4, 5};
<syntaxhighlight lang="java">Integer[] array = {1, 2, 3, 4, 5};
Integer[] result = filter(array, i -> (i % 2) == 0);</lang>
Integer[] result = filter(array, i -> (i % 2) == 0);</syntaxhighlight>
Warning: This solution works not with primitive types!<br/>
Warning: This solution works not with primitive types!<br/>
For arrays with a primitive type use the wrapper class.
For arrays with a primitive type use the wrapper class.


=={{header|JavaFX Script}}==
=={{header|JavaFX Script}}==
<lang javafx>def array = [1..100];
<syntaxhighlight lang="javafx">def array = [1..100];
def evens = array[n | n mod 2 == 0];</lang>
def evens = array[n | n mod 2 == 0];</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
===ES5===
===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}}):
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}}):
<lang javascript>var arr = [1,2,3,4,5];
<syntaxhighlight lang="javascript">var arr = [1,2,3,4,5];
var evens = arr.filter(function(a) {return a % 2 == 0});</lang>
var evens = arr.filter(function(a) {return a % 2 == 0});</syntaxhighlight>


Other ways:
Other ways:
<lang javascript>var arr = [1,2,3,4,5];
<syntaxhighlight lang="javascript">var arr = [1,2,3,4,5];
var evens = [];
var evens = [];
for (var i=0, ilen=arr.length; i<ilen; i++)
for (var i=0, ilen=arr.length; i<ilen; i++)
if (arr[i] % 2 == 0)
if (arr[i] % 2 == 0)
evens.push(arr[i]);</lang>
evens.push(arr[i]);</syntaxhighlight>


{{works with|Firefox|2.0}}
{{works with|Firefox|2.0}}


<lang javascript>var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
<syntaxhighlight 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)];
var evens = [i for (i in numbers) if (i % 2 == 0)];


Line 1,771: Line 2,233:
}
}


var evens2 = [i for (i in range(100)) if (i % 2 == 0)];</lang>
var evens2 = [i for (i in range(100)) if (i % 2 == 0)];</syntaxhighlight>


{{libheader|Functional}}
{{libheader|Functional}}
<lang javascript>Functional.select("+1&1", [1,2,3,4]) // [2, 4]</lang>
<syntaxhighlight lang="javascript">Functional.select("+1&1", [1,2,3,4]) // [2, 4]</syntaxhighlight>


===ES6===
===ES6===


<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 1,791: Line 2,253:


// [2, 4, 6, 8]
// [2, 4, 6, 8]
})();</lang>
})();</syntaxhighlight>


{{Out}}
{{Out}}
<lang JavaScript>[2, 4, 6, 8]</lang>
<syntaxhighlight lang="javascript">[2, 4, 6, 8]</syntaxhighlight>

=={{header|Joy}}==
<syntaxhighlight lang="joy">[1 2 3 4 5 6 7 8 9 10] [2 rem null] filter.</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
jq's "select" filter is designed to make it easy to filter both arrays and streams:
jq's "select" filter is designed to make it easy to filter both arrays and streams:
<lang jq>(1,2,3,4,5,6,7,8,9) | select(. % 2 == 0)</lang>
<syntaxhighlight lang="jq">(1,2,3,4,5,6,7,8,9) | select(. % 2 == 0)</syntaxhighlight>
{{Out}}
{{Out}}
2
2
Line 1,804: Line 2,269:
6
6
8
8
<syntaxhighlight lang="jq">
<lang jq>
[range(1;10)] | map( select(. % 2 == 0) )
[range(1;10)] | map( select(. % 2 == 0) )
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
[2,4,6,8]
[2,4,6,8]
Line 1,813: Line 2,278:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<lang julia>@show filter(iseven, 1:10)</lang>
<syntaxhighlight lang="julia">@show filter(iseven, 1:10)</syntaxhighlight>


{{out}}
{{out}}
Line 1,819: Line 2,284:


=={{header|K}}==
=={{header|K}}==
<lang K> / even is a boolean function
<syntaxhighlight lang="k"> / even is a boolean function
even:{0=x!2}
even:{0=x!2}
even 1 2 3 4 5
even 1 2 3 4 5
Line 1,833: Line 2,298:
45 5 79 77 44 15 83 88 33 99
45 5 79 77 44 15 83 88 33 99
evens a
evens a
44 88</lang>
44 88</syntaxhighlight>


Alternative syntax:
Alternative syntax:
<lang K> {x[&0=x!2]}
<syntaxhighlight lang="k"> {x[&0=x!2]}
{x[&even x]}</lang>
{x[&even x]}</syntaxhighlight>


Destructive:
Destructive:
<lang K> a:evens a
<syntaxhighlight lang="k"> a:evens a
44 88</lang>
44 88</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.5-2
<syntaxhighlight lang="scala">// version 1.0.5-2


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 1,856: Line 2,321:
mutableList.retainAll { it % 2 == 0 }
mutableList.retainAll { it % 2 == 0 }
println(mutableList.joinToString(" "))
println(mutableList.joinToString(" "))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,867: Line 2,332:
=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==


<lang scheme>
<syntaxhighlight lang="scheme">


{def filter
{def filter
{lambda {:bool :a}
{lambda {:bool :s}
{if {S.empty? {S.rest :a}}
{:bool {S.first :s}}
then {:bool {S.first :a}}
{if {> {S.length :s} 1}
else {:bool {S.first :a}}
then {filter :bool {S.rest :s}}
else}}}
{filter :bool {S.rest :a}}}}}
-> filter


{def even? {lambda {:w} {if {= {% :w 2} 0} then :w else}}}
{def even? {lambda {:n} {if {= {% :n 2} 0} then :n else}}}
-> even?
{def odd? {lambda {:w} {if {= {% :w 2} 1} then :w else}}}
{def odd? {lambda {:n} {if {= {% :n 2} 1} then :n else}}}
-> odd?


{filter even? {S.serie 1 20}}
{filter even? {S.serie 1 20}}
Line 1,884: Line 2,352:
-> 1 3 5 7 9 11 13 15 17 19
-> 1 3 5 7 9 11 13 15 17 19


</syntaxhighlight>
</lang>

=={{header|Lang}}==
Solution with isEven function:
<syntaxhighlight lang="lang">
&arr = fn.arrayGenerateFrom(fn.inc, 10)
fp.isEven = ($x) -> return parser.op($x % 2 === 0)
&filteredArr = fn.arrayFiltered(&arr, fp.isEven)
fn.println(&arr)
fn.println(&filteredArr)
</syntaxhighlight>
{{out}}
<pre>
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 4, 6, 8, 10]
</pre>
Solution with combinator functions:
<syntaxhighlight lang="lang">
&arr = fn.arrayGenerateFrom(fn.inc, 10)
&filteredArr = fn.arrayFiltered(&arr, fn.combC(fn.combX1(fn.conStrictEquals, fn.combC(fn.mod, 2)), 0))
fn.println(&arr)
fn.println(&filteredArr)
</syntaxhighlight>
{{out}}
<pre>
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 4, 6, 8, 10]
</pre>


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang lang5>: filter over swap execute select ;
<syntaxhighlight lang="lang5">: filter over swap execute select ;
10 iota "2 % not" filter . "\n" .
10 iota "2 % not" filter . "\n" .


# [ 0 2 4 6 8 ]</lang>
# [ 0 2 4 6 8 ]</syntaxhighlight>


=={{header|langur}}==
=={{header|langur}}==
Using the where() function filters by a function and returns an array of values. Using wherekeys() filters the same way, but returns an array of keys instead.
Using the filter() function filters by a function or regex and returns a list of values.


<syntaxhighlight lang="langur">val .list = series 7
{{works with|langur|0.8.1}}
<lang langur>val .arr = series 7


writeln " array: ", .arr
writeln " list: ", .list
writeln "filtered: ", where f .x div 2, .arr</lang>
writeln "filtered: ", filter fn{div 2}, .list
</syntaxhighlight>


{{out}}
{{out}}
<pre> array: [1, 2, 3, 4, 5, 6, 7]
<pre> list: [1, 2, 3, 4, 5, 6, 7]
filtered: [2, 4, 6]</pre>
filtered: [2, 4, 6]</pre>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>local(original = array(1,2,3,4,5,6,7,8,9,10))
<syntaxhighlight lang="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)
local(evens = (with item in #original where #item % 2 == 0 select #item) -> asstaticarray)
#evens</lang>
#evens</syntaxhighlight>
<pre>staticarray(2, 4, 6, 8, 10)</pre>
<pre>staticarray(2, 4, 6, 8, 10)</pre>


Modifying the original array
Modifying the original array
<lang lasso>local(original = array(1,2,3,4,5,6,7,8,9,10))
<syntaxhighlight 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)
with item in #original where #item % 2 != 0 do #original ->removeall(#item)
#original</lang>
#original</syntaxhighlight>
<pre>array(2, 4, 6, 8, 10)</pre>
<pre>array(2, 4, 6, 8, 10)</pre>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>' write random nos between 1 and 100
<syntaxhighlight lang="lb">' write random nos between 1 and 100
' to array1 counting matches as we go
' to array1 counting matches as we go
dim array1(100)
dim array1(100)
Line 1,938: Line 2,433:
for n=1 to count
for n=1 to count
print array2(n)
print array2(n)
next</lang>
next</syntaxhighlight>


=={{header|Lisaac}}==
=={{header|Lisaac}}==
<lang Lisaac>+ a, b : ARRAY[INTEGER];
<syntaxhighlight lang="lisaac">+ a, b : ARRAY[INTEGER];
a := ARRAY[INTEGER].create_with_capacity 10 lower 0;
a := ARRAY[INTEGER].create_with_capacity 10 lower 0;
b := ARRAY[INTEGER].create_with_capacity 10 lower 0;
b := ARRAY[INTEGER].create_with_capacity 10 lower 0;
Line 1,951: Line 2,446:
b.add_last item;
b.add_last item;
};
};
};</lang>
};</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to even? :n
<syntaxhighlight lang="logo">to even? :n
output equal? 0 modulo :n 2
output equal? 0 modulo :n 2
end
end
show filter "even? [1 2 3 4] ; [2 4]
show filter "even? [1 2 3 4] ; [2 4]


show filter [equal? 0 modulo ? 2] [1 2 3 4]</lang>
show filter [equal? 0 modulo ? 2] [1 2 3 4]</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function filter(t, func)
<syntaxhighlight lang="lua">function filter(t, func)
local ret = {}
local ret = {}
for i, v in ipairs(t) do
for i, v in ipairs(t) do
Line 1,972: Line 2,467:
function even(a) return a % 2 == 0 end
function even(a) return a % 2 == 0 end


print(unpack(filter({1, 2, 3, 4 ,5, 6, 7, 8, 9, 10}, even)))</lang>
print(unpack(filter({1, 2, 3, 4 ,5, 6, 7, 8, 9, 10}, even)))</syntaxhighlight>


The destructive version is even simpler, since tables are passed by reference:
The destructive version is even simpler, since tables are passed by reference:


<lang lua>function filter(t, func)
<syntaxhighlight lang="lua">function filter(t, func)
for i, v in ipairs(t) do
for i, v in ipairs(t) do
if not func(v) then table.remove(t, i) end
if not func(v) then table.remove(t, i) end
Line 1,986: Line 2,481:
local values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
local values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
filter(values, even)
filter(values, even)
print(unpack(values))</lang>
print(unpack(values))</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
===Using Filter for arrays===
===Using Filter for arrays===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
Print (1,2,3,4,5,6,7,8)#filter(lambda ->number mod 2=0)
Print (1,2,3,4,5,6,7,8)#filter(lambda ->number mod 2=0)
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


===Old style===
===Old style===
Line 2,008: Line 2,503:




<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Module CheckIt {
Function GetEvenNumbers (A as array){
Function GetEvenNumbers (A as array){
Line 2,060: Line 2,555:
}
}
CheckIt
CheckIt
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
evennum:=proc(nums::list(integer))
evennum:=proc(nums::list(integer))
return select(x->type(x, even), nums);
return select(x->type(x, even), nums);
end proc;
end proc;
</syntaxhighlight>
</lang>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Check for even integers:
Check for even integers:
<lang Mathematica>Select[{4, 5, Pi, 2, 1.3, 7, 6, 8.0}, EvenQ]</lang>
<syntaxhighlight lang="mathematica">Select[{4, 5, Pi, 2, 1.3, 7, 6, 8.0}, EvenQ]</syntaxhighlight>
gives:
gives:
<lang Mathematica>{4, 2, 6}</lang>
<syntaxhighlight lang="mathematica">{4, 2, 6}</syntaxhighlight>
To check also for approximate number (like 8.0 in the example above) a possible solution is:
To check also for approximate number (like 8.0 in the example above) a possible solution is:
<lang Mathematica>Select[{4, 5, Pi, 2, 1.3, 7, 6, 8.0}, Mod[#, 2] == 0 &]</lang>
<syntaxhighlight lang="mathematica">Select[{4, 5, Pi, 2, 1.3, 7, 6, 8.0}, Mod[#, 2] == 0 &]</syntaxhighlight>
gives:
gives:
<lang Mathematica>{4, 2, 6, 8.}</lang>
<syntaxhighlight lang="mathematica">{4, 2, 6, 8.}</syntaxhighlight>
notice that the function returns 8. not 8 (the dot indicates that it is a float number, not an integer).
notice that the function returns 8. not 8 (the dot indicates that it is a float number, not an integer).


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang MATLAB>function evens = selectEvenNumbers(list)
<syntaxhighlight lang="matlab">function evens = selectEvenNumbers(list)


evens = list( mod(list,2) == 0 );
evens = list( mod(list,2) == 0 );


end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
<lang MATLAB>>> selectEvenNumbers([0 1 2 3 4 5 6 7 8 9 10])
<syntaxhighlight lang="matlab">>> selectEvenNumbers([0 1 2 3 4 5 6 7 8 9 10])


ans =
ans =


0 2 4 6 8 10</lang>
0 2 4 6 8 10</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>a: makelist(i, i, 1, 20);
<syntaxhighlight 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]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]


Line 2,102: Line 2,597:


sublist(a, lambda([n], mod(n, 3) = 0));
sublist(a, lambda([n], mod(n, 3) = 0));
[3, 6, 9, 12, 15, 18]</lang>
[3, 6, 9, 12, 15, 18]</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>arr = #(1, 2, 3, 4, 5, 6, 7, 8, 9)
<syntaxhighlight lang="maxscript">arr = #(1, 2, 3, 4, 5, 6, 7, 8, 9)
newArr = for i in arr where (mod i 2 == 0) collect i</lang>
newArr = for i in arr where (mod i 2 == 0) collect i</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>(1 2 3 4 5 6 7 8 9 10) 'even? filter print</lang>
<syntaxhighlight lang="min">(1 2 3 4 5 6 7 8 9 10) 'even? filter print</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,118: Line 2,613:
=={{header|MiniScript}}==
=={{header|MiniScript}}==
We define a ''filter'' method on the list type that returns a new list containing elements filtered by the given function.
We define a ''filter'' method on the list type that returns a new list containing elements filtered by the given function.
<lang MiniScript>list.filter = function(f)
<syntaxhighlight lang="miniscript">list.filter = function(f)
result = []
result = []
for item in self
for item in self
Line 2,131: Line 2,626:


nums = [1, 2, 3, 4, 5, 6, 7, 9, 12, 15, 18, 21]
nums = [1, 2, 3, 4, 5, 6, 7, 9, 12, 15, 18, 21]
print nums.filter(@isEven)</lang>
print nums.filter(@isEven)</syntaxhighlight>


The in-place version is simpler, and even allows the use of an unnamed filter function, defined right on the method call.
The in-place version is simpler, and even allows the use of an unnamed filter function, defined right on the method call.
<lang MiniScript>list.filterInPlace = function(f)
<syntaxhighlight lang="miniscript">list.filterInPlace = function(f)
for i in range(self.len-1, 0)
for i in range(self.len-1, 0)
if not f(self[i]) then self.remove i
if not f(self[i]) then self.remove i
Line 2,146: Line 2,641:
end function
end function


print nums</lang>
print nums</syntaxhighlight>


=={{header|ML}}==
=={{header|ML}}==
==={{header|Standard ML}}===
==={{header|Standard ML}}===
<lang sml>val ary = [1,2,3,4,5,6];
<syntaxhighlight lang="sml">val ary = [1,2,3,4,5,6];
List.filter (fn x => x mod 2 = 0) ary</lang>
List.filter (fn x => x mod 2 = 0) ary</syntaxhighlight>
==={{header|MLite}}===
==={{header|MLite}}===
MLite is similar to Standard ML, though '=>' becomes '=' and 'List.' is elided:
MLite is similar to Standard ML, though '=>' becomes '=' and 'List.' is elided:
<lang ocaml>val ary = [1,2,3,4,5,6];
<syntaxhighlight lang="ocaml">val ary = [1,2,3,4,5,6];
filter (fn x = x mod 2 = 0) ary;</lang>
filter (fn x = x mod 2 = 0) ary;</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<lang MUMPS>FILTERARRAY
<syntaxhighlight lang="mumps">FILTERARRAY
;NEW I,J,A,B - Not making new, so we can show the values
;NEW I,J,A,B - Not making new, so we can show the values
;Populate array A
;Populate array A
Line 2,164: Line 2,659:
;Move even numbers into B
;Move even numbers into B
SET J=0 FOR I=1:1:10 SET:A(I)#2=0 B($INCREMENT(J))=A(I)
SET J=0 FOR I=1:1:10 SET:A(I)#2=0 B($INCREMENT(J))=A(I)
QUIT</lang>
QUIT</syntaxhighlight>
Testing:<pre>WRITE
Testing:<pre>WRITE


Line 2,187: Line 2,682:
=={{header|Nemerle}}==
=={{header|Nemerle}}==
Lists have a built-in method for filtering:
Lists have a built-in method for filtering:
<lang Nemerle>def original = $[1 .. 100];
<syntaxhighlight lang="nemerle">def original = $[1 .. 100];
def filtered = original.Filter(fun(n) {n % 2 == 0});
def filtered = original.Filter(fun(n) {n % 2 == 0});
WriteLine($"$filtered");</lang>
WriteLine($"$filtered");</syntaxhighlight>
The following would work for arrays:
The following would work for arrays:
<lang Nemerle>Filter[T] (a : array[T], f : T -> bool) : array[T]
<syntaxhighlight lang="nemerle">Filter[T] (a : array[T], f : T -> bool) : array[T]
{
{
def b = $[x | x in a, (f(x))];
def b = $[x | x in a, (f(x))];
b.ToArray()
b.ToArray()
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary
numeric digits 5000
numeric digits 5000
Line 2,261: Line 2,756:
ry = Rexx[] clist.toArray(Rexx[clist.size()])
ry = Rexx[] clist.toArray(Rexx[clist.size()])
return ry
return ry
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,278: Line 2,773:


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>> (filter (fn (x) (= (% x 2) 0)) '(1 2 3 4 5 6 7 8 9 10))
<syntaxhighlight lang="newlisp">> (filter (fn (x) (= (% x 2) 0)) '(1 2 3 4 5 6 7 8 9 10))
(2 4 6 8 10)
(2 4 6 8 10)
</syntaxhighlight>
</lang>

=={{header|NGS}}==
<syntaxhighlight lang="ngs">F even(x:Int) x % 2 == 0

evens = Arr(1...10).filter(even)</syntaxhighlight>


=={{header|Nial}}==
=={{header|Nial}}==
<lang nial>filter (= [0 first, mod [first, 2 first] ] ) 0 1 2 3 4 5 6 7 8 9 10
<syntaxhighlight 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</lang>
=0 2 4 6 8 10</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import sequtils
<syntaxhighlight lang="nim">import sequtils


let values = toSeq(0..9)
let values = toSeq(0..9)
Line 2,305: Line 2,805:
var v2 = toSeq(0..9)
var v2 = toSeq(0..9)
v2.keepItIf(it mod 2 != 0)
v2.keepItIf(it mod 2 != 0)
echo "Odd values: ", v2</lang>
echo "Odd values: ", v2</syntaxhighlight>


{{out}}
{{out}}
Line 2,314: Line 2,814:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
use Structure;
use Structure;


Line 2,334: Line 2,834:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
{{works with|Cocoa|Mac OS X 10.6+}}
{{works with|Cocoa|Mac OS X 10.6+}}
<lang objc>NSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],
<syntaxhighlight lang="objc">NSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:3],
[NSNumber numberWithInt:3],
Line 2,344: Line 2,844:
[NSNumber numberWithInt:5], nil];
[NSNumber numberWithInt:5], nil];
NSArray *evens = [numbers objectsAtIndexes:[numbers indexesOfObjectsPassingTest:
NSArray *evens = [numbers objectsAtIndexes:[numbers indexesOfObjectsPassingTest:
^BOOL(id obj, NSUInteger idx, BOOL *stop) { return [obj intValue] % 2 == 0; } ]];</lang>
^BOOL(id obj, NSUInteger idx, BOOL *stop) { return [obj intValue] % 2 == 0; } ]];</syntaxhighlight>


{{works with|Cocoa|Mac OS X 10.5+}}
{{works with|Cocoa|Mac OS X 10.5+}}
<lang objc>NSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],
<syntaxhighlight lang="objc">NSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:3],
[NSNumber numberWithInt:3],
Line 2,353: Line 2,853:
[NSNumber numberWithInt:5], nil];
[NSNumber numberWithInt:5], nil];
NSPredicate *isEven = [NSPredicate predicateWithFormat:@"modulus:by:(SELF, 2) == 0"];
NSPredicate *isEven = [NSPredicate predicateWithFormat:@"modulus:by:(SELF, 2) == 0"];
NSArray *evens = [numbers filteredArrayUsingPredicate:isEven];</lang>
NSArray *evens = [numbers filteredArrayUsingPredicate:isEven];</syntaxhighlight>


{{works with|GNUstep}}
{{works with|GNUstep}}
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


@interface NSNumber ( ExtFunc )
@interface NSNumber ( ExtFunc )
Line 2,387: Line 2,887:
[pool release];
[pool release];
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
It is easier to do it with a list:
It is easier to do it with a list:
<lang ocaml>let lst = [1;2;3;4;5;6]
<syntaxhighlight lang="ocaml">let lst = [1;2;3;4;5;6]
let even_lst = List.filter (fun x -> x mod 2 = 0) lst</lang>
let even_lst = List.filter (fun x -> x mod 2 = 0) lst</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==
<lang octave>arr = [1:100];
<syntaxhighlight lang="octave">arr = [1:100];
evennums = arr( mod(arr, 2) == 0 );
evennums = arr( mod(arr, 2) == 0 );
disp(evennums);</lang>
disp(evennums);</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>100 seq filter(#isEven)</lang>
<syntaxhighlight lang="oforth">100 seq filter(#isEven)</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(filter even? '(1 2 3 4 5 6 7 8 9 10))
(filter even? '(1 2 3 4 5 6 7 8 9 10))
</syntaxhighlight>
</lang>
=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang oorexx> Call random ,,1234567
<syntaxhighlight lang="oorexx"> Call random ,,1234567
a=.array~new
a=.array~new
b=.array~new
b=.array~new
Line 2,438: Line 2,938:
Say 'Filtered values (destructive filtering):' a~makestring(line,' ')
Say 'Filtered values (destructive filtering):' a~makestring(line,' ')
Exit
Exit
filter: Return arg(1)//2=0</lang>
filter: Return arg(1)//2=0</syntaxhighlight>
{{out}}
{{out}}
<pre>Unfiltered values: 1412 2244 6778 4002 439 3335 5877 8273 7882 1469
<pre>Unfiltered values: 1412 2244 6778 4002 439 3335 5877 8273 7882 1469
Line 2,446: Line 2,946:
=={{header|Oz}}==
=={{header|Oz}}==
It is easier to do it with a list:
It is easier to do it with a list:
<lang oz>declare
<syntaxhighlight lang="oz">declare
Lst = [1 2 3 4 5]
Lst = [1 2 3 4 5]
LstEven = {Filter Lst IsEven}</lang>
LstEven = {Filter Lst IsEven}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
{{PARI/GP select}}
{{PARI/GP select}}
<lang parigp>iseven(n)=n%2==0
<syntaxhighlight lang="parigp">iseven(n)=n%2==0
select(iseven, [2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17])</lang>
select(iseven, [2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17])</syntaxhighlight>


Or in anonymous form
Or in anonymous form
<lang parigp>select(n -> n%2==0, [2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17])</lang>
<syntaxhighlight lang="parigp">select(n -> n%2==0, [2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17])</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 2,464: Line 2,964:
{{works with|Delphi}}<br>
{{works with|Delphi}}<br>
{{works with|Turbo Pascal}}
{{works with|Turbo Pascal}}
<lang pascal>const
<syntaxhighlight lang="pascal">const


numbers:array[0..9] of integer = (0,1,2,3,4,5,6,7,8,9);
numbers:array[0..9] of integer = (0,1,2,3,4,5,6,7,8,9);
Line 2,472: Line 2,972:
writeln( 'The number ',numbers[x],' is odd.');
writeln( 'The number ',numbers[x],' is odd.');
else
else
writeln( 'The number ',numbers[x],' is even.');</lang>
writeln( 'The number ',numbers[x],' is even.');</syntaxhighlight>


The odd() function is a standard library function of pascal as is the function even().
The odd() function is a standard library function of pascal as is the function even().
Line 2,478: Line 2,978:
=={{header|Peloton}}==
=={{header|Peloton}}==
Fixed length English dialect
Fixed length English dialect
<lang sgml><@ LETCNWLSTLIT>numbers|1 2 3 4 5 6 7 8 9 10 11 12</@>
<syntaxhighlight lang="sgml"><@ LETCNWLSTLIT>numbers|1 2 3 4 5 6 7 8 9 10 11 12</@>
<@ DEFLST>evens</@>
<@ DEFLST>evens</@>
<@ ENULSTLIT>numbers|
<@ ENULSTLIT>numbers|
Line 2,485: Line 2,985:
<@ LETLSTELTLST>evens|...</@>
<@ LETLSTELTLST>evens|...</@>
</@>
</@>
</@></lang>
</@></syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>my @a = (1, 2, 3, 4, 5, 6);
<syntaxhighlight lang="perl">my @a = (1, 2, 3, 4, 5, 6);
my @even = grep { $_%2 == 0 } @a;</lang>
my @even = grep { $_%2 == 0 } @a;</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
===basic task===
===basic task===
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="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;">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;">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: #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;">)
<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;">)
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,508: Line 3,008:
The following discusses possible destructive/in situ behaviours (in excruciatingly painstaking detail). Phix is reference counted so the distinction between destructive and
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.
non-destructive is somewhat subtle. The following code (builtin filter routine) acts both ways.
<!--<lang Phix>-->
<!--<syntaxhighlight lang="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;">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;">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,522: Line 3,022:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<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;">)
<span style="color: #000000;">main<span style="color: #0000FF;">(<span style="color: #0000FF;">)
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,530: Line 3,030:
</pre>
</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
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
<!--<lang Phix>-->
<!--<syntaxhighlight lang="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: #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>
<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,540: Line 3,040:
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function
<span style="color: #008080;">end</span> <span style="color: #008080;">function
<!--</lang>-->
<!--</syntaxhighlight>-->
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:
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:
<!--<lang Phix>-->
<!--<syntaxhighlight lang="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: #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>
<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,564: Line 3,064:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<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;">)
<span style="color: #000000;">main<span style="color: #0000FF;">(<span style="color: #0000FF;">)
<!--</lang>-->
<!--</syntaxhighlight>-->
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.
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.
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,573: Line 3,073:
=={{header|PHL}}==
=={{header|PHL}}==


<lang phl>module var;
<syntaxhighlight lang="phl">module var;


extern printf;
extern printf;
Line 2,583: Line 3,083:


return 0;
return 0;
]</lang>
]</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
Using a standard loop
Using a standard loop
<lang php>$arr = range(1,5);
<syntaxhighlight lang="php">$arr = range(1,5);
$evens = array();
$evens = array();
foreach ($arr as $val){
foreach ($arr as $val){
if ($val % 2 == 0) $evens[] = $val);
if ($val % 2 == 0) $evens[] = $val);
}
}
print_r($evens);</lang>
print_r($evens);</syntaxhighlight>


Using a filter function
Using a filter function
<lang php>function is_even($var) { return(!($var & 1)); }
<syntaxhighlight lang="php">function is_even($var) { return(!($var & 1)); }
$arr = range(1,5);
$arr = range(1,5);
$evens = array_filter($arr, "is_even");
$evens = array_filter($arr, "is_even");
print_r($evens);</lang>
print_r($evens);</syntaxhighlight>

=={{header|Picat}}==
List comprehension is probably the best way of filtering:
<syntaxhighlight lang="picat">[I : I in 1..20, I mod 2 == 0]</syntaxhighlight>

A more general version of filtering is to use <code>call/1</code> with a defined predicate (here <code>p/1</code>):
<syntaxhighlight lang="picat">go =>
L = 1..20,
A = filter(L,p).

p(N) => N mod 2 == 0.

filter(A,F) = [N : N in A, call(F,N)].</syntaxhighlight>

This general version might be slower since using <code>call/1</code> has some overhead.



=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(filter '((N) (not (bit? 1 N)))
<syntaxhighlight lang="picolisp">(filter '((N) (not (bit? 1 N)))
(1 2 3 4 5 6 7 8 9) )</lang>
(1 2 3 4 5 6 7 8 9) )</syntaxhighlight>
{{out}}
{{out}}
<pre>-> (2 4 6 8)</pre>
<pre>-> (2 4 6 8)</pre>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>(subscriptrange):
<syntaxhighlight lang="pli">(subscriptrange):
filter_values: procedure options (main); /* 15 November 2013 */
filter_values: procedure options (main); /* 15 November 2013 */
declare a(20) fixed, b(*) fixed controlled;
declare a(20) fixed, b(*) fixed controlled;
Line 2,634: Line 3,150:
end filter;
end filter;


end filter_values;</lang>
end filter_values;</syntaxhighlight>
Results:
Results:
<pre>
<pre>
Line 2,647: Line 3,163:
Most natural solution in Pop11 would probably use list. Below we accumulate filtered elements on the stack and then allocate array for the result:
Most natural solution in Pop11 would probably use list. Below we accumulate filtered elements on the stack and then allocate array for the result:


<lang pop11>;;; Generic filtering procedure which selects from ar elements
<syntaxhighlight lang="pop11">;;; Generic filtering procedure which selects from ar elements
;;; satisfying pred
;;; satisfying pred
define filter_array(ar, pred);
define filter_array(ar, pred);
Line 2,661: Line 3,177:
;;; Use it
;;; Use it
filter_array({1, 2, 3, 4, 5},
filter_array({1, 2, 3, 4, 5},
procedure(x); not(testbit(x, 0)); endprocedure) =></lang>
procedure(x); not(testbit(x, 0)); endprocedure) =></syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
{{libheader|initlib}}
{{libheader|initlib}}
<lang postscript>
<syntaxhighlight lang="postscript">
[1 2 3 4 5 6 7 8 9 10] {2 mod 0 eq} find
[1 2 3 4 5 6 7 8 9 10] {2 mod 0 eq} find
</syntaxhighlight>
</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>$array = -15..37
<syntaxhighlight lang="powershell">$array = -15..37
$array | Where-Object { $_ % 2 -eq 0 }</lang>
$array | Where-Object { $_ % 2 -eq 0 }</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
===findall===
===findall===
<lang prolog>evens(D, Es) :- findall(E, (member(E, D), E mod 2 =:= 0), Es).</lang>
<syntaxhighlight lang="prolog">evens(D, Es) :- findall(E, (member(E, D), E mod 2 =:= 0), Es).</syntaxhighlight>


Usage:
Usage:


<lang prolog>?- evens([1,2,3,4,5,6,7,8,9,10],E).
<syntaxhighlight lang="prolog">?- evens([1,2,3,4,5,6,7,8,9,10],E).
E = [2, 4, 6, 8, 10]</lang>
E = [2, 4, 6, 8, 10]</syntaxhighlight>


===Anonymous functions===
===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
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
<lang Prolog>?- use_module(library(lambda)).
<syntaxhighlight lang="prolog">?- use_module(library(lambda)).
true.
true.


?- include((\X^(X mod 2 =:= 0)), [1,2,3,4,5,6,7,8,9], L).
?- include((\X^(X mod 2 =:= 0)), [1,2,3,4,5,6,7,8,9], L).
L = [2,4,6,8].</lang>
L = [2,4,6,8].</syntaxhighlight>


===filter and anonymous functions===
===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
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
<lang prolog>:- use_module(lambda).
<syntaxhighlight lang="prolog">:- use_module(lambda).


%% filter(Pred, LstIn, LstOut)
%% filter(Pred, LstIn, LstOut)
Line 2,701: Line 3,217:
filter(Pred, T, L1),
filter(Pred, T, L1),
( call(Pred,H) -> L = [H|L1]; L = L1).
( call(Pred,H) -> L = [H|L1]; L = L1).
</syntaxhighlight>
</lang>
Usage :
Usage :
<lang prolog> ?- filter(\X^(X mod 2 =:= 0), [1,2,3,4,5,6,7,8,9], L).
<syntaxhighlight lang="prolog"> ?- filter(\X^(X mod 2 =:= 0), [1,2,3,4,5,6,7,8,9], L).
L = [2,4,6,8] .
L = [2,4,6,8] .
</syntaxhighlight>
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Dim Tal.i(9)
<syntaxhighlight lang="purebasic">Dim Tal.i(9)
Dim Evens.i(0)
Dim Evens.i(0)


Line 2,734: Line 3,250:
For i=0 To ArraySize(Evens())
For i=0 To ArraySize(Evens())
Print(Str(Evens(i))+" ")
Print(Str(Evens(i))+" ")
Next</lang>
Next</syntaxhighlight>


{{out}}
{{out}}
Line 2,746: Line 3,262:
{{works with|Python|2.4}}
{{works with|Python|2.4}}


<lang python>values = range(10)
<syntaxhighlight lang="python">values = range(10)
evens = [x for x in values if not x & 1]
evens = [x for x in values if not x & 1]
ievens = (x for x in values if not x & 1) # lazy
ievens = (x for x in values if not x & 1) # lazy
# alternately but less idiomatic:
# alternately but less idiomatic:
evens = filter(lambda x: not x & 1, values)</lang>
evens = filter(lambda x: not x & 1, values)</syntaxhighlight>


Alternative using the slice syntax with its optional "stride" expression:
Alternative using the slice syntax with its optional "stride" expression:


<lang python>values = range(10)
<syntaxhighlight lang="python">values = range(10)
evens = values[::2]</lang>
evens = values[::2]</syntaxhighlight>


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.
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,763: Line 3,279:
One can also assign to a slice (of a list or other mutable indexed object. Thus the following:
One can also assign to a slice (of a list or other mutable indexed object. Thus the following:


<lang python>values = range(10)
<syntaxhighlight lang="python">values = range(10)
values[::2] = [11,13,15,17,19]
values[::2] = [11,13,15,17,19]
print values
print values
11, 1, 13, 3, 15, 5, 17, 7, 19, 9</lang>
11, 1, 13, 3, 15, 5, 17, 7, 19, 9</syntaxhighlight>




Or in functional terms, by descending generality and increasing brevity:
Or in functional terms, by descending generality and increasing brevity:
{{works with|Python|3}}
{{works with|Python|3}}
<lang python>'''Functional filtering - by descending generality and increasing brevity'''
<syntaxhighlight lang="python">'''Functional filtering - by descending generality and increasing brevity'''


from functools import (reduce)
from functools import (reduce)
Line 2,865: Line 3,381:


if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>By descending generality and increasing brevity:
<pre>By descending generality and increasing brevity:
Line 2,876: Line 3,392:
=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ [] ]'[ rot
<syntaxhighlight lang="quackery"> [ [] ]'[ rot
witheach
witheach
[ tuck over do iff
[ tuck over do iff
Line 2,887: Line 3,403:
[] 10 times [ 10 random join ]
[] 10 times [ 10 random join ]
say "Ten arbitrary digits: " dup echo cr
say "Ten arbitrary digits: " dup echo cr
say "Only the even digits: " only even echo cr</lang>
say "Only the even digits: " only even echo cr</syntaxhighlight>


{{out}}
{{out}}
Line 2,896: Line 3,412:
===Destructively===
===Destructively===


<lang Quackery> [ ]'[ over size times
<syntaxhighlight lang="quackery"> [ ]'[ over size times
[ over i peek
[ over i peek
over do if
over do if
Line 2,906: Line 3,422:
[] 10 times [ i join ] shuffle
[] 10 times [ i join ] shuffle
say "Ten shuffled digits: " dup echo cr
say "Ten shuffled digits: " dup echo cr
say "Less the odd digits: " without odd echo cr</lang>
say "Less the odd digits: " without odd echo cr</syntaxhighlight>


{{out}}
{{out}}
Line 2,914: Line 3,430:


=={{header|Q}}==
=={{header|Q}}==
<lang q>x where 0=x mod 2</lang>
<syntaxhighlight lang="q">x where 0=x mod 2</syntaxhighlight>

=={{header|QBASIC}}==
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.x}}
{{works with|Visual Basic for DOS|1.0}}
{{works with|PDS|7.x}}

===Using two arrays===
This version uses two arrays.

<syntaxhighlight lang="qbasic">
' OPTION EXPLICIT

' Filter
' This program selects certain elements from an array into a new array in a generic way

' Var
' $DYNAMIC

TYPE regSub
aNum AS INTEGER
END TYPE
CONST Even = 2
CONST Uneven = 1
CONST cFile = "DUMMY$$$.$$$"
CONST False = 0, True = NOT False

DIM t AS INTEGER
DIM t2 AS INTEGER
DIM f AS INTEGER
DIM i AS INTEGER
DIM iFlag AS INTEGER
DIM iGetWhat AS INTEGER
DIM iArray%(1 TO 1)
DIM iArray2%(1 TO 1)
DIM rSub AS regSub

' Initialize vars
iFlag = False
f = FREEFILE
iGetWhat = Even
RANDOMIZE TIMER
t = INT(RND * 300) + 1
REDIM iArray%(1 TO t)

' Main program cycle
OPEN cFile FOR OUTPUT AS #f
CLOSE

OPEN cFile FOR RANDOM AS #f LEN = LEN(rSub)

CLS
PRINT "Select items in an array into a new array in a generic way."
PRINT "Base array:"
FOR i = 1 TO t
iArray%(i) = INT(RND * 2000) + 1
PRINT iArray%(i);
IF (iArray%(i) MOD 2) = 0 AND iGetWhat = Even THEN
iFlag = True
ELSEIF (iArray%(i) MOD 2) <> 0 AND iGetWhat = Uneven THEN
iFlag = True
END IF

IF iFlag THEN
rSub.aNum = iArray%(i)
PUT #f, , rSub
iFlag = False
END IF
NEXT i

' Redims the array
t2 = LOF(f) / LEN(rSub)
REDIM iArray2%(1 TO t2)

FOR i = 1 TO t2
GET #f, i, rSub
iArray2%(i) = rSub.aNum
NEXT i

CLOSE #f
KILL cFile

PRINT

' Shows the result
IF t2 > 0 THEN
PRINT "Selected items from the array (total:"; t2; "of"; t; "):"
FOR i = 1 TO t2
PRINT iArray2%(i);
NEXT i
END IF

PRINT
PRINT "End of program."
END</syntaxhighlight>
{{out}}
The output can change as the size of the base array and its values varies on each run.
<pre>
Select items in an array into a new array in a generic way.
Base array:
1426 770 1686 1472 385 1212 909 656 776 707 918 1646 1258 1406 887 42
Selected items from the array (total: 12 of 16 ):
1426 770 1686 1472 1212 656 776 918 1646 1258 1406 42
End of program.
</pre>

===Using one array===
Extra points: This version uses one array.
<syntaxhighlight lang="qbasic">
' OPTION EXPLICIT

' Filter
' This program selects certain elements from an array into a new array in a generic way
' Extra points: Destroys the original values in the array

' Var
' $DYNAMIC

TYPE regSub
aNum AS INTEGER
END TYPE
CONST Even = 2
CONST Uneven = 1
CONST cFile = "DUMMY$$$.$$$"
CONST False = 0, True = NOT False
DIM t AS INTEGER
DIM t2 AS INTEGER
DIM f AS INTEGER
DIM i AS INTEGER
DIM iFlag AS INTEGER
DIM iGetWhat AS INTEGER
DIM iArray%(1 TO 1)
DIM rSub AS regSub

' Initialize vars
iFlag = False
t = INT(RND * 300) + 1
f = FREEFILE
iGetWhat = Even
REDIM iArray%(1 TO t)

' Main program cycle
OPEN cFile FOR OUTPUT AS #f
CLOSE

OPEN cFile FOR RANDOM AS #f LEN = LEN(rSub)

CLS
RANDOMIZE TIMER
PRINT "Select items in an array into a new array in a generic way."
PRINT "Base array:"
FOR i = 1 TO t
iArray%(i) = INT(RND * 2000) + 1
PRINT iArray%(i);
IF (iArray%(i) MOD 2) = 0 AND iGetWhat = Even THEN
iFlag = True
ELSEIF (iArray%(i) MOD 2) <> 0 AND iGetWhat = Uneven THEN
iFlag = True
END IF

IF iFlag THEN
rSub.aNum = iArray%(i)
PUT #f, , rSub
iFlag = False
END IF
NEXT i

' Redims the array
t = LOF(f) / LEN(rSub)
REDIM iArray%(1 TO t)

FOR i = 1 TO t
GET #f, i, rSub
iArray%(i) = rSub.aNum
NEXT i

CLOSE #f
KILL cFile

PRINT

' Shows the result
t2 = UBOUND(iArray%)
IF t2 > 0 THEN
PRINT "Selected items from the array (total:"; t2; "of"; t; "):"
FOR i = 1 TO t2
PRINT iArray%(i);
NEXT i
END IF

PRINT
PRINT "End of program."
END
</syntaxhighlight>
{{out}}
The output can change as the size of the base array and its values varies on each run.
<pre>
Select items in an array into a new array in a generic way.
Base array:
1426 770 1686 1472 385 1212 909 656 776 707 918 1646 1258 1406 887 42
Selected items from the array (total: 12 of 16 ):
1426 770 1686 1472 1212 656 776 918 1646 1258 1406 42
End of program.
</pre>


=={{header|R}}==
=={{header|R}}==
<lang R>a <- 1:100
<syntaxhighlight lang="r">a <- 1:100
evennums <- a[ a%%2 == 0 ]
evennums <- a[ a%%2 == 0 ]
print(evennums)</lang>
print(evennums)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
The classic way:
The classic way:
<syntaxhighlight lang="racket">
<lang Racket>
-> (filter even? '(0 1 2 3 4 5 6 7 8 9))
-> (filter even? '(0 1 2 3 4 5 6 7 8 9))
'(0 2 4 6 8)
'(0 2 4 6 8)
</syntaxhighlight>
</lang>
getting the list of non-evens too:
getting the list of non-evens too:
<syntaxhighlight lang="racket">
<lang Racket>
-> (partition even? '(0 1 2 3 4 5 6 7 8 9))
-> (partition even? '(0 1 2 3 4 5 6 7 8 9))
'(0 2 4 6 8)
'(0 2 4 6 8)
'(1 3 5 7 9)
'(1 3 5 7 9)
</syntaxhighlight>
</lang>
Finally, using a for loop, similar to list comprehension:
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)
-> (for/list ([x '(0 1 2 3 4 5 6 7 8 9)] #:when (even? x)) x)
'(0 2 4 6 8)
'(0 2 4 6 8)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 2,943: Line 3,663:
{{works with|Rakudo|2018.03}}
{{works with|Rakudo|2018.03}}


<lang perl6>my @a = 1..6;
<syntaxhighlight lang="raku" line>my @a = 1..6;
my @even = grep * %% 2, @a;</lang>
my @even = grep * %% 2, @a;</syntaxhighlight>


Alternatively:
Alternatively:


<lang perl6>my @a = 1..6;
<syntaxhighlight lang="raku" line>my @a = 1..6;
my @even = @a.grep(* %% 2);</lang>
my @even = @a.grep(* %% 2);</syntaxhighlight>


Destructive:
Destructive:


<lang perl6>my @a = 1..6;
<syntaxhighlight lang="raku" line>my @a = 1..6;
@a .= grep(* %% 2);</lang>
@a .= grep(* %% 2);</syntaxhighlight>


=={{header|Raven}}==
=={{header|Raven}}==
<lang raven>[ 0 1 2 3 4 5 6 7 8 9 ] as nums
<syntaxhighlight lang="raven">[ 0 1 2 3 4 5 6 7 8 9 ] as nums
group nums each
group nums each
dup 1 & if drop
dup 1 & if drop
list as evens</lang>
list as evens</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>a: [] repeat i 100 [append a i] ; Build and load array.
<syntaxhighlight lang="rebol">a: [] repeat i 100 [append a i] ; Build and load array.


evens: [] repeat element a [if even? element [append evens element]]
evens: [] repeat element a [if even? element [append evens element]]


print mold evens</lang>
print mold evens</syntaxhighlight>


{{out}}
{{out}}
Line 2,976: Line 3,696:


=={{header|Red}}==
=={{header|Red}}==
<lang Red>Red []
<syntaxhighlight lang="red">Red []
orig: [] repeat i 10 [append orig i]
orig: [] repeat i 10 [append orig i]
?? orig
?? orig
Line 2,985: Line 3,705:
remove-each ele orig [odd? ele] ;; destructive
remove-each ele orig [odd? ele] ;; destructive
?? orig
?? orig
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>orig: [1 2 3 4 5 6 7 8 9 10]
<pre>orig: [1 2 3 4 5 6 7 8 9 10]
Line 2,996: Line 3,716:
===using two arrays===
===using two arrays===
This example uses two arrays. &nbsp; The &nbsp; '''random''' &nbsp; BIF is used to generate the numbers.
This example uses two arrays. &nbsp; The &nbsp; '''random''' &nbsp; BIF is used to generate the numbers.
<lang rexx>/*REXX program selects all even numbers from an array and puts them ──► a new array.*/
<syntaxhighlight lang="rexx">/*REXX program selects all even numbers from an array and puts them */
parse arg N seed . /*obtain optional arguments from the CL*/
/* into a new array. */
if N=='' | N=="," then N= 50 /*Not specified? Then use the default.*/
Parse Arg n seed . /* obtain optional arguments from CL*/
if datatype(seed,'W') then call random ,,seed /*use the RANDOM seed for repeatability*/
If n==''|n=="," Then n=50 /* Not specified? use the default */
If datatype(seed,'W') Then
old.= /*the OLD array, all are null so far. */
new.= /* " NEW " " " " " " */
Call random,,seed /* use RANDOM seed for repeatability*/
do i=1 for N /*generate N random numbers ──► OLD */
Do i=1 For n /* generate N random numbers */
old.i= random(1, 99999) /*generate random number 1 ──► 99999*/
old.i=random(1,99999) /* generate random number */
End
end /*i*/
#= 0 /*number of elements in NEW (so far).*/
m=0 /* number of elements in NEW */
do j=1 for N /*process the elements of the OLD array*/
Do j=1 To n /* process the elements of the OLD */
if old.j//2 \== 0 then iterate /*if element isn't even, then skip it.*/
If old.j//2==0 Then Do /* if element is even, then */
#= # + 1 /*bump the number of NEW elements. */
m=m+1 /* bump the number of NEW elemens */
new.#= old.j /*assign the number to the NEW array.*/
new.m=old.j /* assign the number to the NEW */
end /*j*/
End
End

do k=1 for # /*display all the NEW numbers. */
Do k=1 For m /* display all the NEW numbers. */
say right('new.'k, 20) "=" right(new.k, 9) /*display a line (an array element). */
Say right('new.'k,20) '=' right(new.k,9)
End </syntaxhighlight>
end /*k*/ /*stick a fork in it, we're all done. */</lang>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> , &nbsp; 12345 </tt>}}
Programming note: &nbsp; the REXX statement
The '''12345''' is the '''random''' BIF &nbsp; ''seed'' &nbsp; so that the random numbers can be repeated when re-running the REXX program.
<lang rexx> if old.j//2 \== 0 then iterate</lang>
could've been replaced with
<lang rexx> if old.j//2 then iterate</lang>
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.

{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> , &nbsp; 1234567 </tt>}}

The '''1234567''' is the '''random''' BIF &nbsp; ''seed'' &nbsp; so that the random numbers can be repeated when re-running the REXX program.
<pre>
<pre>
new.1 = 17520
new.1 = 17520
Line 3,050: Line 3,762:
new.23 = 44360
new.23 = 44360
</pre>
</pre>
===Using a control array===

===using one array with a control array===
This version uses a control array (even.*)
<syntaxhighlight lang="rexx">
This version uses a control array, which isn't fully populated &nbsp; (in REXX terms, a sparse array.)
<lang rexx>/*REXX program finds all even numbers from an array, and marks a control array. */
/*REXX program uses a control array to tell which elements ars even. */
parse arg N seed . /*obtain optional arguments from the CL*/
Parse Arg n seed . /* obtain optional arguments from CL*/
if N=='' | N=="," then N= 50 /*Not specified? Then use the default.*/
If n==''|n=="," Then n=50 /* Not specified? use the default */
if datatype(seed,'W') then call random ,,seed /*use the RANDOM seed for repeatability*/
If datatype(seed,'W') Then
Call random,,seed /* use RANDOM seed for repeatability*/

do i=1 for N /*generate N random numbers ──► OLD */
Do i=1 For n /* generate n random numbers */
@.i= random(1, 99999) /*generate random number 1 ──► 99999*/
x.i=random(1,99999) /* generate random number */
End
end /*i*/
!.= 0 /*number of elements in NEW (so far).*/
even.=0 /* all even bits are off */
do j=1 for N /*process the OLD array elements. */
Do j=1 To n /* process the elements of x.* */
if @.j//2 \==0 then !.j= 1 /*mark the ! array that it's ¬even. */
If x.j//2==0 Then /* if element is even, then */
even.j=1 /* turn on the even bit */
end /*j*/
End

do k=1 for N /*display all the @ even numbers. */
Do k=1 To n /* display all the numbers */
if !.k then iterate /*if it's marked as not even, skip it.*/
If even.k Then /* that are even */
say right('array.'k, 20) "=" right(@.k, 9) /*display a even number, filtered array*/
Say right('x.'k,20) '=' right(x.k,9)
End</syntaxhighlight>
end /*k*/ /*stick a fork in it, we're all done. */</lang>
For the following input: &nbsp; &nbsp; <tt> , 1234567 </tt>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 20 &nbsp; 12345 </tt>}}
<pre>

x.3 = 52754
{{out|output|text=&nbsp; Output is the same as the 1<sup>st</sup> REXX version &nbsp; (using two arrays).}}<br>
x.5 = 94296

x.6 = 2068

x.13 = 71494
x.14 = 71628
x.15 = 47404
x.19 = 92502
x.20 = 24808</pre>
===using one array, destructive===
===using one array, destructive===
This version just uses one array to perform the filtering instead of creating a &nbsp; ''new'' &nbsp; array.
This version just uses one array to perform the filtering instead of creating a &nbsp; ''new'' &nbsp; array.
The result is a sparse array.

This method doesn't need as much memory to hold the sparse array.
This method doesn't need as much memory.
<lang rexx>/*REXX program finds all even numbers from an array, and marks the not even numbers.*/
<syntaxhighlight lang="rexx">/*REXX program sets all elements containing odd numbers to blank */
parse arg N seed . /*obtain optional arguments from the CL*/
Parse Arg n seed . /* obtain optional arguments from CL*/
if N=='' | N=="," then N= 50 /*Not specified? Then use the default.*/
If n==''|n=="," Then n=50 /* Not specified? use the default */
if datatype(seed,'W') then call random ,,seed /*use the RANDOM seed for repeatability*/
If datatype(seed,'W') Then
Call random,,seed /* use RANDOM seed for repeatability*/

do i=1 for N /*generate N random numbers ──► OLD */
Do i=1 For n /* generate N random numbers */
@.i= random(1, 99999) /*generate a random number 1 ──► 99999 */
x.i=random(1,99999) /* generate random number */
End
end /*i*/
Do j=1 To n /* process the elements of x.* */

do j=1 for N /*process the OLD array elements. */
If x.j//2<>0 Then /* if element is not even, then */
if @.j//2 \==0 then @.j= /*mark the @ array that it's not even*/
Drop x.j /* delete it */
End
end /*j*/
Do k=1 To n /* display all the numbers */

do k=1 for N /*display all the @ even numbers. */
If datatype(x.k)='NUM' Then /* that are even */
Say right('x.'k,20) '=' right(x.k,9)
if @.k=='' then iterate /*if it's marked not even, then skip it*/
End</syntaxhighlight>
say right('array.'k, 20) "=" right(@.k, 9) /*display a line (an array element). */
For the following input: &nbsp; &nbsp; <tt> 20 12345 </tt>
end /*k*/ /*stick a fork in it, we're all done. */</lang>
{{out|output|text=&nbsp; is the same as the 2<sup>nd</sup> REXX version.}} <br><br>
For the following input: &nbsp; &nbsp; <tt> , 1234567 </tt>

{{out|output|text=&nbsp; is the same as the 1<sup>st</sup> REXX version &nbsp; (using two arrays).}} <br><br>


=={{header|Ring}}==
=={{header|Ring}}==
<lang>
<syntaxhighlight lang="text">
aList = [1, 2, 3, 4, 5, 6]
aList = [1, 2, 3, 4, 5, 6]
bArray = list(3)
bArray = list(3)
Line 3,114: Line 3,829:
next
next
return bArray
return bArray
</syntaxhighlight>
</lang>

=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
DUP SIZE {} 2 ROT '''FOR''' j OVER j GET + 2 '''STEP'''
≫ ''''FILTR'''' STO
LIST→ → len
≪ {} len 1 '''FOR''' j
'''IF''' j 2 MOD '''THEN''' SWAP DROP '''ELSE''' + '''END'''
-1 '''STEP'''
≫ ≫ ''''FILTD'''' STO
|
'''FILTR''' ''( { a1 a2.. an } -- { a1 a2.. an } { a2 a4... a2k } )''
selective copy
'''FILTD''' ''( { a1 a2.. an } -- { a2 a4... a2k } )''
Destructive version : put the array in the stack...
... and make a new one by picking one out of two items
|}
{{in}}
<pre>
{ 1 2 3 4 5 6 7 8 9 } FILTR
{ 1 2 3 4 5 6 7 8 9 } FILTD
</pre>
{{out}}
<pre>
3: { 1 2 3 4 5 6 7 8 9 }
2: { 2 4 6 8 }
1: { 2 4 6 8 }
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
Enumerable#select is the filter that returns a new Array.
Enumerable#select is the filter that returns a new Array.


<lang ruby># Enumerable#select returns a new array.
<syntaxhighlight lang="ruby"># Enumerable#select returns a new array.
ary = [1, 2, 3, 4, 5, 6]
ary = [1, 2, 3, 4, 5, 6]
even_ary = ary.select {|elem| elem.even?}
even_ary = ary.select {|elem| elem.even?}
Line 3,127: Line 3,883:
range = 1..6
range = 1..6
even_ary = range.select {|elem| elem.even?}
even_ary = range.select {|elem| elem.even?}
p even_ary # => [2, 4, 6]</lang>
p even_ary # => [2, 4, 6]</syntaxhighlight>


=== Destructive ===
=== Destructive ===
Array#select! is the destructive version which modifies the original Array.
Array#select! is the destructive version which modifies the original Array.


<lang ruby>ary = [1, 2, 3, 4, 5, 6]
<syntaxhighlight lang="ruby">ary = [1, 2, 3, 4, 5, 6]
ary.select! {|elem| elem.even?}
ary.select! {|elem| elem.even?}
p ary # => [2, 4, 6]</lang>
p ary # => [2, 4, 6]</syntaxhighlight>


Shorthand:
Shorthand:


<lang ruby>ary = [1, 2, 3, 4, 5, 6]
<syntaxhighlight lang="ruby">ary = [1, 2, 3, 4, 5, 6]
ary.select!(&:even?)
ary.select!(&:even?)
p ary # => [2, 4, 6]</lang>
p ary # => [2, 4, 6]</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>dim a1(100)
<syntaxhighlight lang="runbasic">dim a1(100)
count = 100
count = 100
for i = 1 to 100
for i = 1 to 100
Line 3,161: Line 3,917:
for i = 1 to count
for i = 1 to count
print a2(i)
print a2(i)
next</lang>
next</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>fn main() {
<syntaxhighlight lang="rust">fn main() {
println!("new vec filtered: ");
println!("new vec filtered: ");
let nums: Vec<i32> = (1..20).collect();
let nums: Vec<i32> = (1..20).collect();
Line 3,175: Line 3,931:
nums.retain(|x| x % 2 == 0);
nums.retain(|x| x % 2 == 0);
println!("{:?}", nums);
println!("{:?}", nums);
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,188: Line 3,944:
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.
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.


<lang Salmon>iterate(x; comprehend(y; [1...10]; y % 2 == 0) (y))
<syntaxhighlight lang="salmon">iterate(x; comprehend(y; [1...10]; y % 2 == 0) (y))
x!;</lang>
x!;</syntaxhighlight>


Here's a version that walks an array destructively removing the non-even elements:
Here's a version that walks an array destructively removing the non-even elements:


<lang Salmon>variable my_array := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
<syntaxhighlight lang="salmon">variable my_array := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
variable write_position := 0;
variable write_position := 0;
iterate (read_position; [0...9])
iterate (read_position; [0...9])
Line 3,207: Line 3,963:
my_array := my_array[0...write_position - 1];
my_array := my_array[0...write_position - 1];
iterate(x; my_array)
iterate(x; my_array)
x!;</lang>
x!;</syntaxhighlight>


=={{header|Sather}}==
=={{header|Sather}}==
<lang sather>class MARRAY{T} < $ARR{T} is
<syntaxhighlight lang="sather">class MARRAY{T} < $ARR{T} is
include ARRAY{T};
include ARRAY{T};


Line 3,232: Line 3,988:
#OUT + "\n";
#OUT + "\n";
end;
end;
end;</lang>
end;</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>(1 to 100).filter(_ % 2 == 0)</lang>
<syntaxhighlight lang="scala">(1 to 100).filter(_ % 2 == 0)</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
Filter function definition:
Filter function definition:
<lang scheme>
<syntaxhighlight lang="scheme">
(define filter
(define filter
(lambda (fn lst)
(lambda (fn lst)
Line 3,250: Line 4,006:
(iter rest (cons item result))
(iter rest (cons item result))
(iter rest result)))))))
(iter rest result)))))))
</syntaxhighlight>
</lang>
Usage in the interactive prompt:
Usage in the interactive prompt:
<lang scheme>> (filter even? '(1 2 3 4 5 6 7 8 9 10))
<syntaxhighlight lang="scheme">> (filter even? '(1 2 3 4 5 6 7 8 9 10))
(2 4 6 8 10)</lang>
(2 4 6 8 10)</syntaxhighlight>
Or as a function:
Or as a function:
<lang scheme>(define (select-even lst)
<syntaxhighlight lang="scheme">(define (select-even lst)
(filter even? lst))
(filter even? lst))


(select-even '(1 2 3 4 5 6 7 8 9 10))</lang>
(select-even '(1 2 3 4 5 6 7 8 9 10))</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>var array integer: arr is [] (1, 2, 3, 4, 5);
<syntaxhighlight lang="seed7">var array integer: arr is [] (1, 2, 3, 4, 5);
var array integer: evens is 0 times 0;
var array integer: evens is 0 times 0;
var integer: number is 0;
var integer: number is 0;
Line 3,269: Line 4,025:
evens &:= [] (number);
evens &:= [] (number);
end if;
end if;
end for;</lang>
end for;</syntaxhighlight>


=={{header|SequenceL}}==
=={{header|SequenceL}}==
Filters are primarily written in SequenceL using partial Indexed Functions.<br>
Filters are primarily written in SequenceL using partial Indexed Functions.<br>
<lang sequencel>evens(x(1))[i] := x[i] when x[i] mod 2 = 0;</lang>
<syntaxhighlight lang="sequencel">evens(x(1))[i] := x[i] when x[i] mod 2 = 0;</syntaxhighlight>


{{out}}
{{out}}
Line 3,282: Line 4,038:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var arr = [1,2,3,4,5];
<syntaxhighlight lang="ruby">var arr = [1,2,3,4,5]


# Creates a new array
# Creates a new array
var new = arr.grep {|i| i %% 2};
var new = arr.grep {|i| i.is_even }
say new.dump; # => [2, 4]
say new # => [2, 4]


# Destructive (at variable level)
# Destructive (at variable level)
arr.grep! {|i| i %% 2};
arr.grep! {|i| i.is_even }
say arr.dump; # => [2, 4]</lang>
say arr # => [2, 4]</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>#(1 2 3 4 5) select: [| :number | number isEven].</lang>
<syntaxhighlight lang="slate">#(1 2 3 4 5) select: [| :number | number isEven].</syntaxhighlight>

=={{header|Slope}}==
<syntaxhighlight lang="slope">
(define number-list (range 20))

(define even-number-list
(filter
(lambda (num) (equal? (% num 2) 0))
number-list))

(display number-list "\n" even-number-list "\n")
</syntaxhighlight>

'''Output:'''
<syntaxhighlight lang="text">
(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19)
(0 2 4 6 8 10 12 14 16 18)
</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Creates a new array:
Creates a new array:
<lang smalltalk>#(1 2 3 4 5) select: [:number | number even]</lang>
<syntaxhighlight lang="smalltalk">#(1 2 3 4 5) select: [:number | number even]</syntaxhighlight>
or for short:
or for short:
<lang smalltalk>#(1 2 3 4 5) select:#even</lang>
<syntaxhighlight lang="smalltalk">#(1 2 3 4 5) select:#even</syntaxhighlight>
Destructive modification is not possible for literal constants (these are immutable);
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.
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,307: Line 4,081:


{{works with|MS SQL}}
{{works with|MS SQL}}
<lang sql>--Create the original array (table #nos) with numbers from 1 to 10
<syntaxhighlight lang="sql">--Create the original array (table #nos) with numbers from 1 to 10
create table #nos (v int)
create table #nos (v int)
declare @n int set @n=1
declare @n int set @n=1
Line 3,320: Line 4,094:
-- Clean up so you can edit and repeat:
-- Clean up so you can edit and repeat:
drop table #nos
drop table #nos
drop table #evens</lang>
drop table #evens</syntaxhighlight>


'{{works with|MySQL}}
'{{works with|MySQL}}
<lang sql>create temporary table nos (v int);
<syntaxhighlight lang="sql">create temporary table nos (v int);
insert into nos values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
insert into nos values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
create temporary table evens (v int);
create temporary table evens (v int);
Line 3,329: Line 4,103:
select * from evens order by v; /*2,4,6,8,10*/
select * from evens order by v; /*2,4,6,8,10*/
drop table nos;
drop table nos;
drop table evens;</lang>
drop table evens;</syntaxhighlight>


Or to be shorter, you could create the table evens directly from the query result :
Or to be shorter, you could create the table evens directly from the query result :
<lang sql>create temporary table evens select * from nos where v%2=0;</lang>
<syntaxhighlight lang="sql">create temporary table evens select * from nos where v%2=0;</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
<lang stata>mata
<syntaxhighlight lang="stata">mata
a=2,9,4,7,5,3,6,1,8
a=2,9,4,7,5,3,6,1,8


Line 3,343: Line 4,117:
// Select the indices of even elements of a
// Select the indices of even elements of a
selectindex(mod(a,2):==0)
selectindex(mod(a,2):==0)
end</lang>
end</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>let numbers = [1,2,3,4,5,6]
<syntaxhighlight lang="swift">let numbers = [1,2,3,4,5,6]
let even_numbers = numbers.filter { $0 % 2 == 0 }
let even_numbers = numbers.filter { $0 % 2 == 0 }
println(even_numbers)</lang>
println(even_numbers)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,355: Line 4,129:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>set l {56 21 71 27 39 62 87 76 82 94 45 83 65 45 28 90 52 44 1 89}
<syntaxhighlight 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}]</lang>
puts [lmap x $l {if {$x % 2} continue; set x}]</syntaxhighlight>
{{out}}
{{out}}
<pre>56 62 76 82 94 28 90 52 44</pre>
<pre>56 62 76 82 94 28 90 52 44</pre>
<br>
<br>
Inplace way, quite the inefficient contraption compared to mapping:
Inplace way, quite the inefficient contraption compared to mapping:
<lang tcl>proc lreplaceip {_list args} {
<syntaxhighlight lang="tcl">proc lreplaceip {_list args} {
upvar 1 $_list list
upvar 1 $_list list
set list [lreplace $list[set list {}] {*}$args]
set list [lreplace $list[set list {}] {*}$args]
Line 3,377: Line 4,151:
}
}


puts $l</lang>
puts $l</syntaxhighlight>
{{out}}
{{out}}
<pre>56 62 76 82 94 28 90 52 44</pre>
<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>
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:
Proof by timing removal of the end element of lists of different lengths:
<lang tcl>proc lreplaceip {_list args} {
<syntaxhighlight lang="tcl">proc lreplaceip {_list args} {
upvar 1 $_list list
upvar 1 $_list list
set list [lreplace $list[set list {}] {*}$args]
set list [lreplace $list[set list {}] {*}$args]
Line 3,401: Line 4,175:
puts " lreplace: [time {set l [lreplace $l end end]}]"
puts " lreplace: [time {set l [lreplace $l end end]}]"
puts " lreplaceip: [time {lreplaceip l end end}]"
puts " lreplaceip: [time {lreplaceip l end end}]"
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>1e5
<pre>1e5
Line 3,414: Line 4,188:


=={{header|Toka}}==
=={{header|Toka}}==
<lang toka>10 cells is-array table
<syntaxhighlight lang="toka">10 cells is-array table
10 cells is-array even
10 cells is-array even
{
{
Line 3,426: Line 4,200:
} is copy-even
} is copy-even
10 0 [ i i table array.put ] countedLoop
10 0 [ i i table array.put ] countedLoop
table 10 copy-even</lang>
table 10 copy-even</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
arr="1'4'9'16'25'36'49'64'81'100",even=""
arr="1'4'9'16'25'36'49'64'81'100",even=""
Line 3,437: Line 4,211:
ENDLOOP
ENDLOOP
PRINT even
PRINT even
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,446: Line 4,220:
{{works with|Bash}}
{{works with|Bash}}


<lang bash>a=(1 2 3 4 5)
<syntaxhighlight lang="bash">a=(1 2 3 4 5)
unset e[@]
unset e[@]
for ((i=0;i<${#a[@]};i++)); do
for ((i=0;i<${#a[@]};i++)); do
[ $((a[$i]%2)) -eq 0 ] && e[$i]="${a[$i]}"
[ $((a[$i]%2)) -eq 0 ] && e[$i]="${a[$i]}"
done</lang>
done</syntaxhighlight>


Or, using '''grep''':
Or, using '''grep''':


<lang bash>a=(1 2 3 4 5)
<syntaxhighlight lang="bash">a=(1 2 3 4 5)
read -a e -d\n < <(printf '%s\n' "${a[@]}" | grep '[02468]$')</lang>
read -a e -d\n < <(printf '%s\n' "${a[@]}" | grep '[02468]$')</syntaxhighlight>


Either way, to display the results:
Either way, to display the results:


<lang bash>echo "${a[@]}"
<syntaxhighlight lang="bash">echo "${a[@]}"
echo "${e[@]}"</lang>
echo "${e[@]}"</syntaxhighlight>


{{out}}
{{out}}
Line 3,467: Line 4,241:


=={{header|UnixPipes}}==
=={{header|UnixPipes}}==
<lang bash>yes \ | cat -n | while read a; do ; expr $a % 2 >/dev/null && echo $a ; done</lang>
<syntaxhighlight lang="bash">yes \ | cat -n | while read a; do ; expr $a % 2 >/dev/null && echo $a ; done</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
Line 3,481: Line 4,255:
predicate <code>p</code> is to write <code>p*~</code>, as shown below.
predicate <code>p</code> is to write <code>p*~</code>, as shown below.


<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import nat
#import nat


Line 3,488: Line 4,262:
#cast %nL
#cast %nL


y = (not remainder\2)*~ x</lang>
y = (not remainder\2)*~ x</syntaxhighlight>


{{out}}
{{out}}
Line 3,500: Line 4,274:
of other ways to do it.
of other ways to do it.
Selecting according to a binary predicate can be done like this.
Selecting according to a binary predicate can be done like this.
<lang Ursala>z = (not remainder)~| (36,<1,2,3,4,5,6,7,8,9,10,11,12>)</lang>
<syntaxhighlight lang="ursala">z = (not remainder)~| (36,<1,2,3,4,5,6,7,8,9,10,11,12>)</syntaxhighlight>
The value of <code>z</code> will be the divisors of 36 appearing in the list.
The value of <code>z</code> will be the divisors of 36 appearing in the list.
<pre>
<pre>
Line 3,517: Line 4,291:
modified by appending an <code>F</code>, it becomes a selection filter.
modified by appending an <code>F</code>, it becomes a selection filter.
For example
For example
<lang Ursala>shortcut = ~&ihBF x</lang>
<syntaxhighlight lang="ursala">shortcut = ~&ihBF x</syntaxhighlight>
using the <code>x</code> defined above will evaluate to
using the <code>x</code> defined above will evaluate to
<pre>
<pre>
Line 3,525: Line 4,299:


=={{header|V}}==
=={{header|V}}==
<lang v>[even? dup 2 / >int 2 * - zero?].
<syntaxhighlight lang="v">[even? dup 2 / >int 2 * - zero?].


[1 2 3 4 5 6 7 8 9] [even?] filter
[1 2 3 4 5 6 7 8 9] [even?] filter
=[2 4 6 8]</lang>
=[2 4 6 8]</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
Option Explicit


Line 3,578: Line 4,352:
Private Function IsEven(Number As Long) As Boolean
Private Function IsEven(Number As Long) As Boolean
IsEven = (CLng(Right(CStr(Number), 1)) And 1) = 0
IsEven = (CLng(Right(CStr(Number), 1)) And 1) = 0
End Function</lang>
End Function</syntaxhighlight>


{{Out}}
{{Out}}
Line 3,586: Line 4,360:


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
test_arr_1 = Array(1,2,3,4,5,6,7,8,9,10)
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)
test_arr_2 = Array(1,2,3,4,5,6,7,8,9,10)
Line 3,633: Line 4,407:
ReDim Preserve arr(UBound(arr)-count)
ReDim Preserve arr(UBound(arr)-count)
filter_destruct = Join(arr,",")
filter_destruct = Join(arr,",")
End Function</lang>
End Function</syntaxhighlight>


{{Out}}
{{Out}}
Line 3,648: Line 4,422:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
{{works with|Visual Basic .NET|9.0+}}
<lang vbnet>Module Filter
<syntaxhighlight lang="vbnet">Module Filter


Sub Main()
Sub Main()
Line 3,689: Line 4,463:


End Module
End Module
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,716: Line 4,490:
8
8
10
10
</pre>

=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
fn reduce(mut a []int){
mut last := 0
for e in a {
if e % 2 == 0 {
a[last] = e
last++
}
}
a = a[..last].clone()
}
fn main() {
mut nums := [5, 4, 8, 2, 4, 6, 5, 6, 34, 12, 21]
even := nums.filter(it % 2 == 0)
println('orig: ${nums}')
println('even: ${even}')
reduce(mut nums)
println('dest: ${nums}')
}
</syntaxhighlight>
{{out}}
<pre>
orig: [5, 4, 8, 2, 4, 6, 5, 6, 34, 12, 21]
even: [4, 8, 2, 4, 6, 6, 34, 12]
dest: [4, 8, 2, 4, 6, 6, 34, 12]
</pre>
</pre>


=={{header|WDTE}}==
=={{header|WDTE}}==
<lang WDTE>let a => import 'arrays';
<syntaxhighlight lang="wdte">let a => import 'arrays';
let s => import 'stream';
let s => import 'stream';


Line 3,726: Line 4,528:
-> s.collect
-> s.collect
-- io.writeln io.stdout
-- io.writeln io.stdout
;</lang>
;</syntaxhighlight>


{{out}}
{{out}}
Line 3,734: Line 4,536:


=={{header|Wrapl}}==
=={{header|Wrapl}}==
<lang wrapl>VAR a <- ALL 1:to(10);</lang>
<syntaxhighlight lang="wrapl">VAR a <- ALL 1:to(10);</syntaxhighlight>
<tt>a</tt> will be the list <tt>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</tt>
<tt>a</tt> will be the list <tt>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</tt>
<lang wrapl>VAR e <- ALL a:values \ $ % 2 = 0;</lang>
<syntaxhighlight lang="wrapl">VAR e <- ALL a:values \ $ % 2 = 0;</syntaxhighlight>
<tt>e</tt> will be the list <tt>[2, 4, 6, 8, 10]</tt>
<tt>e</tt> will be the list <tt>[2, 4, 6, 8, 10]</tt>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>var a = [1, 4, 17, 8, -21, 6, -11, -2, 18, 31]
<syntaxhighlight lang="wren">var a = [1, 4, 17, 8, -21, 6, -11, -2, 18, 31]
System.print("The original array is : %(a)")
System.print("The original array is : %(a)")


Line 3,759: Line 4,561:
System.print("\nAfter a destructive filter :-")
System.print("\nAfter a destructive filter :-")
System.print("The even numbers are : %(evens)")
System.print("The even numbers are : %(evens)")
System.print("The original array is now : %(a)")</lang>
System.print("The original array is now : %(a)")</syntaxhighlight>


{{out}}
{{out}}
Line 3,778: Line 4,580:
There is no 'sizeof' operator, unfortunately.
There is no 'sizeof' operator, unfortunately.


<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations


proc Filter(A, B, Option); \Select all even numbers from array A
proc Filter(A, B, Option); \Select all even numbers from array A
Line 3,805: Line 4,607:
[IntOut(0, Array(I)); ChOut(0, ^ )];
[IntOut(0, Array(I)); ChOut(0, ^ )];
CrLf(0);
CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 3,814: Line 4,616:


=={{header|XQuery}}==
=={{header|XQuery}}==
<lang xquery>
<syntaxhighlight lang="xquery">
(: Sequence of numbers from 1 to 10 :)
(: Sequence of numbers from 1 to 10 :)
let $array := (1 to 10)
let $array := (1 to 10)
Line 3,832: Line 4,634:
<long>{$long}</long>
<long>{$long}</long>
</result>
</result>
</syntaxhighlight>
</lang>


{{out}}
{{out}}
<lang xml>
<syntaxhighlight lang="xml">
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<result>
<result>
Line 3,841: Line 4,643:
<long>2 4 6 8 10</long>
<long>2 4 6 8 10</long>
</result>
</result>
</syntaxhighlight>
</lang>


=={{header|XSLT}}==
=={{header|XSLT}}==
<lang xml><xsl:for-each select="nodes[@value mod 2 = 0]">
<syntaxhighlight lang="xml"><xsl:for-each select="nodes[@value mod 2 = 0]">
<xsl:value-of select="@value" />
<xsl:value-of select="@value" />
</xsl:for-each></lang>
</xsl:for-each></syntaxhighlight>


=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
{{untested}}
{{untested}}
<lang z80>TestArray_Metadata:
<syntaxhighlight lang="z80">TestArray_Metadata:
byte 4,4 ;4 rows, 4 columns.
byte 4,4 ;4 rows, 4 columns.
TestArray:
TestArray:
Line 3,886: Line 4,688:
djnz loop_filterEvenValues
djnz loop_filterEvenValues


ret ;return to basic</lang>
ret ;return to basic</syntaxhighlight>


{{out}}
{{out}}
Line 3,895: Line 4,697:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>T(1,4,9,16,25,36,"37",49,64,81,100, True,self)
<syntaxhighlight 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})
.filter(fcn(n){(0).isType(n) and n.isOdd})
//-->L(1,9,25,49,81)</lang>
//-->L(1,9,25,49,81)</syntaxhighlight>


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
<lang zxbasic>10 LET items=100: LET filtered=0
<syntaxhighlight lang="zxbasic">10 LET items=100: LET filtered=0
20 DIM a(items)
20 DIM a(items)
30 FOR i=1 TO items
30 FOR i=1 TO items
Line 3,913: Line 4,715:
120 NEXT i
120 NEXT i
130 DIM a(1): REM To free memory (well, almost all)
130 DIM a(1): REM To free memory (well, almost all)
140 DEF FN m(a,b)=a-INT (a/b)*b</lang>
140 DEF FN m(a,b)=a-INT (a/b)*b</syntaxhighlight>

Latest revision as of 01:41, 14 April 2024

Task
Filter
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Select certain elements from an Array into a new Array in a generic way.


To demonstrate, select all even numbers from an Array.

As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.

11l

V array = Array(1..10)
V even = array.filter(n -> n % 2 == 0)
print(even)
Output:
[2, 4, 6, 8, 10]

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
or android 64 bits with application Termux
/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program filterdes64.s   */

/************************************/
/* Constantes                       */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc" 

/************************************/
/* Initialized data                 */
/************************************/
.data
szMessResult:        .asciz "Start array : "
szMessResultFil:     .asciz "Filter array : "
szMessResultdest:    .asciz "Same array : "
szMessStart:         .asciz "Program 64 bits start.\n"
szCarriageReturn:    .asciz "\n"
szFiller:            .asciz "  "
.align 4
arrayNumber:         .quad  1,2,3,4,5,6,7,8,9,10
.equ LGARRAY,   (. - arrayNumber) / 8
/************************************/
/* UnInitialized data               */
/************************************/
.bss 
.align 4
arrayNumberFil:           .skip 8 * LGARRAY  // result array
sZoneConv:                .skip 24
/************************************/
/*  code section                    */
/************************************/
.text
.global main 
main:
    ldr x0,qAdrszMessStart      // display start message
    bl affichageMess
    ldr x0,qAdrszMessResult     // display message
    bl affichageMess
    ldr x5,qAdrarrayNumber      // start array address
    mov x4,#0                   // index
    
1:
    ldr x0,[x5,x4,lsl #3]       // load a value
    ldr x1,qAdrsZoneConv
    bl conversion10             // décimal conversion
    ldr x0,qAdrsZoneConv
    bl affichageMess            // display value
    ldr x0,qAdrszFiller
    bl affichageMess
    add x4,x4,#1                // increment index
    cmp x4,#LGARRAY             // end array ?
    blt 1b                      // no -> loop
    ldr x0,qAdrszCarriageReturn
    bl affichageMess
    
    ldr x6,qAdrarrayNumberFil   // adrress result array
    mov x4,#0                   // index
    mov x3,#0                   // index result
2:
    ldr x0,[x5,x4,lsl #3]       // load a value
    tst x0,#1                   // odd ?
    bne 3f
    str x0,[x6,x3,lsl #3]       // no -> store in result array
    add x3,x3,#1                // and increment result index
3:
    add x4,x4,#1                // increment array index
    cmp x4,#LGARRAY             // end ?
    blt 2b                      // no -> loop
    
    ldr x0,qAdrszMessResultFil  
    bl affichageMess
    mov x4,#0                   // init index
    
4:                              // display filter result array
    ldr x0,[x6,x4,lsl #3]
    ldr x1,qAdrsZoneConv
    bl conversion10
    ldr x0,qAdrsZoneConv
    bl affichageMess
    ldr x0,qAdrszFiller
    bl affichageMess
    add x4,x4,#1
    cmp x4,x3
    blt 4b
    ldr x0,qAdrszCarriageReturn
    bl affichageMess
    
                                // array destruction
    mov x4,#0                   // index
    mov x3,#0                   // index result
5:
    ldr x0,[x5,x4,lsl #3]       // load a value
    tst x0,#1                   // odd ?
    bne 7f
    cmp x3,x4                   // index =  no store
    beq 6f
    str x0,[x5,x3,lsl #3]       // store in free item on same array
6:
    add x3,x3,#1                // and increment result index
7:
    add x4,x4,#1                // increment array index
    cmp x4,#LGARRAY             // end ?
    blt 5b                      // no -> loop
    
    ldr x0,qAdrszMessResultdest  
    bl affichageMess
    mov x4,#0                   // init index
    
8:                              // display array
    ldr x0,[x5,x4,lsl #3]
    ldr x1,qAdrsZoneConv
    bl conversion10
    ldr x0,qAdrsZoneConv
    bl affichageMess
    ldr x0,qAdrszFiller
    bl affichageMess
    add x4,x4,#1
    cmp x4,x3
    blt 8b
    ldr x0,qAdrszCarriageReturn
    bl affichageMess
      

100:                             // standard end of the program
    mov x0, #0                   // return code
    mov x8, #EXIT                // request to exit program
    svc 0                        // perform the system call
qAdrszCarriageReturn:    .quad  szCarriageReturn
qAdrszMessStart:         .quad  szMessStart
qAdrarrayNumber:         .quad  arrayNumber
qAdrszMessResult:        .quad  szMessResult
qAdrarrayNumberFil:      .quad  arrayNumberFil
qAdrszMessResultFil:     .quad  szMessResultFil
qAdrszMessResultdest:    .quad  szMessResultdest
qAdrsZoneConv:           .quad  sZoneConv
qAdrszFiller:            .quad  szFiller
/***************************************************/
/*      ROUTINES INCLUDE                           */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"
Output:
Program 64 bits start.
Start array : 1  2  3  4  5  6  7  8  9  10
Filter array : 2  4  6  8  10
Same array : 2  4  6  8  10

ACL2

(defun filter-evens (xs)
   (cond ((endp xs) nil)
         ((evenp (first xs))
          (cons (first xs) (filter-evens (rest xs))))
         (t (filter-evens (rest xs)))))

Action!

DEFINE PTR="CARD"

INT value ;used in predicate

PROC PrintArray(INT ARRAY a BYTE size)
  BYTE i

  Put('[)
  FOR i=0 TO size-1
  DO
    PrintI(a(i))
    IF i<size-1 THEN
      Put(' )
    FI
  OD
  Put(']) PutE()
RETURN

;jump addr is stored in X and A registers
BYTE FUNC Predicate=*(PTR jumpAddr)
  DEFINE STX="$8E"
  DEFINE STA="$8D"
  DEFINE JSR="$20"
  DEFINE RTS="$60"
 [STX Predicate+8
  STA Predicate+7
  JSR $00 $00
  RTS]

PROC DoFilter(PTR predicateFun
  INT ARRAY src BYTE srcSize
  INT ARRAY dst BYTE POINTER dstSize)

  INT i

  dstSize^=0
  FOR i=0 TO srcSize-1
  DO
    value=src(i)
    IF Predicate(predicateFun) THEN
      dst(dstSize^)=value
      dstSize^==+1
    FI
  OD
RETURN

PROC DoFilterInplace(PTR predicateFun
  INT ARRAY data BYTE POINTER size)

  INT i,j

  i=0
  WHILE i<size^
  DO
    value=data(i)
    IF Predicate(predicateFun)=0 THEN
      FOR j=i TO size^-2
      DO
        data(j)=data(j+1)
      OD
      size^==-1
    ELSE
      i==+1
    FI
  OD
RETURN

BYTE FUNC Even()
  IF (value&1)=0 THEN
    RETURN (1)
  FI
RETURN (0)

BYTE FUNC NonNegative()
  IF value>=0 THEN
    RETURN (1)
  FI
RETURN (0)

PROC Main()
  INT ARRAY src=[65532 3 5 2 65529 1 0 65300 4123],dst(9)
  BYTE srcSize=[9],dstSize

  PrintE("Non destructive operations:") PutE()
  PrintE("Original array:")
  PrintArray(src,srcSize)

  DoFilter(Even,src,srcSize,dst,@dstSize)
  PrintE("Select all even numbers:")
  PrintArray(dst,dstSize)

  DoFilter(NonNegative,src,srcSize,dst,@dstSize)
  PrintE("Select all non negative numbers:")
  PrintArray(dst,dstSize)

  PutE()
  PrintE("Destructive operations:") PutE()
  PrintE("Original array:")
  PrintArray(src,srcSize)

  DoFilterInplace(Even,src,@srcSize)
  PrintE("Select all even numbers:")
  PrintArray(src,srcSize)

  DoFilterInplace(NonNegative,src,@srcSize)
  PrintE("Select all non negative numbers:")
  PrintArray(src,srcSize)
RETURN
Output:

Screenshot from Atari 8-bit computer

Non destructive operations:

Original array:
[-4 3 5 2 -7 1 0 -236 4123]
Select all even numbers:
[-4 2 0 -236]
Select all non negative numbers:
[3 5 2 1 0 4123]

Destructive operations:

Original array:
[-4 3 5 2 -7 1 0 -236 4123]
Select all even numbers:
[-4 2 0 -236]
Select all non negative numbers:
[2 0]

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]);
}

Actionscript 3

var arr:Array = new Array(1, 2, 3, 4, 5);
arr = arr.filter(function(item:int, index:int, array:Array) {
  return item % 2 == 0;
});

Ada

with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Text_Io; use Ada.Text_Io;

procedure Array_Selection is
   type Array_Type is array (Positive range <>) of Integer;
   Null_Array : Array_Type(1..0);

   function Evens (Item : Array_Type) return Array_Type is
   begin
      if Item'Length > 0 then
         if Item(Item'First) mod 2 = 0 then
            return Item(Item'First) & Evens(Item((Item'First + 1)..Item'Last));
         else
            return Evens(Item((Item'First + 1)..Item'Last));
         end if;
      else
         return Null_Array;
      end if;
   end Evens;

   procedure Print(Item : Array_Type) is
   begin
      for I in Item'range loop
         Put(Item(I));
         New_Line;
      end loop;
   end Print;

   Foo : Array_Type := (1,2,3,4,5,6,7,8,9,10);
begin
   Print(Evens(Foo));
end Array_Selection;

Here is a non-recursive solution:

with Ada.Text_IO;  use Ada.Text_IO;

procedure Array_Selection is
   type Array_Type is array (Positive range <>) of Integer;

   function Evens (Item : Array_Type) return Array_Type is
      Result : Array_Type (1..Item'Length);
      Index  : Positive := 1;
   begin
      for I in Item'Range loop
         if Item (I) mod 2 = 0 then
            Result (Index) := Item (I);
            Index := Index + 1;
         end if;
      end loop;
      return Result (1..Index - 1);
   end Evens;

   procedure Put (Item : Array_Type) is
   begin
      for I in Item'range loop
         Put (Integer'Image (Item (I)));
      end loop;
   end Put;
begin
   Put (Evens ((1,2,3,4,5,6,7,8,9,10)));
   New_Line;
end Array_Selection;

Aime

integer
even(integer e)
{
    return !(e & 1);
}

list
filter(list l, integer (*f)(integer))
{
    integer i;
    list v;

    i = 0;
    while (i < l_length(l)) {
        integer e;

        e = l_q_integer(l, i);
        if (f(e)) {
            lb_p_integer(v, e);
        }

        i += 1;
    }

    return v;
}

integer
main(void)
{
    integer i;
    list l;

    i = 0;
    while (i < 10) {
        lb_p_integer(l, i);
        i += 1;
    }

    l = filter(l, even);

    i = 0;
    while (i < l_length(l)) {
        o_space(1);
        o_integer(l_q_integer(l, i));
        i += 1;
    }
    o_byte('\n');

    return 0;
}
Output:
 0 2 4 6 8

ALGOL 68

Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386
MODE TYPE = INT;

PROC select = ([]TYPE from, PROC(TYPE)BOOL where)[]TYPE:
BEGIN
  FLEX[0]TYPE result;
  FOR key FROM LWB from TO UPB from DO
    IF where(from[key]) THEN
      [UPB result+1]TYPE new result;
      new result[:UPB result] := result;
      new result[UPB new result] := from[key];
      result := new result
    FI
  OD;
  result
END;

[]TYPE from values = (1,2,3,4,5,6,7,8,9,10);
PROC where even = (TYPE value)BOOL: NOT ODD value;

print((select(from values, where even), new line));

# 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))
Output:
         +2         +4         +6         +8        +10
         +4        +16        +36        +64       +100

ALGOL W

In the original Algol W, for procedures passed as parameters to another procedure, the types of the expected parameters could not be specified. (The types of the reuired parameters had to match exactly with those in the call)
In the sample below, the select procedure's parameters do not include the parameters of where - they are commented out.
Recent compilers (such as Awe) require the parameter types be specified and so the parameters to where should be uncommented when compilling with Awe.

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    %
    %      elements is returned in outUb - in and out can be the same array                                     %
    procedure select ( integer array in  ( * ); integer value  inUb
                     ; integer array out ( * ); integer result outUb
                     ; logical procedure where % ( integer value n ) %
                     ) ;
    begin
        outUb := 0;
        for i := 1 until inUb do begin
            if where( in( i ) ) then begin
                outUb := outUb + 1;
                out( outUb ) := in( i )
            end f_where_in_i
        end for_i
    end select ;
    % test the select procedure %
    logical procedure isEven ( integer value n ) ; not odd( n );
    integer array t, out ( 1 :: 10 );
    integer outUb;
    for i := 1 until 10 do t( i ) := i;
    select( t, 10, out, outUb, isEven );
    for i := 1 until outUb do writeon( i_w := 3, s_w := 0, out( i ) );
    write()
end.
Output:
  2  4  6  8 10

AmigaE

PROC main()
  DEF l : PTR TO LONG, r : PTR TO LONG, x
  l := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  r := List(ListLen(l))
  SelectList({x}, l, r, `Mod(x,2)=0)
  ForAll({x}, r, `WriteF('\d\n', x))
ENDPROC

AntLang

x:range[100]
{1- x mod 2}hfilter x

Apex

List<Integer> integers = new List<Integer>{1,2,3,4,5};
Set<Integer> evenIntegers = new Set<Integer>();
for(Integer i : integers)
{
    if(math.mod(i,2) == 0)
    {
        evenIntegers.add(i);
    }
}
system.assert(evenIntegers.size() == 2, 'We should only have two even numbers in the set');
system.assert(!evenIntegers.contains(1), '1 should not be a number in the set');
system.assert(evenIntegers.contains(2), '2 should be a number in the set');
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');

APL

      (0=2|x)/x20
2 4 6 8	10 12 14 16 18 20

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

Result is (a list):

{2, 4, 6}

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

to filter(inList, acceptor)
  set outList to {}
  repeat with anItem in inList
    if acceptor's accept(anItem) then
      set end of outList to contents of anItem
    end
  end
  return outList
end

script isEven
  to accept(aNumber)
    aNumber mod 2 = 0
  end accept
end script

filter({1,2,3,4,5,6}, isEven)


We can simplify and generalise this further by lifting any ordinary predicate handler into a script on the fly.

In this example, as with JavaScript filter lambdas, the lifted handler can optionally have one or two additional arguments:

  1. The index of the current element
  2. A reference to the whole list.


This allows for context-sensitive filters, which can take account of following or preceding elements in a sequence.

-------------------------- FILTER --------------------------

-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
    tell mReturn(f)
        set lst to {}
        set lng to length of xs
        repeat with i from 1 to lng
            set v to item i of xs
            if |λ|(v, i, xs) then set end of lst to v
        end repeat
        return lst
    end tell
end filter


--------------------------- TEST ---------------------------
on run
    filter(even, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10})

    --> {0, 2, 4, 6, 8, 10}
end run


-------------------- GENERIC FUNCTIONS ---------------------

-- even :: Int -> Bool
on even(x)
    0 = x mod 2
end even


-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn
Output:
{0, 2, 4, 6, 8, 10}

ARM Assembly

Works with: as version Raspberry Pi
or android 32 bits with application Termux
/* ARM assembly Raspberry PI  */
/*  program filterdes.s   */

/************************************/
/* Constantes                       */
/************************************/
/* for constantes see task include a file in arm assembly */
.include "../constantes.inc"

/************************************/
/* Initialized data                 */
/************************************/
.data
szMessResult:        .asciz "Start array : "
szMessResultFil:     .asciz "Filter array : "
szMessResultdest:    .asciz "Same array : "
szMessStart:         .asciz "Program 32 bits start.\n"
szCarriageReturn:    .asciz "\n"
.align 4
arrayNumber:         .int 1,2,3,4,5,6,7,8,9,10
.equ LGARRAY,   (. - arrayNumber) / 4
/************************************/
/* UnInitialized data               */
/************************************/
.bss 
.align 4
arrayNumberFil:           .skip 4 * LGARRAY  @ result array
sZoneConv:                .skip 24
/************************************/
/*  code section                    */
/************************************/
.text
.global main 
main:
    ldr r0,iAdrszMessStart      @ display start message
    bl affichageMess
    ldr r0,iAdrszMessResult     @ display message
    bl affichageMess
    ldr r5,iAdrarrayNumber      @ start array address
    mov r4,#0                   @ index
    
1:
    ldr r0,[r5,r4,lsl #2]       @ load a value
    ldr r1,iAdrsZoneConv
    bl conversion10             @ décimal conversion
    add r1,r1,r0                @ compute address end number
    add r1,#2                   @ add two characters 
    mov r0,#0                   @ for limit the size of display number
    strb r0,[r1]                @ to store a final zero
    ldr r0,iAdrsZoneConv
    bl affichageMess            @ display value
    add r4,r4,#1                @ increment index
    cmp r4,#LGARRAY             @ end array ?
    blt 1b                      @ no -> loop
    ldr r0,iAdrszCarriageReturn
    bl affichageMess
    
    ldr r6,iAdrarrayNumberFil   @ adrress result array
    mov r4,#0                   @ index
    mov r3,#0                   @ index result
2:
    ldr r0,[r5,r4,lsl #2]       @ load a value
    tst r0,#1                   @ odd ?
    streq r0,[r6,r3,lsl #2]     @ no -> store in result array
    addeq r3,r3,#1              @ and increment result index
    add r4,r4,#1                @ increment array index
    cmp r4,#LGARRAY             @ end ?
    blt 2b                      @ no -> loop
    
    ldr r0,iAdrszMessResultFil  
    bl affichageMess
    mov r4,#0                   @ init index
    
3:                              @ display filter result array
    ldr r0,[r6,r4,lsl #2]
    ldr r1,iAdrsZoneConv
    bl conversion10
    add r1,r1,r0
    add r1,#2
    mov r0,#0
    strb r0,[r1]
    ldr r0,iAdrsZoneConv
    bl affichageMess
    add r4,r4,#1
    cmp r4,r3
    blt 3b
    ldr r0,iAdrszCarriageReturn
    bl affichageMess
    
                                @ array destruction
    mov r4,#0                   @ index
    mov r3,#0                   @ index result
4:
    ldr r0,[r5,r4,lsl #2]       @ load a value
    tst r0,#1                   @ even ?
    bne 6f
    cmp r3,r4                   @ index =  no store
    beq 5f
    str r0,[r5,r3,lsl #2]       @ store in free item on same array
5:
    add r3,r3,#1                @ and increment result index
6:
    add r4,r4,#1                @ increment array index
    cmp r4,#LGARRAY             @ end ?
    blt 4b                      @ no -> loop
    
    ldr r0,iAdrszMessResultdest  
    bl affichageMess
    mov r4,#0                   @ init index
    
7:                              @ display array
    ldr r0,[r5,r4,lsl #2]
    ldr r1,iAdrsZoneConv
    bl conversion10
    add r1,r1,r0
    add r1,#2
    mov r0,#0
    strb r0,[r1]
    ldr r0,iAdrsZoneConv
    bl affichageMess
    add r4,r4,#1
    cmp r4,r3
    blt 7b
    ldr r0,iAdrszCarriageReturn
    bl affichageMess
      

100:                             @ standard end of the program
    mov r0, #0                   @ return code
    mov r7, #EXIT                @ request to exit program
    svc 0                        @ perform the system call
iAdrszCarriageReturn:    .int szCarriageReturn
iAdrszMessStart:         .int szMessStart
iAdrarrayNumber:         .int arrayNumber
iAdrszMessResult:        .int szMessResult
iAdrarrayNumberFil:      .int arrayNumberFil
iAdrszMessResultFil:     .int szMessResultFil
iAdrszMessResultdest:    .int szMessResultdest
iAdrsZoneConv:           .int sZoneConv
/***************************************************/
/*      ROUTINES INCLUDE                           */
/***************************************************/
/* for this file see task include a file in language ARM assembly*/
.include "../affichage.inc"
Output:
Program 32 bits start.
Start array : 1  2  3  4  5  6  7  8  9  10
Filter array : 2  4  6  8  10
Same array : 2  4  6  8  10

Arturo

arr: [1 2 3 4 5 6 7 8 9 10]

print select arr [x][even? x]
Output:
2 4 6 8 10

AutoHotkey

array = 1,2,3,4,5,6,7
loop, parse, array, `,
{
    if IsEven(A_LoopField)
        evens = %evens%,%A_LoopField%
}
stringtrimleft, evens, evens, 1
msgbox % evens
return

IsEven(number)
{
    return !mod(number, 2)
}


; ----- Another version: always with csv string ------
array = 1,2,3,4,5,6,7

even(s) {
	loop, parse, s, `,
		if !mod(A_LoopField, 2)
			r .= "," A_LoopField
	return SubStr(r, 2)
}

MsgBox % "Array => " array "`n" "Result => " even(array)


; ----- Yet another version: with array (requires AutoHotKey_L) ------
array2 := [1,2,3,4,5,6,7]

even2(a) {
	r := []
	For k, v in a
		if !mod(v, 2)
			r.Insert(v)
	return r
}

; Add "join" method to string object (just like python)
s_join(o, a) {
	Loop, % a.MaxIndex()
		r .= o a[A_Index]
	return SubStr(r, StrLen(o) + 1)
}
"".base.join := Func("s_join")

MsgBox % "Array => " ",".join(array2) "`n"  "Result => " ",".join(even2(array2))

AWK

In this example, an array is filled with the numbers 1..9. In a loop, even elements are collected into the string r. Note that sequence is not necessarily maintained.

One-liner:

$ 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}'
Output:
4 6 8 2

Regular script:

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
}

Same output.

Batch File

@echo off
setlocal enabledelayedexpansion

set numberarray=1 2 3 4 5 6 7 8 9 10
for %%i in (%numberarray%) do (
  set /a tempcount+=1
  set numberarray!tempcount!=%%i
)

echo Filtering all even numbers from numberarray into newarray...
call:filternew numberarray
echo numberarray - %numberarray%
echo newarray    -%newarray%
echo.
echo Filtering numberarray so that only even entries remain...
call:filterdestroy numberarray
echo numberarray -%numberarray%
pause>nul
exit /b

:filternew
set arrayname=%1
call:arraylength %arrayname%
set tempcount=0
for /l %%i in (1,1,%length%) do (
  set /a cond=!%arrayname%%%i! %% 2
  if !cond!==0 (
    set /a tempcount+=1
    set newarray!tempcount!=!%arrayname%%%i!
    set newarray=!newarray! !%arrayname%%%i!
  )
)
exit /b

:filterdestroy
set arrayname=%1
call:arraylength %arrayname%
set tempcount=0
set "%arrayname%="
for /l %%i in (1,1,%length%) do (
  set /a cond=!%arrayname%%%i! %% 2
  if !cond!==0 (
    set /a tempcount+=1
    set %arrayname%!tempcount!=!%arrayname%%%i!
    set %arrayname%=!%arrayname%! !%arrayname%%%i!
  )
)
exit /b

:arraylength
set tempcount=0
set lengthname=%1
set length=0
:lengthloop
set /a tempcount+=1
if "!%lengthname%%tempcount%!"=="" exit /b
set /a length+=1
goto lengthloop
Output:
Filtering all even numbers from numberarray into newarray...
numberarray - 1 2 3 4 5 6 7 8 9 10
newarray    - 2 4 6 8 10

Filtering numberarray so that only even entries remain...
numberarray - 2 4 6 8 10

BBC BASIC

      REM Create the test array:
      items% = 1000
      DIM array%(items%)
      FOR index% = 1 TO items%
        array%(index%) = RND
      NEXT

      REM Count the number of filtered items:
      filtered% = 0
      FOR index% = 1 TO items%
        IF FNfilter(array%(index%)) filtered% += 1
      NEXT

      REM Create a new array containing the filtered items:
      DIM new%(filtered%)
      filtered% = 0
      FOR index% = 1 TO items%
        IF FNfilter(array%(index%)) THEN
          filtered% += 1
          new%(filtered%) = array%(index%)
        ENDIF
      NEXT

      REM Alternatively modify the original array:
      filtered% = 0
      FOR index% = 1 TO items%
        IF FNfilter(array%(index%)) THEN
          filtered% += 1
          array%(filtered%) = array%(index%)
        ENDIF
      NEXT
      END

      DEF FNfilter(A%) = ((A% AND 1) = 0)

BCPL

get "libhdr"

// Copy every value for which p(x) is true from in to out
// This will also work in place by setting out = in
let filter(p, in, ilen, out, olen) be
$(  !olen := 0
    for i = 0 to ilen-1 do
        if p(in!i) do
        $(  out!!olen := in!i
            !olen := !olen + 1
        $)
$)

// Write N elements from vector
let writevec(v, n) be
    for i = 0 to n-1 do writef("%N ", v!i)

let start() be
$(  // Predicates 
    let even(n) = (n&1) = 0
    let mul3(n) = n rem 3 = 0
    
    let nums = table 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
    let arr = vec 20
    let len = ?
    
    writes("Numbers: ")
    writevec(nums, 15)
    
    // Filter 'nums' into 'arr'
    filter(even, nums, 15, arr, @len)
    writes("*NEven numbers: ")
    writevec(arr, len)
    
    // Filter 'arr' in place for multiples of 3
    filter(mul3, arr, len, arr, @len)
    writes("*NEven multiples of 3: ")
    writevec(arr, len)
    wrch('*N')
$)
Output:
Numbers: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Even numbers: 2 4 6 8 10 12 14
Even multiples of 3: 6 12

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
  )
)
1 3 5 7 9 25 49 81

Brat

#Prints [2, 4, 6, 8, 10]
p 1.to(10).select { x | x % 2 == 0 }

Burlesque

blsq ) 1 13r@{2.%n!}f[
{2 4 6 8 10 12}

BQN

General filtering is done using the /(Replicate) function, which can fliter elements given a bitmask. We can make a modifier based on it to accept a function for filtering.

_filter  {(𝔽𝕩)/𝕩}
Odd  2|

Odd _filter 12345
⟨ 1 3 5 ⟩

C

#include <stdio.h>
#include <stdlib.h>

int even_sel(int x) { return !(x & 1); }
int tri_sel(int x) { return x % 3; }

/* using a predicate function sel() to select elements */
int* grep(int *in, int len, int *outlen, int (*sel)(int), int inplace)
{
	int i, j, *out;

	if (inplace)	out = in;
	else		out = malloc(sizeof(int) * len);

	for (i = j = 0; i < len; i++)
		if (sel(in[i]))
			out[j++] = in[i];

	if (!inplace && j < len)
		out = realloc(out, sizeof(int) * j);

	*outlen = j;
	return out;
}

int main()
{
	int in[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	int i, len;

	int *even = grep(in, 10, &len, even_sel, 0);
	printf("Filtered even:");
	for (i = 0; i < len; i++) printf(" %d", even[i]);
	printf("\n");

	grep(in, 8, &len, tri_sel, 1);
	printf("In-place filtered not multiple of 3:");
	for (i = 0; i < len; i++) printf(" %d", in[i]);

	printf("\n");

	return 0;
}
Output:
Filtered even: 2 4 6 8 10
In-place filtered not multiple of 3: 1 2 4 5 7 8 10

C#

Works with: .NET version 1.1
ArrayList array = new ArrayList( new int[] { 1, 2, 3, 4, 5 } );
ArrayList evens = new ArrayList();
foreach( int i in array )
{
        if( (i%2) == 0 )
                evens.Add( i );
}
foreach( int i in evens )
       System.Console.WriteLine( i.ToString() );
Works with: .NET version 2.0
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() );
Works with: .NET version 3.5
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() );

Replacing the delegate with the more concise lambda expression syntax.

int[] array = { 1, 2, 3, 4, 5 };
int[] evens = array.Where(i => (i % 2) == 0).ToArray();

foreach (int i in evens)
    Console.WriteLine(i);

C++

#include <vector>
#include <algorithm>
#include <functional>
#include <iterator>
#include <iostream>

int main() {
  std::vector<int> ary;
  for (int i = 0; i < 10; i++)
    ary.push_back(i);
  std::vector<int> evens;
  std::remove_copy_if(ary.begin(), ary.end(), back_inserter(evens),
                      std::bind2nd(std::modulus<int>(), 2)); // filter copy
  std::copy(evens.begin(), evens.end(),
            std::ostream_iterator<int>(std::cout, "\n"));

  return 0;
}


Works with: C++11
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>

using namespace std;

int main() {
  vector<int> ary = {1, 2, 3, 4, 5, 6, 7, 8, 9};
  vector<int> evens;

  copy_if(ary.begin(), ary.end(), back_inserter(evens),
      [](int i) { return i % 2 == 0; });

  // print result
  copy(evens.begin(), evens.end(), ostream_iterator<int>(cout, "\n"));
}

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.

module SelectFromArray

import StdEnv

Create a lazy array where each element comes from the list 1 to 10.

array :: {Int}
array = {x \\ x <- [1 .. 10]}

Create (and print) a strict array where each element (coming from another array) is even.

Start :: {!Int}
Start = {x \\ x <-: array | isEven x}

Clojure

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

CoffeeScript

[1..10].filter (x) -> not (x%2)
Output:
[ 2,
  4,
  6,
  8,
  10 ]

Common Lisp

Common Lisp has many ways of accomplishing this task. Most of them involve higher-order sequence functions that take a predicate as the first argument and a list as the second argument. A predicate is a function that returns a boolean. The higher-order functions call the predicate for each element in list, testing the element.

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:

(remove-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10))
> (2 4 6 8 10)

However, this function is non-destructive, meaning the function creates a brand new list. This might be too prohibitive for very large lists.

Destructive

There is a destructive version that modifies the list in-place:

(delete-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10))
> (2 4 6 8 10)

Cowgol

include "cowgol.coh";

# Cowgol has strict typing and there are no templates either.
# Defining the type this way makes it easy to change.
typedef FilterT is uint32; 

# In order to pass functions around, we need to define an
# interface. The 'FilterPredicate' interface will take an argument
# and return zero if it should be filtered out.
interface FilterPredicate(x: FilterT): (keep: uint8);

# Filter an array and store it a new location. Returns the new length.
sub Filter(f:         FilterPredicate, 
           items:     [FilterT], 
           length:    intptr,
           result:    [FilterT]):
          (newLength: intptr) is
    newLength := 0;
    while length > 0 loop
        var item := [items];
        items := @next items;
        if f(item) != 0 then
            [result] := item;
            result := @next result;
            newLength := newLength + 1;
        end if;
        length := length - 1;
    end loop;
end sub;

# Filter an array in place. Returns the new length.
sub FilterInPlace(f:         FilterPredicate,
                  items:     [FilterT],
                  length:    intptr):
                 (newLength: intptr) is
    newLength := Filter(f, items, length, items);
end sub;

# Filter that selects even numbers
sub Even implements FilterPredicate is
    keep := (~ x as uint8) & 1;
end sub;

# Filter an array
var array: uint32[] := {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var filtered: uint32[@sizeof array];
var length := Filter(Even, &array[0], @sizeof array, &filtered[0]);

# Print result
var i: uint8 := 0;
while i < length as uint8 loop
    print_i32(filtered[i]);
    print_char(' ');
    i := i + 1;
end loop;
print_nl();

# Filter the result again in place for numbers less than 8
sub LessThan8 implements FilterPredicate is
    if x < 8 then keep := 1;
    else keep := 0;
    end if;
end sub;

length := FilterInPlace(LessThan8, &filtered[0], length);
i := 0;
while i < length as uint8 loop
    print_i32(filtered[i]);
    print_char(' ');
    i := i + 1;
end loop;
print_nl();
Output:
2 4 6 8 10
2 4 6

D

void main() {
    import std.algorithm: filter, equal;

    immutable data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    auto evens = data.filter!(x => x % 2 == 0); // Lazy.
    assert(evens.equal([2, 4, 6, 8, 10]));
}

Tango Version

Library: Tango
import tango.core.Array, tango.io.Stdout;

void main() {
    auto array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    // removeIf places even elements at the beginnig of the array and returns number of found evens
    auto evens = array.removeIf( ( typeof(array[0]) i ) { return (i % 2) == 1; } );
    Stdout("Evens - ")( array[0 .. evens] ).newline; // The order of even elements is preserved
    Stdout("Odds - ")( array[evens .. $].sort ).newline; // Unlike odd elements
}
Output:
 Evens - [ 2, 4, 6, 8, 10 ]
 Odds - [ 1, 3, 5, 7, 9 ]

Delphi

Hand-coded version

program FilterEven;

{$APPTYPE CONSOLE}

uses SysUtils, Types;

const
  SOURCE_ARRAY: array[0..9] of Integer = (0,1,2,3,4,5,6,7,8,9);
var
  i: Integer;
  lEvenArray: TIntegerDynArray;
begin
  for i in SOURCE_ARRAY do
  begin
    if not Odd(i) then
    begin
      SetLength(lEvenArray, Length(lEvenArray) + 1);
      lEvenArray[Length(lEvenArray) - 1] := i;
    end;
  end;

  for i in lEvenArray do
    Write(i:3);
  Writeln;
end.


Using Boost.Int library

Alternative using Boost.Int[1]:

Library: Types
Library: Boost.Int
program FilterEven;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  Types,
  Boost.Int;

var
  Source, Destiny: TIntegerDynArray;

begin
  Source.Assign([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

  // Non-destructively
  Destiny := Source.Filter(
    function(Item: Integer): Boolean
    begin
      Result := not odd(Item) and (Item <> 0);
    end);

  Writeln('[' + Destiny.Comma + ']');
  Readln;
end.

  // Destructively
  Source.Remove(
    function(Item: Integer): Boolean
    begin
      Result := odd(Item) or (Item = 0);
    end);

  Writeln('[' + Source.Comma + ']');
End.
Output:
[2,4,6,8]
[2,4,6,8]

Dyalect

Non-destructively

func Array.Filter(pred) {
    var arr = []
    for x in this when pred(x) {
        arr.Add(x)
    }
    arr
}

var arr = [1..20].Filter(x => x % 2 == 0)
print(arr)
Output:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Destructively

func Array.Filter(pred) {
    var i = 0
    while i < this.Length() {
        if !pred(this[i]) {
            this.RemoveAt(i)
        }
        i += 1
    }
}

var arr = [1..20]
arr.Filter(x => x % 2 == 0)
print(arr)
Output:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Idiomatic approach

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:

var xs = [1..20]
var arr = xs.Iterate().Filter(x => x % 2 == 0).Map(x => x.ToString())
print(arr.ToArray())
Output:
["2", "4", "6", "8", "10", "12", "14", "16", "18", "20"]

Déjà Vu

Non-destructively

filter pred lst:
	]
	for value in copy lst:
		if pred @value:
			@value
	[

even x:
	= 0 % x 2

!. filter @even [ 0 1 2 3 4 5 6 7 8 9 ]
Output:
[ 0 2 4 6 8 ]

Destructively

local :lst [ 0 1 2 3 4 5 6 7 8 9 ]

filter-destructively pred lst:
	local :tmp []
	while lst:
		pop-from lst
		if pred dup:
			push-to tmp
		else:
			drop
	while tmp:
		push-to lst pop-from tmp

filter-destructively @even lst

!. lst
Output:
[ 0 2 4 6 8 ]

E

There are several ways this could be done.

pragma.enable("accumulator")
accum [] for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] { _.with(x) }
var result := []
for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] {
    result with= x
}
result
def makeSeries := <elang:control.makeSeries>
makeSeries([1,2,3,4,5,6,7,8,9,10]).filter(fn x,_{x %% 2 <=> 0}).asList()

EasyLang

a[] = [ 1 2 3 4 5 6 7 8 9 ]
for i = 1 to len a[]
  if a[i] mod 2 = 0
    b[] &= a[i]
  .
.
print b[]

EchoLisp

(iota 12)  { 0 1 2 3 4 5 6 7 8 9 10 11 }

;; lists
(filter even? (iota 12))
     (0 2 4 6 8 10)

;; array (non destructive)
(vector-filter even? #(1 2 3 4 5 6 7 8 9 10 11 12 13))
     #( 2 4 6 8 10 12)

;; sequence, infinite, lazy
(lib 'sequences)
(define evens (filter even? [0 ..]))

(take evens 12)
     (0 2 4 6 8 10 12 14 16 18 20 22)

Ela

Using higher-order function (non-strict version)

open list

evenList = filter' (\x -> x % 2 == 0) [1..]

Using comprehension (non-strict version)

evenList = [& x \\ x <- [1..] | x % 2 == 0]

Elena

ELENA 5.0 :

import system'routines;
import system'math;
import extensions;
import extensions'routines;

public program()
{
    auto array := new int[]{1,2,3,4,5};

    var evens := array.filterBy::(n => n.mod(2) == 0).toArray();

    evens.forEach(printingLn)
}

Using strong typed collections and extensions:

import system'collections;
import system'routines'stex;
import system'math;
import extensions;

public program()
{
    int[] array := new int[]{1,2,3,4,5};

    array
        .filterBy::(int n => n.mod(2) == 0)
        .forEach::(int i){ console.printLine(i) }
}
Output:
2
4

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]


Emacs Lisp

Translation of: Common_Lisp
(seq-filter (lambda (x) (= (% x 2))) '(1 2 3 4 5 6 7 8 9 10))
Output:
(2 4 6 8 10)

EMal

writeLine(range(1, 11).filter(<int i|i % 2 == 0))
Output:
[2,4,6,8,10]

Erlang

Numbers = lists:seq(1, 5).
EvenNumbers = lists:filter(fun (X) -> X rem 2 == 0 end, Numbers).

Or using a list comprehension:

EvenNumbers = [X || X <- Numbers, X rem 2 == 0].

Euphoria

sequence s, evens
s = {1, 2, 3, 4, 5, 6}
evens = {}
for i = 1 to length(s) do
    if remainder(s[i], 2) = 0 then
        evens = append(evens, s[i])
    end if
end for
? evens
Output:
{2,4,6}

F#

let lst = [1;2;3;4;5;6]
List.filter (fun x -> x % 2 = 0) lst;;

val it : int list = [2; 4; 6]

Factor

Works with: Factor version 0.98

This code uses filter on an array.

10 <iota> >array [ even? ] filter .
! prints { 0 2 4 6 8 }

10 <iota> is already a sequence, so we can skip the conversion to array.

10 <iota> [ even? ] filter .
! prints V{ 0 2 4 5 8 }

Destructive

This uses filter! to modify the original vector.

USE: vectors
10 <iota> >vector [ even? ] filter! .
! prints V{ 0 2 4 5 8 }

To prove that filter! is destructive but filter is non-destructive, I assign the original vector to v.

USE: locals
10 <iota> >vector [| v |
    v [ even? ] filter drop
    v pprint " after filter" print
    v [ even? ] filter! drop
    v pprint " after filter!" print
] call
! V{ 0 1 2 3 4 5 6 7 8 9 } after filter
! V{ 0 2 4 6 8 } after filter!

Fantom

class Main
{
  Void main ()
  {
    items := [1, 2, 3, 4, 5, 6, 7, 8]
    // create a new list with just the even numbers
    evens := items.findAll |i| { i.isEven }
    // display the result
    echo (evens.join(","))
  }
}

Fe

(= filter (fn (f lst)
  (let res (cons nil nil))
  (let tail res)
  (while lst
    (let item (car lst))
    (if (f item) (do
      (setcdr tail (cons item nil))
      (= tail (cdr tail))))
    (= lst (cdr lst)))
  (cdr res)))

(print (filter (fn (x) (< 5 x)) '(1 4 5 6 3 2 7 9 0 8)))

Outputs:

(6 7 9 8)

Forth

: sel ( dest 0 test src len -- dest len )
  cells over + swap do   ( dest len test )
    i @ over execute if
      i @ 2over cells + !
      >r 1+ r>
    then
  cell +loop drop ;

create nums 1 , 2 , 3 , 4 , 5 , 6 ,
create evens 6 cells allot

: .array  0 ?do dup i cells + @ . loop drop ;

: even? ( n -- ? ) 1 and 0= ;

evens 0 ' even? nums 6 sel .array        \ 2 4 6

Fortran

module funcs
  implicit none
contains
  pure function iseven(x)
    logical :: iseven
    integer, intent(in) :: x
    iseven = mod(x, 2) == 0
  end function iseven
end module funcs
program Filter
  use funcs
  implicit none

  integer, parameter                 :: N = 100
  integer, dimension(N)              :: array
  integer, dimension(:), pointer     :: filtered

  integer :: i

  forall(i=1:N) array(i) = i

  filtered => filterwith(array, iseven)
  print *, filtered

contains

  function filterwith(ar, testfunc)
    integer, dimension(:), pointer        :: filterwith
    integer, dimension(:), intent(in)     :: ar
    interface
       elemental function testfunc(x)
         logical :: testfunc
         integer, intent(in) :: x
       end function testfunc
    end interface

    integer :: i, j, n

    n = count( testfunc(ar) )
    allocate( filterwith(n) )

    j = 1
    do i = lbound(ar, dim=1), ubound(ar, dim=1)
       if ( testfunc(ar(i)) ) then
          filterwith(j) = ar(i)
          j = j + 1
       end if
    end do

  end function filterwith

end program Filter

FreeBASIC

' FB 1.05.0 Win64

Type FilterType As Function(As Integer) As Boolean

Function isEven(n As Integer) As Boolean
  Return n Mod 2  = 0
End Function

Sub filterArray(a() As Integer, b() As Integer, filter As FilterType)
  If UBound(a) = -1 Then Return  '' empty array
  Dim count As Integer = 0
  Redim b(0 To UBound(a) - LBound(a))
  For i As Integer = LBound(a) To UBound(a)
    If filter(a(i)) Then
      b(count) = a(i)
      count += 1
    End If
  Next

  If count > 0 Then Redim Preserve b(0 To count - 1) '' trim excess elements
End Sub

' Note that da() must be a dynamic array as static arrays can't be redimensioned
Sub filterDestructArray(da() As Integer, filter As FilterType)
  If UBound(da) = -1 Then Return  '' empty array
  Dim count As Integer = 0
  For i As Integer = LBound(da) To UBound(da)
    If i > UBound(da) - count Then Exit For
    If Not filter(da(i)) Then '' remove this element by moving those still to be examined down one
      For j As Integer = i + 1 To UBound(da) - count
        da(j - 1) = da(j)
      Next j
      count += 1
      i -= 1
    End If
  Next i

  If count > 0 Then
    Redim Preserve da(LBound(da) To UBound(da) - count) '' trim excess elements
  End If
End Sub

Dim n As Integer = 12
Dim a(1 To n) As Integer '' creates dynamic array as upper bound is a variable
For i As Integer = 1 To n : Read a(i) : Next
Dim b() As Integer '' array to store results
filterArray a(), b(), @isEven
Print "The even numbers are (in new array)      : ";
For i As Integer = LBound(b) To UBound(b)
  Print b(i); " ";
Next
Print : Print
filterDestructArray a(), @isEven
Print "The even numbers are (in original array) : ";
For i As Integer = LBound(a) To UBound(a)
  Print a(i); " ";
Next
Print : Print
Print "Press any key to quit"
Sleep
End

Data 1, 2, 3, 7, 8, 10, 11, 16, 19, 21, 22, 27
Output:
The even numbers are (in new array)      :  2  8  10  16  22

The even numbers are (in original array) :  2  8  10  16  22

Frink

b = array[1 to 100]
c = select[b, {|x| x mod 2  == 0}]

Futhark

This example is incorrect. Please fix the code and remove this message.

Details: Futhark's syntax has changed, so this example will not compile

fun main(as: []int): []int =
  filter (fn x => x%2 == 0) as

FutureBasic

Even elements from array added to new array.

include "NSLog.incl"

local fn EvenNumbersFromArrayToNewArray
  CFArrayRef numbersArray = @[@1,@2,@3,@4,@5,@6,@7,@8,@9,@10,@11,@12]
  PredicateRef isEvenPred = fn PredicateWithFormat( @"modulus:by:(SELF, 2) == 0" )
  CFArrayRef   evensArray = fn ArrayFilteredArrayUsingPredicate( numbersArray, isEvenPred )
  NSLog( @"Array of odd and even numbers before sort:\n\t%@\n", numbersArray )
  NSLog( @"New array of even numbers after sort:\n\t%@\n", evensArray )
end fn
fn EvenNumbersFromArrayToNewArray
NSLogScrollToTop

Destructive version: Odd elemnts removed from mutable array.

local fn OddNumbersRemovedFromArray
  CFMutablearrayRef mutableNumbersArray = fn MutableArrayWithArray( @[@1,@2,@3,@4,@5,@6,@7,@8,@9,@10,@11,@12] )
  NSLog( @"Mutable array of odd and even numbers before sort:\n\t%@\n", mutableNumbersArray )
  PredicateRef isEvenPred = fn PredicateWithFormat( @"modulus:by:(SELF, 2) == 0" )
  MutableArrayFilterUsingPredicate( mutableNumbersArray, isEvenPred )
  NSLog( @"Mutable array with odd numbers removed:\n\t%@\n", mutableNumbersArray )
end fn

fn OddNumbersRemovedFromArray
NSLogScrollToTop

HandleEvents
Output:

Array of odd and even numbers before sort:
	(
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    11,
    12
)

New array of even numbers after sort:
	(
    2,
    4,
    6,
    8,
    10,
    12
)

Mutable array of odd and even numbers before sort:
	(
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    11,
    12
)

Mutable array with odd numbers removed:
	(
    2,
    4,
    6,
    8,
    10,
    12
)



Gambas

Click this link to run this code

sRandom As New String[]
'______________________________________________________________________________________________________
Public Sub Main()
Dim siCount As Short

For siCount = 0 To 19
  sRandom.Add(Rand(1, 100))
Next

Print sRandom.join(",")

NewArray
Destructive

End
'______________________________________________________________________________________________________
Public Sub NewArray() 'Select certain elements from an array into a new array in a generic way
Dim sEven As New String[]
Dim siCount As Short

For siCount = 0 To sRandom.Max
  If Even(sRandom[siCount]) Then sEven.Add(sRandom[siCount])
Next

Print sEven.join(",")

End
'______________________________________________________________________________________________________
Public Sub Destructive() 'Give a second solution which filters destructively
Dim siIndex As New Short[]
Dim siCount As Short

For siCount = 0 To sRandom.Max
  If Odd(sRandom[siCount]) Then siIndex.Add(siCount)
Next

For siCount = siIndex.max DownTo 0
  sRandom.Extract(siIndex[siCount], 1)
Next

Print sRandom.join(",")

End

Output:

36,13,21,37,68,6,47,4,53,80,90,95,60,29,76,39,6,93,83,91
36,68,6,4,80,90,60,76,6
36,68,6,4,80,90,60,76,6

GAP

# Built-in

Filtered([1 .. 100], IsPrime);
# [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 ]

Filtered([1 .. 10], IsEvenInt);
# [ 2, 4, 6, 8, 10 ]

Filtered([1 .. 10], IsOddInt);
# [ 1, 3, 5, 7, 9 ]

Go

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    a := rand.Perm(20)
    fmt.Println(a)       // show array to filter
    fmt.Println(even(a)) // show result of non-destructive filter
    fmt.Println(a)       // show that original array is unchanged
    reduceToEven(&a)     // destructive filter
    fmt.Println(a)       // show that a is now changed
    // a is not only changed, it is changed in place.  length and capacity
    // show that it still has its original allocated capacity but has now
    // been reduced in length.
    fmt.Println("a len:", len(a), "cap:", cap(a))
}

func even(a []int) (r []int) {
    for _, e := range a {
        if e%2 == 0 {
            r = append(r, e)
        }
    }
    return
}

func reduceToEven(pa *[]int) {
    a := *pa
    var last int
    for _, e := range a {
        if e%2 == 0 {
            a[last] = e
            last++
        }
    }
    *pa = a[:last]
}
Output:
[15 1 7 3 4 8 19 0 17 18 14 5 16 9 13 11 12 10 2 6]
[4 8 0 18 14 16 12 10 2 6]
[15 1 7 3 4 8 19 0 17 18 14 5 16 9 13 11 12 10 2 6]
[4 8 0 18 14 16 12 10 2 6]
a len: 10 cap: 20

Groovy

 def evens = [1, 2, 3, 4, 5].findAll{it % 2 == 0}

Haskell

In Haskell, a list is often more basic than an array:

ary = [1..10]
evens = [x | x <- ary, even x]

or

evens = filter even ary

To do the same operation on an array, the simplest way it to convert it lazily into a list:

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]

Note that the bounds must be known before creating the array, so the temporary list will be fully evaluated before the array is created.

Icon and Unicon

procedure main()

every put(A := [],1 to 10)              # make a list of 1..10
every put(B := [],iseven(!A))           # make a second list and filter out odd numbers
every writes(!B," ") | write()          # show
end

procedure iseven(x)                     #: return x if x is even or fail
if x % 2 = 0 then return x
end

IDL

The where() function can select elements on any logical expression. For example

result = array[where(NOT array AND 1)]

Insitux

> (filter even? [0 1 2 3 4])
[0 2 4]

> (var x [0 1 2 3 4])
[0 1 2 3 4]

> (var! x (filter even?)) ;replaces variable x by applying implicit closure
[0 2 4]

J

Solution:
With any verb (function) f that returns a boolean for each element of a vector v, the following is the generic solution:

   (#~ f) v

Examples:

   ] 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

Or using the generic form suggested above:

   isEven=: 0 = 2&|    NB. verb testing for even numbers
   (#~ isEven) v
92 92 36 40 16 2 22

We might decide that we use this pattern so often that it is worthwhile creating a new adverb select that filters an array using the verb to its left.

   select=: adverb def '(#~ u)'
   isPrime=: 1&p:

   isEven select v
92 92 36 40 16 2 22
   isPrime select v
43 89 23 2 29 43
   (isEven *. isPrime) select v
2

Destructive example:

   v=: isEven select v

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

Jakt

fn filter<T>(anon array: [T], anon filter_function: fn(anon value: T) -> bool) throws -> [T] {
    mut result: [T] = []
    for value in array {
        if filter_function(value) {
            result.push(value)
        }
    }
    return result
}

fn main() {
    mut numbers: [i64] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    let filtered = filter(numbers, fn(anon x: i64) -> bool => x % 2 == 0)
    println("{}", filtered)
}

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]);

A Java 8 solution with stream and generic types:

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));
}

Methodcall:

Integer[] array = {1, 2, 3, 4, 5};
Integer[] result = filter(array, i -> (i % 2) == 0);

Warning: This solution works not with primitive types!
For arrays with a primitive type use the wrapper class.

JavaFX Script

def array = [1..100];
def evens = array[n | n mod 2 == 0];

JavaScript

ES5

The standard way is to use the Array.prototype.filter function (

Works with: JavaScript version 1.6

):

var arr = [1,2,3,4,5];
var evens = arr.filter(function(a) {return a % 2 == 0});

Other ways:

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]);
Works with: Firefox version 2.0
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var evens = [i for (i in numbers) if (i % 2 == 0)];

function range(limit) {
  for(var i = 0; i < limit; i++) {
    yield i;
  }
}

var evens2 = [i for (i in range(100)) if (i % 2 == 0)];
Library: Functional
Functional.select("+1&1", [1,2,3,4])   // [2, 4]

ES6

(() => {
    'use strict';

    // isEven :: Int -> Bool
    const isEven = n => n % 2 === 0;


    // TEST

    return [1,2,3,4,5,6,7,8,9]
        .filter(isEven);

    // [2, 4, 6, 8]
})();
Output:
[2, 4, 6, 8]

Joy

[1 2 3 4 5 6 7 8 9 10] [2 rem null] filter.

jq

jq's "select" filter is designed to make it easy to filter both arrays and streams:

(1,2,3,4,5,6,7,8,9) | select(. % 2 == 0)
Output:
2
4
6
8
[range(1;10)] | map( select(. % 2 == 0) )
Output:
[2,4,6,8]

Julia

Works with: Julia version 0.6
@show filter(iseven, 1:10)
Output:
filter(iseven, 1:10) = [2, 4, 6, 8, 10]

K

   / even is a boolean function
   even:{0=x!2}
   even 1 2 3 4 5
0 1 0 1 0

   / filtering the even numbers
   a@&even'a:1+!10
2 4 6 8 10

   / as a function
   evens:{x@&even'x}
   a:10?100
45 5 79 77 44 15 83 88 33 99
   evens a
44 88

Alternative syntax:

   {x[&0=x!2]}
   {x[&even x]}

Destructive:

   a:evens a
44 88

Kotlin

// version 1.0.5-2

fun main(args: Array<String>) {
    val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
    println(array.joinToString(" "))

    val filteredArray = array.filter{ it % 2 == 0 }
    println(filteredArray.joinToString(" "))

    val mutableList = array.toMutableList()
    mutableList.retainAll { it % 2 == 0 }
    println(mutableList.joinToString(" "))
}
Output:
1 2 3 4 5 6 7 8 9
2 4 6 8
2 4 6 8

Lambdatalk

{def filter
 {lambda {:bool :s}
  {:bool {S.first :s}}
  {if {> {S.length :s} 1}
   then {filter :bool {S.rest :s}}
   else}}}
-> filter

{def even? {lambda {:n} {if {= {% :n 2} 0} then :n else}}}
-> even?
{def odd?  {lambda {:n} {if {= {% :n 2} 1} then :n else}}}
-> odd?

{filter even? {S.serie 1 20}}
-> 2  4  6  8  10  12  14  16  18  20
{filter odd? {S.serie 1 20}}
-> 1  3  5  7  9  11  13  15  17  19

Lang

Solution with isEven function:

&arr = fn.arrayGenerateFrom(fn.inc, 10)
fp.isEven = ($x) -> return parser.op($x % 2 === 0)
&filteredArr = fn.arrayFiltered(&arr, fp.isEven)
fn.println(&arr)
fn.println(&filteredArr)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 4, 6, 8, 10] 

Solution with combinator functions:

&arr = fn.arrayGenerateFrom(fn.inc, 10)
&filteredArr = fn.arrayFiltered(&arr, fn.combC(fn.combX1(fn.conStrictEquals, fn.combC(fn.mod, 2)), 0))
fn.println(&arr)
fn.println(&filteredArr)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 4, 6, 8, 10] 

Lang5

: filter  over swap execute select ;
10 iota "2 % not" filter . "\n" .

# [    0     2     4     6     8  ]

langur

Using the filter() function filters by a function or regex and returns a list of values.

val .list = series 7

writeln "    list: ", .list
writeln "filtered: ", filter fn{div 2}, .list
Output:
    list: [1, 2, 3, 4, 5, 6, 7]
filtered: [2, 4, 6]

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
staticarray(2, 4, 6, 8, 10)

Modifying the original array

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
array(2, 4, 6, 8, 10)

Liberty BASIC

' write random nos between 1 and 100
' to array1 counting matches as we go
dim array1(100)
count=100
for i = 1 to 100
    array1(i) = int(rnd(0)*100)+1
    count=count-(array1(i) mod 2)
next

'dim the extract and fill it
dim array2(count)
for i = 1 to 100
    if not(array1(i) mod 2) then
        n=n+1
        array2(n)=array1(i)
    end if
next

for n=1 to count
    print array2(n)
next

Lisaac

+ a, b : ARRAY[INTEGER];
a := ARRAY[INTEGER].create_with_capacity 10 lower 0;
b := ARRAY[INTEGER].create_with_capacity 10 lower 0;
1.to 10 do { i : INTEGER;
  a.add_last i;
};
a.foreach { item : INTEGER;
  (item % 2 = 0).if {
    b.add_last item;
  };
};

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]

Lua

function filter(t, func)
  local ret = {}
  for i, v in ipairs(t) do
    ret[#ret+1] = func(v) and v or nil
  end
  return ret
end

function even(a) return a % 2 == 0 end

print(unpack(filter({1, 2, 3, 4 ,5, 6, 7, 8, 9, 10}, even)))

The destructive version is even simpler, since tables are passed by reference:

function filter(t, func)
  for i, v in ipairs(t) do
    if not func(v) then table.remove(t, i) end
  end
end

function even(a) return a % 2 == 0 end

local values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
filter(values, even)
print(unpack(values))

M2000 Interpreter

Using Filter for arrays

Module Checkit {
      Print (1,2,3,4,5,6,7,8)#filter(lambda ->number mod 2=0)
}
Checkit

Old style

Function GetEvenNumbers can get pointer to array or array and return a pointer to array.

Module Filter2EvenNumbers get an array by reference and first place numbers to stack and then make stack an array and then copy to array.

Module Filter2EvenNumbers change definition and now place numbers in A() and at the last statement A() change dimension, preserving values.

We can use Base 1 arrays too: Dim Base 1, A(5) : A(1)=10,3,6,7,11


Module CheckIt {
      Function GetEvenNumbers (A as array){
            If len(A)=0 then =(,) : exit
            Flush  ' empty current stack (of values)
            n=each(A)
            While n {
                  if array(n) mod 2 = 0 then data array(n)
            }
            \\ [] return a stack object, leave an empty stack as current stack
            =Array([])
      }

      Dim A(5), B()
      A(0)=10,3,6,7,11
      B()=GetEvenNumbers(A())
      Print B()  ' print 10,6
      Print GetEvenNumbers((1,2,3,4,5,6,7,8))  ' 2 4 6 8

      Module Filter2EvenNumbers (&A()) {
            If len(A())=0 then  exit
            Stack New {
                  Flush  ' empty current stack (of values)
                  n=each(A())
                  While n {
                        if array(n) mod 2 = 0 then data array(n)
                  }
                  \\ [] return a stack object, leave an empty stack as current stack
                  A()=Array([])
            }
      }
      A(0)=10,3,6,7,11
      Filter2EvenNumbers &A()
      Print A()  ' 10 6
      Module Filter2EvenNumbers (&A()) {
            If len(A())=0 then  exit
            n=each(A())
            x=Dimension(A(), 0)-1  ' base of array (0 or 1)
            k=-x
            While n {
                  if array(n) mod 2 = 0 then x++ : A(x)=Array(n)
            }
            Dim A(x+k)
       }
      Dim A(5)
      A(0)=10,3,6,7,11
      Filter2EvenNumbers &A()
      Print A()  ' 10 6
}
CheckIt
}
CheckIt

Maple

evennum:=proc(nums::list(integer))
	return select(x->type(x, even), nums);
end proc;

Mathematica / Wolfram Language

Check for even integers:

Select[{4, 5, Pi, 2, 1.3, 7, 6, 8.0}, EvenQ]

gives:

{4, 2, 6}

To check also for approximate number (like 8.0 in the example above) a possible solution is:

Select[{4, 5, Pi, 2, 1.3, 7, 6, 8.0}, Mod[#, 2] == 0 &]

gives:

{4, 2, 6, 8.}

notice that the function returns 8. not 8 (the dot indicates that it is a float number, not an integer).

MATLAB

function evens = selectEvenNumbers(list)

    evens = list( mod(list,2) == 0 );

end
Output:
>> selectEvenNumbers([0 1 2 3 4 5 6 7 8 9 10])

ans =

     0     2     4     6     8    10

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]

sublist(a, evenp);
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

sublist(a, lambda([n], mod(n, 3) = 0));
[3, 6, 9, 12, 15, 18]

MAXScript

arr = #(1, 2, 3, 4, 5, 6, 7, 8, 9)
newArr = for i in arr where (mod i 2 == 0) collect i

min

Works with: min version 0.19.3
(1 2 3 4 5 6 7 8 9 10) 'even? filter print
Output:
(2 4 6 8 10)

MiniScript

We define a filter method on the list type that returns a new list containing elements filtered by the given function.

list.filter = function(f)
    result = []
    for item in self
        if f(item) then result.push item
    end for
    return result
end function

isEven = function(x)
    return x % 2 == 0
end function

nums = [1, 2, 3, 4, 5, 6, 7, 9, 12, 15, 18, 21]
print nums.filter(@isEven)

The in-place version is simpler, and even allows the use of an unnamed filter function, defined right on the method call.

list.filterInPlace = function(f)
    for i in range(self.len-1, 0)
        if not f(self[i]) then self.remove i
    end for
end function

nums = [1, 2, 3, 4, 5, 6, 7, 9, 12, 15, 18, 21]

nums.filterInPlace function(x)
    return x % 2 == 0
end function

print nums

ML

Standard ML

val ary = [1,2,3,4,5,6];
List.filter (fn x => x mod 2 = 0) ary

MLite

MLite is similar to Standard ML, though '=>' becomes '=' and 'List.' is elided:

val ary = [1,2,3,4,5,6];
filter (fn x = x mod 2 = 0) ary;

MUMPS

FILTERARRAY
 ;NEW I,J,A,B - Not making new, so we can show the values
 ;Populate array A
 FOR I=1:1:10 SET A(I)=I
 ;Move even numbers into B
 SET J=0 FOR I=1:1:10 SET:A(I)#2=0 B($INCREMENT(J))=A(I)
 QUIT

Testing:

WRITE

A(1)=1
A(2)=2
A(3)=3
A(4)=4
A(5)=5
A(6)=6
A(7)=7
A(8)=8
A(9)=9
A(10)=10
B(1)=2
B(2)=4
B(3)=6
B(4)=8
B(5)=10
I=10
J=5

Nemerle

Lists have a built-in method for filtering:

def original = $[1 .. 100];
def filtered = original.Filter(fun(n) {n % 2 == 0});
WriteLine($"$filtered");

The following would work for arrays:

Filter[T] (a : array[T], f : T -> bool) : array[T]
{
    def b = $[x | x in a, (f(x))];
    b.ToArray()
}

NetRexx

/* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 5000

-- =============================================================================
class RFilter public
  properties indirect
    filter = RFilter.ArrayFilter
  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method main(args = String[]) public static
    arg = Rexx(args)
    RFilter().runSample(arg)
    return
  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method runSample(arg) public
    sd1 = Rexx[]
    sd2 = Rexx[]

    say 'Test data:'
    sd1 = makeSampleData(100)
    display(sd1)
    setFilter(RFilter.EvenNumberOnlyArrayFilter())
    say
    say 'Option 1 (copy to a new array):'
    sd2 = getFilter().filter(sd1)
    display(sd2)
    say
    say 'Option 2 (replace the original array):'
    sd1 = getFilter().filter(sd1)
    display(sd1)
    return
  -- ---------------------------------------------------------------------------
  method display(sd = Rexx[]) public static
    say '-'.copies(80)
    loop i_ = 0 to sd.length - 1
      say sd[i_] '\-'
      end i_
    say
    return
  -- ---------------------------------------------------------------------------
  method makeSampleData(size) public static returns Rexx[]
    sd = Rexx[size]
    loop e_ = 0 to size - 1
      sd[e_] = (e_ + 1 - size / 2) / 2
      end e_
    return sd

-- =============================================================================
class RFilter.ArrayFilter abstract
  -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
  method filter(array = Rexx[]) public abstract returns Rexx[]
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
class RFilter.EvenNumberOnlyArrayFilter extends RFilter.ArrayFilter
  -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  method filter(array = Rexx[]) public returns Rexx[]
    clist = ArrayList(Arrays.asList(array))
    li = clist.listIterator()
    loop while li.hasNext()
      e_ = Rexx li.next
      if \e_.datatype('w'), e_ // 2 \= 0 then li.remove()
      end
    ry = Rexx[] clist.toArray(Rexx[clist.size()])
    return ry
Output:
Test data:
--------------------------------------------------------------------------------
-24.5 -24 -23.5 -23 -22.5 -22 -21.5 -21 -20.5 -20 -19.5 -19 -18.5 -18 -17.5 -17 -16.5 -16 -15.5 -15 -14.5 -14 -13.5 -13 -12.5 -12 -11.5 -11 -10.5 -10 -9.5 -9 -8.5 -8 -7.5 -7 -6.5 -6 -5.5 -5 -4.5 -4 -3.5 -3 -2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6 6.5 7 7.5 8 8.5 9 9.5 10 10.5 11 11.5 12 12.5 13 13.5 14 14.5 15 15.5 16 16.5 17 17.5 18 18.5 19 19.5 20 20.5 21 21.5 22 22.5 23 23.5 24 24.5 25

Option 1 (copy to a new array):
--------------------------------------------------------------------------------
-24 -22 -20 -18 -16 -14 -12 -10 -8 -6 -4 -2 0 2 4 6 8 10 12 14 16 18 20 22 24

Option 2 (replace the original array):
--------------------------------------------------------------------------------
-24 -22 -20 -18 -16 -14 -12 -10 -8 -6 -4 -2 0 2 4 6 8 10 12 14 16 18 20 22 24

NewLISP

> (filter (fn (x) (= (% x 2) 0)) '(1 2 3 4 5 6 7 8 9 10))
(2 4 6 8 10)

NGS

F even(x:Int) x % 2 == 0

evens = Arr(1...10).filter(even)

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

Nim

import sequtils

let values = toSeq(0..9)

# Filtering by returning a new sequence.
# - using an explicit filtering procedure.
echo "Even values: ", values.filter(proc(x: int): bool = x mod 2 == 0)
# - using a predicate.
echo "Odd values: ", values.filterIt(it mod 2 == 1)

# Filtering by modifying the sequence.
# - using an explicit filtering procedure.
var v1 = toSeq(0..9)
v1.keepIf(proc(x: int): bool = x mod 2 == 0)
echo "Even values: ", v1
# - using a predicate.
var v2 = toSeq(0..9)
v2.keepItIf(it mod 2 != 0)
echo "Odd values: ", v2
Output:
Even values: @[0, 2, 4, 6, 8]
Odd values: @[1, 3, 5, 7, 9]
Even values: @[0, 2, 4, 6, 8]
Odd values: @[1, 3, 5, 7, 9]

Objeck

use Structure;

bundle Default {
  class Evens {
    function : Main(args : String[]) ~ Nil {
      values := IntVector->New([1, 2, 3, 4, 5]);
      f := Filter(Int) ~ Bool;
      evens := values->Filter(f);

      each(i : evens) {
        evens->Get(i)->PrintLine();
      };
    }

    function : Filter(v : Int) ~ Bool {
      return v % 2 = 0;
    }
  }
}

Objective-C

Works with: Cocoa version Mac OS X 10.6+
NSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],
                                             [NSNumber numberWithInt:2],
                                             [NSNumber numberWithInt:3],
                                             [NSNumber numberWithInt:4],
                                             [NSNumber numberWithInt:5], nil];
NSArray *evens = [numbers objectsAtIndexes:[numbers indexesOfObjectsPassingTest:
  ^BOOL(id obj, NSUInteger idx, BOOL *stop) { return [obj intValue] % 2 == 0; } ]];
Works with: Cocoa version Mac OS X 10.5+
NSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],
                                             [NSNumber numberWithInt:2],
                                             [NSNumber numberWithInt:3],
                                             [NSNumber numberWithInt:4],
                                             [NSNumber numberWithInt:5], nil];
NSPredicate *isEven = [NSPredicate predicateWithFormat:@"modulus:by:(SELF, 2) == 0"];
NSArray *evens = [numbers filteredArrayUsingPredicate:isEven];
Works with: GNUstep
#import <Foundation/Foundation.h>

@interface NSNumber ( ExtFunc )
-(int) modulo2;
@end

@implementation NSNumber ( ExtFunc )
-(int) modulo2
{
  return [self intValue] % 2;
}
@end

int main()
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

  NSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],
                                               [NSNumber numberWithInt:2],
                                               [NSNumber numberWithInt:3],
                                               [NSNumber numberWithInt:4],
                                               [NSNumber numberWithInt:5], nil];

  NSPredicate *isEven = [NSPredicate predicateWithFormat:@"modulo2 == 0"];
  NSArray *evens = [numbers filteredArrayUsingPredicate:isEven];

  NSLog(@"%@", evens);


  [pool release];
  return 0;
}

OCaml

It is easier to do it with a list:

let lst = [1;2;3;4;5;6]
let even_lst = List.filter (fun x -> x mod 2 = 0) lst

Octave

arr = [1:100];
evennums = arr( mod(arr, 2) == 0 );
disp(evennums);

Oforth

100 seq filter(#isEven)

Ol

(filter even? '(1 2 3 4 5 6 7 8 9 10))

ooRexx

 Call random ,,1234567
 a=.array~new
 b=.array~new
 Do i=1 To 10
   a[i]=random(1,9999)
   End
 Say 'Unfiltered values:' a~makestring(line,' ')
 /* copy even numbers to array b */
 j=0
 Do i=1 to 10
   If filter(a[i]) Then Do
     j = j + 1
     b[j]=a[i]
     End
   end
 Say 'Filtered values (in second array):      ' b~makestring(line,' ')
 /* destructive filtering: copy within array a */
 j=0
 Do i=1 to 10
   If filter(a[i]) Then Do
     j = j + 1
     a[j]=a[i]
     End
   end
 /* destructive filtering: delete the remaining elements */
 Do i=10 To j+1 By -1
   a~delete(i)
   End
 Say 'Filtered values (destructive filtering):' a~makestring(line,' ')
 Exit
 filter: Return arg(1)//2=0
Output:
Unfiltered values: 1412 2244 6778 4002 439 3335 5877 8273 7882 1469
Filtered values (in second array):       1412 2244 6778 4002 7882
Filtered values (destructive filtering): 1412 2244 6778 4002 7882

Oz

It is easier to do it with a list:

declare
Lst = [1 2 3 4 5]
LstEven = {Filter Lst IsEven}

PARI/GP

Works with: PARI/GP version 2.4.3 and above
This code uses the select() function, which was added in PARI version 2.4.2. The order of the arguments changed between versions; to use in 2.4.2 change select(function, vector) to select(vector, function).
iseven(n)=n%2==0
select(iseven, [2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17])

Or in anonymous form

select(n -> n%2==0, [2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17])

Pascal

Arrays are supported in all versions of pascal so this simple example will cover the entire gamut.

Works with: Delphi


Works with: Turbo Pascal
const

numbers:array[0..9] of integer = (0,1,2,3,4,5,6,7,8,9);

for x = 1 to 10 do
     if odd(numbers[x]) then
         writeln( 'The number ',numbers[x],' is odd.');
     else
         writeln( 'The number ',numbers[x],' is even.');

The odd() function is a standard library function of pascal as is the function even().

Peloton

Fixed length English dialect

<@ LETCNWLSTLIT>numbers|1 2 3 4 5 6 7 8 9 10 11 12</@>
<@ DEFLST>evens</@>
<@ ENULSTLIT>numbers|
<@ TSTEVEELTLST>...</@>
<@ IFF>
<@ LETLSTELTLST>evens|...</@>
</@>
</@>

Perl

my @a = (1, 2, 3, 4, 5, 6);
my @even = grep { $_%2 == 0 } @a;

Phix

Library: Phix/basics

basic task

function even(integer i)
    return remainder(i,2)=0
end function
?filter(tagset(10),even)
Output:
{2,4,6,8,10}

extra credit

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.

function even(integer i)
    return remainder(i,2)=0
end function
procedure main()
sequence s = tagset(10),
         t = filter(s,even) -- copy-on-write here...
    ?s -- still all 10
    ?t -- 5
    s = filter(s,even)      -- ...but automatic pass by reference occurs here
    ?s -- 5
end procedure
main()
Output:
{1,2,3,4,5,6,7,8,9,10}
{2,4,6,8,10}
{2,4,6,8,10}

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

function lhnd_filter(sequence a, integer fn)
    sequence res = {}
    for i=1 to length(a) do
        if fn(a[i]) then
            res = append(res,a[i])
        end if
    end for
    return res
end function

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:

function lhd_filter(sequence a, integer fn)
    integer l = 0
    for i=1 to length(a) do
        if fn(a[i]) then
            l += 1
            a[l] = a[i]
        end if
    end for
    a = a[1..l] -- (can occur in situ)
    return a
end function
procedure main()
sequence s = tagset(10),
         t = lhd_filter(s,even) -- copy on write here...
    ?s -- still all 10
    ?t -- 5
    s = lhd_filter(s,even)      -- ...but automatic pass by reference occurs here
    ?s -- 5
end procedure
main()

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.

There is one case in the interpreter (pEmit2.e/rebuild_callback()) where it needs to circumvent this behaviour. For performance reasons it does not populate the symbol table with actual names until a fatal error or trace event occurs. At that time, the symbol table may have a reference count>1, so it deliberately patches it to 1 over the name population call to switch off the copy-on-write semantics, and later restores the reference count before carrying on. Not that you really needed to know that.

PHL

module var;

extern printf;

@Integer main [
	var arr = 1..9;
	var evens = arr.filter(#(i) i % 2 == 0);
	printf("%s\n", evens::str);

	return 0;
]

PHP

Using a standard loop

$arr = range(1,5);
$evens = array();
foreach ($arr as $val){
      if ($val % 2 == 0) $evens[] = $val);
}
print_r($evens);

Using a filter function

function is_even($var) { return(!($var & 1)); }
$arr = range(1,5);
$evens = array_filter($arr, "is_even");
print_r($evens);

Picat

List comprehension is probably the best way of filtering:

[I : I in 1..20, I mod 2 == 0]

A more general version of filtering is to use call/1 with a defined predicate (here p/1):

go => 
   L = 1..20,
   A = filter(L,p).

p(N) => N mod 2 == 0.

filter(A,F) = [N : N in A, call(F,N)].

This general version might be slower since using call/1 has some overhead.


PicoLisp

(filter '((N) (not (bit? 1 N)))
   (1 2 3 4 5 6 7 8 9) )
Output:
-> (2 4 6 8)

PL/I

(subscriptrange):
filter_values: procedure options (main); /* 15 November 2013 */
   declare a(20) fixed, b(*) fixed controlled;
   declare (i, j, n) fixed binary;

   a = random()*99999; /* fill the array with random elements from 0-99998 */
   put list ('Unfiltered values:');
   put skip edit (a) (f(6));
   /* Loop to count the number of elements that will be filtered */
   n = 0;
   do i = 1 to hbound(a);
      n = n + filter(a(i));
   end;
   allocate b(n);
   j = 0;
   do i = 1 to hbound(a);
      if filter(a(i)) then do; j = j + 1; b(j) = a(i); end;
   end;
   put skip list ('Filtered values:');
   put skip edit (b) (f(6));

filter: procedure (value) returns (bit(1));
   declare value fixed;

   return (iand(abs(value), 1) = 0);
end filter;

end filter_values;

Results:

Unfiltered values:
 44270  6008 80477 17004 91587 48669 29623 74640 29841 20019 77833 59865 49647  2272 54781
 36154 40114 71893 25960 76863
Filtered values:
 44270  6008 17004 74640  2272 36154 40114 25960

Pop11

Most natural solution in Pop11 would probably use list. Below we accumulate filtered elements on the stack and then allocate array for the result:

;;; Generic filtering procedure which selects from ar elements
;;; satisfying pred
define filter_array(ar, pred);
lvars i, k;
    stacklength() -> k;
    for i from 1 to length(ar) do
       ;;; if element satisfies pred we leave it on the stack
       if pred(ar(i)) then ar(i) endif;
    endfor;
    ;;; Collect elements from the stack into a vector
    return (consvector(stacklength() - k));
enddefine;
;;; Use it
filter_array({1, 2, 3, 4, 5},
             procedure(x); not(testbit(x, 0)); endprocedure) =>

PostScript

Library: initlib
[1 2 3 4 5 6 7 8 9 10] {2 mod 0 eq} find

PowerShell

$array = -15..37
$array | Where-Object { $_ % 2 -eq 0 }

Prolog

findall

evens(D, Es) :- findall(E, (member(E, D), E mod 2 =:= 0), Es).

Usage:

?- evens([1,2,3,4,5,6,7,8,9,10],E).
E = [2, 4, 6, 8, 10]

Anonymous functions

Works with SWI-Prolog and module(lambda) written by Ulrich Neumerkel, "lambda.pl" can be found there : http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl

?- 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].

filter and anonymous functions

Works with SWI-Prolog and module(lambda) written by Ulrich Neumerkel, "lambda.pl" can be found there : http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl

:- use_module(lambda).

%% filter(Pred, LstIn, LstOut)
%%
filter(_Pre, [], []).

filter(Pred, [H|T], L) :-
	filter(Pred, T, L1),
	(   call(Pred,H) -> L = [H|L1]; L = L1).

Usage :

 ?- filter(\X^(X mod 2 =:= 0), [1,2,3,4,5,6,7,8,9], L).
L = [2,4,6,8] .

PureBasic

Dim Tal.i(9)
Dim Evens.i(0)

;- Set up an array with random numbers
For i=0 To ArraySize(Tal())
  Tal(i)=Random(100)
Next

;- Pick out all Even and save them
j=0
For i=0 To ArraySize(Tal())
  If Tal(i)%2=0
    ReDim Evens(j)    ; extend the Array as we find new Even's
    Evens(j)=tal(i)
    j+1
  EndIf
Next

;- Display the result
PrintN("List of Randoms")
For i=0 To ArraySize(Tal())
  Print(Str(Tal(i))+" ")
Next
PrintN(#CRLF$+#CRLF$+"List of Even(s)")
For i=0 To ArraySize(Evens())
  Print(Str(Evens(i))+" ")
Next
Output:
List of Randoms
32 35 89 91 11 33 12 22 42 43
List of Even(s)
32 12 22 42

Python

Works with: Python version 2.4
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)

Alternative using the slice syntax with its optional "stride" expression:

values = range(10)
evens = values[::2]

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.

Since strings in Python can be treated as a sort of immutable list of characters then the slicing and extended slicing can also be used with them as well. Thus mystring[::-2] will return every other character from the reverse order of the string.

One can also assign to a slice (of a list or other mutable indexed object. Thus the following:

values = range(10)
values[::2] = [11,13,15,17,19]
print values
11, 1, 13, 3, 15, 5, 17, 7, 19, 9


Or in functional terms, by descending generality and increasing brevity:

Works with: Python version 3
'''Functional filtering - by descending generality and increasing brevity'''

from functools import (reduce)
from itertools import (chain)
import inspect
import re


def f1(xs):
    '''Catamorphism: fold / reduce.
       See [The expressiveness and universality of fold]
       (http://www.cs.nott.ac.uk/~pszgmh/fold.pdf)'''
    return reduce(lambda a, x: a + [x] if even(x) else a, xs, [])


def f2(xs):
    '''List monad bind/inject operator (concatMap combined with
       an (a -> [b]) function which wraps its result in a
       possibly empty list). This is the universal abstraction
       which underlies list comprehensions.'''
    return concatMap(lambda x: [x] if even(x) else [])(xs)


def f3(xs):
    '''Built-in syntactic sugar for list comprehensions.
       Convenient, and encouraged as 'Pythonic',
       but less general and expressive than a fold.'''
    return (x for x in xs if even(x))


def f4(xs):
    '''Built-in filter function'''
    return filter(even, xs)


def main():
    '''Tests'''
    xs = enumFromTo(0)(10)
    print(
        tabulated(showReturn)(
            'By descending generality and increasing brevity:\n'
        )(
            lambda f: list(f(xs))
        )([f1, f2, f3, f4])
    )


# GENERIC -------------------------------------------------


# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
    '''Concatenated list over which a function has been mapped.
       The list monad can be derived by using a function of the type
       (a -> [b]) which wraps its output in list
       (using an empty list to represent computational failure).'''
    return lambda xs: list(
        chain.from_iterable(
            map(f, xs)
        )
    )


# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
    '''Integer enumeration from m to n.'''
    return lambda n: list(range(m, 1 + n))


# even :: Int -> Bool
def even(x):
    '''Predicate'''
    return 0 == x % 2


# showReturn :: (a -> b) -> String
def showReturn(f):
    '''Stringification of final (return) expression in function body.'''
    return re.split('return ', inspect.getsource(f))[-1].strip()


# tabulated :: (a -> String) -> String -> (a -> b) -> [a] -> String
def tabulated(fShow):
    '''heading -> function -> input List -> tabulated output string'''
    def go(s, f, xs):
        w = max(len(fShow(x)) for x in xs)
        return s + '\n' + '\n'.join([
            fShow(x).rjust(w, ' ') +
            ' -> ' + str(f(x)) for x in xs
        ])
    return lambda s: lambda f: lambda xs: go(s, f, xs)


if __name__ == '__main__':
    main()
Output:
By descending generality and increasing brevity:

reduce(lambda a, x: a + [x] if even(x) else a, xs, []) -> [0, 2, 4, 6, 8, 10]
       concatMap(lambda x: [x] if even(x) else [])(xs) -> [0, 2, 4, 6, 8, 10]
                            (x for x in xs if even(x)) -> [0, 2, 4, 6, 8, 10]
                                      filter(even, xs) -> [0, 2, 4, 6, 8, 10]

Quackery

  [ [] ]'[ rot
    witheach
      [ tuck over do iff
          [ dip [ nested join ] ]
        else nip ]
    drop ]                        is only    ( [ --> [ )

  [ 1 & not ]                     is even    ( n --> b )

  [] 10 times [ 10 random join ]
  say "Ten arbitrary digits: "   dup       echo cr
  say "Only the even digits: "   only even echo cr
Output:
Ten arbitrary digits: [ 1 6 1 2 2 1 8 5 5 4 ]
Only the even digits: [ 6 2 2 8 4 ]

Destructively

  [ ]'[ over size times
    [ over i peek
      over do if
        [ dip [ i pluck drop ] ] ]
    drop ]                         is without ( [ --> [ )

  [ 1 & ]                          is odd     ( n --> b )

  [] 10 times [ i join ] shuffle
  say "Ten shuffled digits: "    dup         echo cr
  say "Less the odd digits: "    without odd echo cr
Output:
Ten shuffled digits: [ 5 6 8 2 1 4 0 3 9 7 ]
Less the odd digits: [ 6 8 2 4 0 ]

Q

x where 0=x mod 2

QBASIC

Works with: QBasic version 1.1
Works with: QuickBasic version 4.x
Works with: Visual Basic for DOS version 1.0
Works with: PDS version 7.x

Using two arrays

This version uses two arrays.

' OPTION EXPLICIT

' Filter
' This program selects certain elements from an array into a new array in a generic way

' Var
' $DYNAMIC

TYPE regSub
  aNum AS INTEGER
END TYPE
CONST Even = 2
CONST Uneven = 1
CONST cFile = "DUMMY$$$.$$$"
CONST False = 0, True = NOT False

DIM t AS INTEGER
DIM t2 AS INTEGER
DIM f AS INTEGER
DIM i AS INTEGER
DIM iFlag AS INTEGER
DIM iGetWhat AS INTEGER
DIM iArray%(1 TO 1)
DIM iArray2%(1 TO 1)
DIM rSub AS regSub

' Initialize vars
iFlag = False
f = FREEFILE
iGetWhat = Even
RANDOMIZE TIMER
t = INT(RND * 300) + 1
REDIM iArray%(1 TO t)

' Main program cycle
OPEN cFile FOR OUTPUT AS #f
CLOSE

OPEN cFile FOR RANDOM AS #f LEN = LEN(rSub)

CLS
PRINT "Select items in an array into a new array in a generic way."
PRINT "Base array:"
FOR i = 1 TO t
  iArray%(i) = INT(RND * 2000) + 1
  PRINT iArray%(i);
  IF (iArray%(i) MOD 2) = 0 AND iGetWhat = Even THEN
    iFlag = True
  ELSEIF (iArray%(i) MOD 2) <> 0 AND iGetWhat = Uneven THEN
    iFlag = True
  END IF

  IF iFlag THEN
    rSub.aNum = iArray%(i)
    PUT #f, , rSub
    iFlag = False
  END IF
NEXT i

' Redims the array
t2 = LOF(f) / LEN(rSub)
REDIM iArray2%(1 TO t2)

FOR i = 1 TO t2
  GET #f, i, rSub
  iArray2%(i) = rSub.aNum
NEXT i

CLOSE #f
KILL cFile

PRINT

' Shows the result
IF t2 > 0 THEN
  PRINT "Selected items from the array (total:"; t2; "of"; t; "):"
  FOR i = 1 TO t2
    PRINT iArray2%(i);
  NEXT i
END IF

PRINT
PRINT "End of program."
END
Output:

The output can change as the size of the base array and its values varies on each run.

Select items in an array into a new array in a generic way.
Base array:
 1426  770  1686  1472  385  1212  909  656  776  707  918  1646  1258  1406  887  42
Selected items from the array (total: 12 of 16 ):
 1426  770  1686  1472  1212  656  776  918  1646  1258  1406  42
End of program. 

Using one array

Extra points: This version uses one array.

' OPTION EXPLICIT

' Filter
' This program selects certain elements from an array into a new array in a generic way
' Extra points: Destroys the original values in the array

' Var
' $DYNAMIC

TYPE regSub
  aNum AS INTEGER
END TYPE
CONST Even = 2
CONST Uneven = 1
CONST cFile = "DUMMY$$$.$$$"
CONST False = 0, True = NOT False
DIM t AS INTEGER
DIM t2 AS INTEGER
DIM f AS INTEGER
DIM i AS INTEGER
DIM iFlag AS INTEGER
DIM iGetWhat AS INTEGER
DIM iArray%(1 TO 1)
DIM rSub AS regSub

' Initialize vars
iFlag = False
t = INT(RND * 300) + 1
f = FREEFILE
iGetWhat = Even
REDIM iArray%(1 TO t)

' Main program cycle
OPEN cFile FOR OUTPUT AS #f
CLOSE

OPEN cFile FOR RANDOM AS #f LEN = LEN(rSub)

CLS
RANDOMIZE TIMER
PRINT "Select items in an array into a new array in a generic way."
PRINT "Base array:"
FOR i = 1 TO t
  iArray%(i) = INT(RND * 2000) + 1
  PRINT iArray%(i);
  IF (iArray%(i) MOD 2) = 0 AND iGetWhat = Even THEN
    iFlag = True
  ELSEIF (iArray%(i) MOD 2) <> 0 AND iGetWhat = Uneven THEN
    iFlag = True
  END IF

  IF iFlag THEN
    rSub.aNum = iArray%(i)
    PUT #f, , rSub
    iFlag = False
  END IF
NEXT i

' Redims the array
t = LOF(f) / LEN(rSub)
REDIM iArray%(1 TO t)

FOR i = 1 TO t
  GET #f, i, rSub
  iArray%(i) = rSub.aNum
NEXT i

CLOSE #f
KILL cFile

PRINT

' Shows the result
t2 = UBOUND(iArray%)
IF t2 > 0 THEN
  PRINT "Selected items from the array (total:"; t2; "of"; t; "):"
  FOR i = 1 TO t2
    PRINT iArray%(i);
  NEXT i
END IF

PRINT
PRINT "End of program."
END
Output:

The output can change as the size of the base array and its values varies on each run.

Select items in an array into a new array in a generic way.
Base array:
 1426  770  1686  1472  385  1212  909  656  776  707  918  1646  1258  1406  887  42
Selected items from the array (total: 12 of 16 ):
 1426  770  1686  1472  1212  656  776  918  1646  1258  1406  42
End of program. 

R

a <- 1:100
evennums <- a[ a%%2 == 0 ]
print(evennums)

Racket

The classic way:

-> (filter even? '(0 1 2 3 4 5 6 7 8 9))
'(0 2 4 6 8)

getting the list of non-evens too:

-> (partition even? '(0 1 2 3 4 5 6 7 8 9))
'(0 2 4 6 8)
'(1 3 5 7 9)

Finally, using a for loop, similar to list comprehension:

-> (for/list ([x '(0 1 2 3 4 5 6 7 8 9)] #:when (even? x)) x)
'(0 2 4 6 8)

Raku

(formerly Perl 6)

Works with: Rakudo version 2018.03
my @a = 1..6;
my @even = grep * %% 2, @a;

Alternatively:

my @a = 1..6;
my @even = @a.grep(* %% 2);

Destructive:

my @a = 1..6;
@a .= grep(* %% 2);

Raven

[ 0 1 2 3 4 5 6 7 8 9 ] as nums
group nums each
    dup 1 & if drop
list as evens

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
Output:
[2 4 6 8 10 12 14 16 18 20 22 24
26 28 30 32 34 36 38 40 42 44 46 48 50
52 54 56 58 60 62 64 66 68 70 72 74 76
78 80 82 84 86 88 90 92 94 96 98 100]

Red

Red []
orig: [] repeat i 10 [append orig i]
?? orig
cpy: [] forall orig [if even? orig/1 [append cpy orig/1]]
;; or - because we know each second element is even :- )
;; cpy: extract next orig 2
?? cpy
remove-each ele orig [odd? ele]    ;; destructive
?? orig
Output:
orig: [1 2 3 4 5 6 7 8 9 10]
cpy: [2 4 6 8 10]
orig: [2 4 6 8 10]
>>

REXX

using two arrays

This example uses two arrays.   The   random   BIF is used to generate the numbers.

/*REXX program selects all even numbers from an array and puts them   */
/* into a new array.                                                  */
Parse Arg n seed .                /* obtain optional arguments from CL*/
If n==''|n=="," Then n=50         /* Not specified?  use the default  */
If datatype(seed,'W') Then
  Call random,,seed               /* use RANDOM seed for repeatability*/
Do i=1 For n                      /* generate  N  random numbers      */
  old.i=random(1,99999)           /* generate random number           */
  End
m=0                               /* number of elements in NEW        */
Do j=1 To n                       /* process the elements of the OLD  */
  If old.j//2==0 Then Do          /* if element is even, then         */
    m=m+1                         /* bump the number of NEW elemens   */
    new.m=old.j                   /* assign the number to the NEW     */
    End
  End
Do k=1 For m                      /* display all the NEW numbers.     */
  Say right('new.'k,20) '=' right(new.k,9)
  End
output   when using the input of:     ,   12345

The 12345 is the random BIF   seed   so that the random numbers can be repeated when re-running the REXX program.

               new.1 =     17520
               new.2 =     77326
               new.3 =     36128
               new.4 =     19124
               new.5 =       202
               new.6 =     82314
               new.7 =     96140
               new.8 =      4066
               new.9 =      3254
              new.10 =     91178
              new.11 =     18806
              new.12 =     60646
              new.13 =     26428
              new.14 =     16790
              new.15 =     24868
              new.16 =     61954
              new.17 =     63424
              new.18 =     97538
              new.19 =     82278
              new.20 =     33360
              new.21 =     74026
              new.22 =     48472
              new.23 =     44360

Using a control array

This version uses a control array (even.*)

/*REXX program uses a control array to tell which elements ars even.  */
Parse Arg n seed .                /* obtain optional arguments from CL*/
If n==''|n=="," Then n=50         /* Not specified?  use the default  */
If datatype(seed,'W') Then
  Call random,,seed               /* use RANDOM seed for repeatability*/
Do i=1 For n                      /* generate n random numbers        */
  x.i=random(1,99999)             /* generate random number           */
  End
even.=0                           /* all even bits are off            */
Do j=1 To n                       /* process the elements of x.*      */
  If x.j//2==0 Then               /* if element is even, then         */
    even.j=1                      /* turn on the even bit             */
  End
Do k=1 To n                       /* display all the numbers          */
  If even.k Then                  /* that are even                    */
    Say right('x.'k,20) '=' right(x.k,9)
  End
output   when using the input of:     20   12345
                 x.3 =     52754
                 x.5 =     94296
                 x.6 =      2068
                x.13 =     71494
                x.14 =     71628
                x.15 =     47404
                x.19 =     92502
                x.20 =     24808

using one array, destructive

This version just uses one array to perform the filtering instead of creating a   new   array. The result is a sparse array. This method doesn't need as much memory.

/*REXX program sets all elements containing odd numbers to blank      */
Parse Arg n seed .                /* obtain optional arguments from CL*/
If n==''|n=="," Then n=50         /* Not specified?  use the default  */
If datatype(seed,'W') Then
  Call random,,seed               /* use RANDOM seed for repeatability*/
Do i=1 For n                      /* generate  N  random numbers      */
  x.i=random(1,99999)             /* generate random number           */
  End
Do j=1 To n                       /* process the elements of x.*      */
  If x.j//2<>0 Then               /* if element is not even, then     */
    Drop x.j                      /* delete it                        */
  End
Do k=1 To n                       /* display all the numbers          */
  If datatype(x.k)='NUM' Then     /* that are even                    */
    Say right('x.'k,20) '=' right(x.k,9)
  End

For the following input:     20 12345

output   is the same as the 2nd REXX version.



Ring

aList = [1, 2, 3, 4, 5, 6]
bArray = list(3)
see evenSelect(aList)

func evenSelect aArray
i = 0
for n = 1 to len(aArray)
    if (aArray[n] % 2) = 0
       i = i + 1
       bArray[i] = aArray[n] ok
next
return bArray

RPL

Works with: Halcyon Calc version 4.2.7
RPL code Comment
≪ 
  DUP SIZE {} 2 ROT FOR j OVER j GET + 2 STEP
≫ 'FILTR' STO

≪ 
  LIST→ → len
  ≪ {} len 1 FOR j
       IF j 2 MOD THEN SWAP DROP ELSE + END
    -1 STEP
≫ ≫ 'FILTD' STO
FILTR ( { a1 a2.. an }  --  { a1 a2.. an }  { a2 a4... a2k } )
selective copy
 
 
FILTD ( { a1 a2.. an }  -- { a2 a4... a2k } )
 Destructive version : put the array in the stack...

... and make a new one by picking one out of two items


Input:
{ 1 2 3 4 5 6 7 8 9 } FILTR
{ 1 2 3 4 5 6 7 8 9 } FILTD
Output:
3: { 1 2 3 4 5 6 7 8 9 }
2: { 2 4 6 8 }
1: { 2 4 6 8 }

Ruby

Enumerable#select is the filter that returns a new Array.

# Enumerable#select returns a new array.
ary = [1, 2, 3, 4, 5, 6]
even_ary = ary.select {|elem| elem.even?}
p even_ary # => [2, 4, 6]

# Enumerable#select also works with Range.
range = 1..6
even_ary = range.select {|elem| elem.even?}
p even_ary # => [2, 4, 6]

Destructive

Array#select! is the destructive version which modifies the original Array.

ary = [1, 2, 3, 4, 5, 6]
ary.select! {|elem| elem.even?}
p ary # => [2, 4, 6]

Shorthand:

ary = [1, 2, 3, 4, 5, 6]
ary.select!(&:even?)
p ary # => [2, 4, 6]

Run BASIC

dim a1(100)
count	= 100
for i = 1 to 100
    a1(i) = int(rnd(0)*100)+1
    count = count - (a1(i) mod 2)
next

'dim the extract and fill it
dim a2(count)
for i = 1 to 100
    if not(a1(i) mod 2) then
        n	= n+1
        a2(n)	= a1(i)
    end if
next

for i = 1 to count
    print a2(i)
next

Rust

fn main() {
    println!("new vec filtered: ");
    let nums: Vec<i32> = (1..20).collect();
    let evens: Vec<i32> = nums.iter().cloned().filter(|x| x % 2 == 0).collect();
    println!("{:?}", evens);

    // Filter an already existing vector
    println!("original vec filtered: ");
    let mut nums: Vec<i32> = (1..20).collect();
    nums.retain(|x| x % 2 == 0);
    println!("{:?}", nums);
}
Output:
new vec filtered:
[2, 4, 6, 8, 10, 12, 14, 16, 18]
original vec filtered:
[2, 4, 6, 8, 10, 12, 14, 16, 18]

Salmon

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.

iterate(x; comprehend(y; [1...10]; y % 2 == 0) (y))
    x!;

Here's a version that walks an array destructively removing the non-even elements:

variable my_array := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
variable write_position := 0;
iterate (read_position; [0...9])
  {
    immutable elem := my_array[read_position];
    if (elem % 2 == 0)
      {
        my_array[write_position] := elem;
        ++write_position;
      };
  };
// Chop off the end of the array.
my_array := my_array[0...write_position - 1];
iterate(x; my_array)
    x!;

Sather

class MARRAY{T} < $ARR{T} is
  include ARRAY{T};

  filter_by(r:ROUT{T}:BOOL):SAME is
    o:MARRAY{T} := #;
    loop e ::= elt!;
      if r.call(e) then
        o := o.append(#MARRAY{T}(|e|));
      end;
    end;
    return o;
  end;

end;

class MAIN is
  main is
    a ::= #MARRAY{INT}(|5, 6, 7, 8, 9, 10, 11|);
    sel ::= a.filter_by( bind(_.is_even) );
    loop #OUT + sel.elt! + " "; end;
    #OUT + "\n";
  end;
end;

Scala

(1 to 100).filter(_ % 2 == 0)

Scheme

Filter function definition:

(define filter
  (lambda (fn lst)
    (let iter ((lst lst) (result '()))
      (if (null? lst)
         (reverse result)
         (let ((item (car lst))
               (rest (cdr lst)))
           (if (fn item)
               (iter rest (cons item result))
               (iter rest result)))))))

Usage in the interactive prompt:

> (filter even? '(1 2 3 4 5 6 7 8 9 10))
(2 4 6 8 10)

Or as a function:

(define (select-even lst)
  (filter even? lst))

(select-even '(1 2 3 4 5 6 7 8 9 10))

Seed7

var array integer: arr is [] (1, 2, 3, 4, 5);
var array integer: evens is 0 times 0;
var integer: number is 0;

for number range arr do
  if not odd(number) then
    evens &:= [] (number);
  end if;
end for;

SequenceL

Filters are primarily written in SequenceL using partial Indexed Functions.

evens(x(1))[i] := x[i] when x[i] mod 2 = 0;
Output:
cmd:>evens(1...5)
[2,4]

Sidef

var arr = [1,2,3,4,5]

# Creates a new array
var new = arr.grep {|i| i.is_even }
say new    # => [2, 4]

# Destructive (at variable level)
arr.grep! {|i| i.is_even }
say arr    # => [2, 4]

Slate

#(1 2 3 4 5) select: [| :number | number isEven].

Slope

(define number-list (range 20))

(define even-number-list
  (filter
    (lambda (num) (equal? (% num 2) 0))
    number-list))

(display number-list "\n" even-number-list "\n")

Output:

(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19)
(0 2 4 6 8 10 12 14 16 18)

Smalltalk

Creates a new array:

#(1 2 3 4 5) select: [:number | number even]

or for short:

#(1 2 3 4 5) select:#even

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.

SQL

Task: Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array.

Works with: MS SQL
--Create the original array (table #nos) with numbers from 1 to 10
create table #nos (v int)
declare @n int set @n=1
while @n<=10 begin insert into #nos values (@n) set @n=@n+1 end

--Select the subset that are even into the new array (table #evens)
select v into #evens from #nos where v % 2 = 0

-- Show #evens
select * from #evens

-- Clean up so you can edit and repeat:
drop table #nos
drop table #evens

'

Works with: MySQL
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);
insert into evens select v from nos where v%2=0;
select * from evens order by v; /*2,4,6,8,10*/
drop table nos;
drop table evens;

Or to be shorter, you could create the table evens directly from the query result :

create temporary table evens select * from nos where v%2=0;

Stata

mata
a=2,9,4,7,5,3,6,1,8

// Select even elements of a
select(a,mod(a,2):==0)

// Select the indices of even elements of a
selectindex(mod(a,2):==0)
end

Swift

let numbers = [1,2,3,4,5,6]
let even_numbers = numbers.filter { $0 % 2 == 0 }
println(even_numbers)
Output:
[2, 4, 6]

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}]
Output:
56 62 76 82 94 28 90 52 44


Inplace way, quite the inefficient contraption compared to mapping:

proc lreplaceip {_list args} {
        upvar 1 $_list list
        set list [lreplace $list[set list {}] {*}$args]
}

set l {56 21 71 27 39 62 87 76 82 94 45 83 65 45 28 90 52 44 1 89}

for {set i 0} {$i < [llength $l]} {} {
        if {[lindex $l $i] % 2 == 1} {
                lreplaceip l $i $i
        } else {
                incr i
        }
}

puts $l
Output:
56 62 76 82 94 28 90 52 44

Explanation: https://wiki.tcl-lang.org/page/lreplace, section "Performance: Modifying a List In-Place"
Proof by timing removal of the end element of lists of different lengths:

proc lreplaceip {_list args} {
        upvar 1 $_list list
        set list [lreplace $list[set list {}] {*}$args]
}

proc iota {n {start 0}} {
        set res {}
        set end [expr {$start + $n}]
        for {set i $start} {$i <= $end} {incr i} {
                lappend res $i
        }
        return $res
}

foreach e {5 6 7} {
        set l [iota 1e$e]
        puts 1e$e
        puts "    lreplace:   [time {set l [lreplace $l end end]}]"
        puts "    lreplaceip: [time {lreplaceip l end end}]"
}
Output:
1e5
    lreplace:   564 microseconds per iteration
    lreplaceip: 19 microseconds per iteration
1e6
    lreplace:   15215 microseconds per iteration
    lreplaceip: 6 microseconds per iteration
1e7
    lreplace:   148028 microseconds per iteration
    lreplaceip: 6 microseconds per iteration

Toka

10 cells is-array table
10 cells is-array even
{
  variable source
  [ swap source ! >r reset r> 0
    [ i source @ array.get
      dup 2 mod 0 <> [ drop ] ifTrue
    ] countedLoop
    depth 0 swap [ i even array.put ] countedLoop
  ]
} is copy-even
10 0 [ i i table array.put ] countedLoop
table 10 copy-even

TUSCRIPT

$$ MODE TUSCRIPT
arr="1'4'9'16'25'36'49'64'81'100",even=""
LOOP nr=arr
rest=MOD (nr,2)
IF (rest==0) even=APPEND (even,nr)
ENDLOOP
PRINT even
Output:
4'16'36'64'100

UNIX Shell

Works with: 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

Or, using grep:

a=(1 2 3 4 5)
read -a e -d\n < <(printf '%s\n' "${a[@]}" | grep '[02468]$')

Either way, to display the results:

echo "${a[@]}"
echo "${e[@]}"
Output:
1 2 3 4 5
2 4

UnixPipes

yes \ | cat -n | while read a; do ; expr $a % 2 >/dev/null && echo $a ; done

Ursala

Ursala doesn't have arrays, except when the run time system transparently converts a list to an array as needed for an external math library function call. However, selection can be done on lists.

Unary predicates

The most common way to select items from a list according to a unary predicate p is to write p*~, as shown below.

#import std
#import nat

x = <89,36,13,15,41,39,21,3,15,92,16,59,52,88,33,65,54,88,93,43>

#cast %nL

y = (not remainder\2)*~ x
Output:
<36,92,16,52,88,54,88>

Binary predicates

Selection is so frequently useful that the language has a couple of other ways to do it. Selecting according to a binary predicate can be done like this.

z = (not remainder)~| (36,<1,2,3,4,5,6,7,8,9,10,11,12>)

The value of z will be the divisors of 36 appearing in the list.

<1,2,3,4,6,9,12>

This usage has the advantage over writing (not remainder/36)*~ with the operator above that it allows the 36 to be part of the argument rather than being hard coded into the function.

Operator suffixes

Many operators in Ursala allow suffixes that modify their semantics. For example, the suffix ihB on the identity function ~& makes it ~&ihB, a predicate to detect odd numbers by inspecting the binary representation. If an operator with this kind of suffix is further modified by appending an F, it becomes a selection filter. For example

shortcut = ~&ihBF x

using the x defined above will evaluate to

<89,13,15,41,39,21,3,15,59,33,65,93,43>

There are also suffixes corresponding to the ~| operator.

V

[even? dup 2 / >int 2 * - zero?].

[1 2 3 4 5 6 7 8 9] [even?] filter
=[2 4 6 8]

VBA

Option Explicit

Sub Main()
Dim evens() As Long, i As Long
Dim numbers() As Long

    For i = 1 To 100000
        ReDim Preserve numbers(1 To i)
        numbers(i) = i
    Next i

    evens = FilterInNewArray(numbers)

    Debug.Print "Count of initial array : " & UBound(numbers) & ", first item : " & numbers(LBound(numbers)) & ", last item : " & numbers(UBound(numbers))
    Debug.Print "Count of new array : " & UBound(evens) & ", first item : " & evens(LBound(evens)) & ", last item : " & evens(UBound(evens))

    FilterInPlace numbers

    Debug.Print "Count of initial array (filtered): " & UBound(numbers) & ", first item : " & numbers(LBound(numbers)) & ", last item : " & numbers(UBound(numbers))
End Sub

Private Function FilterInNewArray(arr() As Long) As Long()
Dim i As Long, t() As Long, cpt As Long
    For i = LBound(arr) To UBound(arr)
        If IsEven(arr(i)) Then
            cpt = cpt + 1
            ReDim Preserve t(1 To cpt)
            t(cpt) = i
        End If
    Next i
    FilterInNewArray = t
End Function

Private Sub FilterInPlace(arr() As Long)
Dim i As Long, cpt As Long
    For i = LBound(arr) To UBound(arr)
        If IsEven(arr(i)) Then
            cpt = cpt + 1
            arr(cpt) = i
        End If
    Next i
    ReDim Preserve arr(1 To cpt)
End Sub

Private Function IsEven(Number As Long) As Boolean
    IsEven = (CLng(Right(CStr(Number), 1)) And 1) = 0
End Function
Output:
Count of initial array : 100000, first item : 1, last item : 100000
Count of new array : 50000, first item : 2, last item : 100000
Count of initial array (filtered): 50000, first item : 2, last item : 100000

VBScript

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)

WScript.StdOut.Write "Scenario 1: Create a new array"
WScript.StdOut.WriteLine
WScript.StdOut.Write "Input: " & Join(test_arr_1,",")
WScript.StdOut.WriteLine
WScript.StdOut.Write "Output: " & filter_create(test_arr_1)
WScript.StdOut.WriteBlankLines(2)

WScript.StdOut.Write "Scenario 2: Destructive approach"
WScript.StdOut.WriteLine
WScript.StdOut.Write "Input: " & Join(test_arr_2,",")
WScript.StdOut.WriteLine
WScript.StdOut.Write "Output: " & filter_destruct(test_arr_2)
WScript.StdOut.WriteBlankLines(2)

Function filter_create(arr)
	ReDim arr_new(0)
	For i = 0 To UBound(arr)
		If arr(i) Mod 2 = 0 Then
			If arr_new(0) = "" Then
				arr_new(0) = arr(i)
			Else
				ReDim Preserve arr_new(UBound(arr_new)+1)
				arr_new(UBound(arr_new)) = arr(i)
			End If
		End If
	Next
	filter_create = Join(arr_new,",")
End Function

Function filter_destruct(arr)
	count = 0
	For i = 0 To UBound(arr)
		If arr(i) Mod 2 <> 0 Then
			count = count + 1
			For j = i To UBound(arr)
				If j + 1 <= UBound(arr) Then
					arr(j) = arr(j+1)
				End If
			Next
		End If
	Next
	ReDim Preserve arr(UBound(arr)-count)
	filter_destruct = Join(arr,",")
End Function
Output:
Scenario 1: Create a new array
Input: 1,2,3,4,5,6,7,8,9,10
Output: 2,4,6,8,10

Scenario 2: Destructive approach
Input: 1,2,3,4,5,6,7,8,9,10
Output: 2,4,6,8,10

Visual Basic .NET

Works with: Visual Basic .NET version 9.0+
Module Filter

    Sub Main()
        Dim array() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        Dim newEvenArray() As Integer

        Console.WriteLine("Current Array:")
        For Each i As Integer In array
            Console.WriteLine(i)
        Next

        newEvenArray = filterArrayIntoNewArray(array)

        Console.WriteLine("New Filtered Array:")
        For Each i As Integer In newEvenArray
            Console.WriteLine(i)
        Next

        array = changeExistingArray(array)

        Console.WriteLine("Orginal Array After Filtering:")
        For Each i As Integer In array
            Console.WriteLine(i)
        Next
    End Sub

    Private Function changeExistingArray(array() As Integer) As Integer()
        Return filterArrayIntoNewArray(array)
    End Function

    Private Function filterArrayIntoNewArray(array() As Integer) As Integer()
        Dim result As New List(Of Integer)
        For Each element As Integer In array
            If element Mod 2 = 0 Then
                result.Add(element)
            End If
        Next
        Return result.ToArray
    End Function

End Module
Output:
Current Array:
1
2
3
4
5
6
7
8
9
10
New Filtered Array:
2
4
6
8
10
Orginal Array After Filtering:
2
4
6
8
10

V (Vlang)

fn reduce(mut a []int){
    mut last := 0
    for e in a {
        if e % 2 == 0 {
            a[last] = e
            last++
        }
    }
    a = a[..last].clone()
}
fn main() {
    mut nums := [5, 4, 8, 2, 4, 6, 5, 6, 34, 12, 21]
    even := nums.filter(it % 2 == 0)
    println('orig: ${nums}')
    println('even: ${even}')
    reduce(mut nums)
    println('dest: ${nums}')
}
Output:
orig: [5, 4, 8, 2, 4, 6, 5, 6, 34, 12, 21]
even: [4, 8, 2, 4, 6, 6, 34, 12]
dest: [4, 8, 2, 4, 6, 6, 34, 12]

WDTE

let a => import 'arrays';
let s => import 'stream';

a.stream [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
-> s.filter (@ even n => % n 2 -> == 0)
-> s.collect
-- io.writeln io.stdout
;
Output:
[2; 4; 6; 8; 10]

Doing this in a destructive manner is not possible normally in WDTE as everything is immutable.

Wrapl

VAR a <- ALL 1:to(10);

a will be the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

VAR e <- ALL a:values \ $ % 2 = 0;

e will be the list [2, 4, 6, 8, 10]

Wren

var a = [1, 4, 17, 8, -21, 6, -11, -2, 18, 31]
System.print("The original array is       : %(a)")

System.print("\nFiltering to a new array    :-")
var evens = a.where { |e| e%2 == 0 }.toList
System.print("The even numbers are        : %(evens)")
System.print("The original array is still : %(a)")

// Destructive filter, permanently remove even numbers.
evens.clear()
for (i in a.count-1..0) {
    if (a[i]%2 == 0) {
        evens.add(a[i])
        a.removeAt(i)
    }
}
evens = evens[-1..0]
System.print("\nAfter a destructive filter  :-")
System.print("The even numbers are        : %(evens)")
System.print("The original array is now   : %(a)")
Output:
The original array is       : [1, 4, 17, 8, -21, 6, -11, -2, 18, 31]

Filtering to a new array    :-
The even numbers are        : [4, 8, 6, -2, 18]
The original array is still : [1, 4, 17, 8, -21, 6, -11, -2, 18, 31]

After a destructive filter  :-
The even numbers are        : [4, 8, 6, -2, 18]
The original array is now   : [1, 17, -21, -11, 31]

XPL0

This uses the kludge of making the first element of an array its size. There is no 'sizeof' operator, unfortunately.

include c:\cxpl\codes;          \intrinsic 'code' declarations

proc Filter(A, B, Option);      \Select all even numbers from array A
int  A, B, Option;              \ and return them in B, unless Option = true
int  I, J;
[J:= 0;
for I:= 1 to A(0) do
        if (A(I)&1) = 0 then
                [J:= J+1;
                if Option then
                        A(J):= A(I)
                else    B(J):= A(I);
                ];
if Option then A(0):= J else B(0):= J;
];

int Array, Evens(11), I;
[Array:= [10, 3, 1, 4, 1, 5, 9, 2, 6, 5, 4];
Filter(Array, Evens, false);
for I:= 1 to Evens(0) do
        [IntOut(0, Evens(I));  ChOut(0, ^ )];
CrLf(0);

Filter(Array, Evens \not used\, true);
for I:= 1 to Array(0) do
        [IntOut(0, Array(I));  ChOut(0, ^ )];
CrLf(0);
]
Output:
4 2 6 4
4 2 6 4

XQuery

(: Sequence of numbers from 1 to 10 :)
let $array := (1 to 10)

(: Short version :)
let $short := $array[. mod 2 = 0]

(: Long version with a FLWOR expression :)
let $long := for $value in $array
             where $value mod 2 = 0
             return $value

(: Show the results :)
return
  <result>
    <short>{$short}</short>
    <long>{$long}</long>
  </result>
Output:
<?xml version="1.0" encoding="UTF-8"?>
<result>
   <short>2 4 6 8 10</short>
   <long>2 4 6 8 10</long>
</result>

XSLT

<xsl:for-each select="nodes[@value mod 2 = 0]">
  <xsl:value-of select="@value" />
</xsl:for-each>

Z80 Assembly

This example is untested. Please check that it's correct, debug it as necessary, and remove this message.


TestArray_Metadata:
byte 4,4   ;4 rows, 4 columns.
TestArray:
byte 0,1,2,3
byte 4,5,6,7
byte 8,9,10,11
byte 12,13,14,15

OutputArray_Metadata:
byte 2,4
OutputArray:
ds 8,0              ;16 bytes each equaling zero

FilterEvenValues:
ld hl,TestArray_Metadata
ld a,(hl)
inc hl
ld b,(hl)
inc hl               ;LD HL,TestArray
call mul_A_times_B   ;unimplemented multiplication routine, multiplies A by B and returns product in A.
ld b,a               ;we'll use this product as a loop counter.

ld de,OutputArray

loop_filterEvenValues:
ld a,(hl)
ld c,a
rrc c        ;destructively test if odd or even. (That's why it was copied into C first.)
jr c,skipThis
ld (de),a
inc de

skipThis:
inc hl
djnz loop_filterEvenValues

ret   ;return to basic
Output:

There was no code showing the contents of OutputArray to the screen, so here's a hexdump instead:

00 02 04 06 08 0A 0C 0E

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)

ZX Spectrum Basic

10 LET items=100: LET filtered=0
20 DIM a(items)
30 FOR i=1 TO items
40 LET a(i)=INT (RND*items)
50 NEXT i
60 FOR i=1 TO items
70 IF FN m(a(i),2)=0 THEN LET filtered=filtered+1: LET a(filtered)=a(i)
80 NEXT i
90 DIM b(filtered)
100 FOR i=1 TO filtered
110 LET b(i)=a(i): PRINT b(i);" ";
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