Filter: Difference between revisions
→{{header|langur}}
Langurmonkey (talk | contribs) |
Langurmonkey (talk | contribs) |
||
(94 intermediate revisions by 47 users not shown) | |||
Line 3:
;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.
<br><br>
Line 14:
=={{header|11l}}==
<
V even = array.filter(n -> n % 2 == 0)
print(even)</
{{out}}
<pre>
[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>
=={{header|ACL2}}==
<
(cond ((endp xs) nil)
((evenp (first xs))
(cons (first xs) (filter-evens (rest xs))))
(t (filter-evens (rest xs)))))</
=={{header|Action!}}==
<syntaxhighlight lang="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</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Filter.png Screenshot from Atari 8-bit computer]
<pre>
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]
</pre>
=={{header|ActionScript}}==
<
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'''
<
arr = arr.filter(function(item:int, index:int, array:Array) {
return item % 2 == 0;
});
</syntaxhighlight>
=={{header|Ada}}==
<
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
Line 65 ⟶ 351:
end if;
end Evens;
procedure Print(Item : Array_Type) is
begin
Line 73 ⟶ 359:
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:
<
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);
Line 96 ⟶ 382:
return Result (1..Index - 1);
end Evens;
procedure Put (Item : Array_Type) is
begin
Line 106 ⟶ 392:
Put (Evens ((1,2,3,4,5,6,7,8,9,10)));
New_Line;
end Array_Selection;</
=={{header|Aime}}==
<
even(integer e)
{
Line 159 ⟶ 445:
return 0;
}</
{{out}}
<pre> 0 2 4 6 8</pre>
Line 167 ⟶ 453:
{{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}}
<
PROC select = ([]TYPE from, PROC(TYPE)BOOL where)[]TYPE:
BEGIN
FLEX[0]TYPE result;
Line 189 ⟶ 475:
# 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))</
{{out}}
<pre>
+2 +4 +6 +8 +10
+4 +16 +36 +64 +100
</pre>
=={{header|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)<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.
<syntaxhighlight lang="algolw">begin
% sets the elements of out to the elements of in that return true from applying the where procedure to them %
% the bounds of in must be 1 :: inUb - out must be at least as big as in and the number of matching %
% 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.
</syntaxhighlight>
{{out}}
<pre>
2 4 6 8 10
</pre>
=={{header|AmigaE}}==
<
DEF l : PTR TO LONG, r : PTR TO LONG, x
l := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Line 203 ⟶ 525:
SelectList({x}, l, r, `Mod(x,2)=0)
ForAll({x}, r, `WriteF('\d\n', x))
ENDPROC</
=={{header|AntLang}}==
<
{1- x mod 2}hfilter x</
=={{header|Apex}}==
<
Set<Integer> evenIntegers = new Set<Integer>();
for(Integer i : integers)
Line 224 ⟶ 546:
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');</
=={{header|APL}}==
<
2 4 6 8 10 12 14 16 18 20</
=={{header|AppleScript}}==
<
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</
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):
<
set outList to {}
repeat with anItem in inList
Line 256 ⟶ 578:
end script
filter({1,2,3,4,5,6}, isEven)</
Line 268 ⟶ 590:
This allows for context-sensitive filters, which can take account of following or preceding elements in a sequence.
<syntaxhighlight lang="applescript">-------------------------- FILTER --------------------------
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
Line 281 ⟶ 605:
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)
Line 307 ⟶ 632:
end script
end if
end mReturn</
{{Out}}
<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}}==
<
print
{{out}}
<pre>2 4 6 8 10</pre>
=={{header|AutoHotkey}}==
<
loop, parse, array, `,
{
Line 340 ⟶ 822:
even(s) {
loop, parse, s, `,
if !mod(A_LoopField, 2)
r .= "," A_LoopField
return SubStr(r, 2)
Line 355 ⟶ 837:
r := []
For k, v in a
if !mod(v, 2)
r.Insert(v)
return r
Line 363 ⟶ 845:
s_join(o, a) {
Loop, % a.MaxIndex()
r .= o a[A_Index]
return SubStr(r, StrLen(o) + 1)
}
Line 371 ⟶ 853:
</syntaxhighlight>
=={{header|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:'''
<
{{out}}
<pre>4 6 8 2</pre>
'''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
}
</syntaxhighlight>
Same output.
=={{header|Batch File}}==
<
@echo off
setlocal enabledelayedexpansion
Line 453 ⟶ 935:
set /a length+=1
goto lengthloop
</syntaxhighlight>
{{out}}
<pre>
Line 463 ⟶ 945:
numberarray - 2 4 6 8 10
</pre>
=={{header|BBC BASIC}}==
<
items% = 1000
DIM array%(items%)
Line 472 ⟶ 953:
array%(index%) = RND
NEXT
REM Count the number of filtered items:
filtered% = 0
Line 478 ⟶ 959:
IF FNfilter(array%(index%)) filtered% += 1
NEXT
REM Create a new array containing the filtered items:
DIM new%(filtered%)
Line 488 ⟶ 969:
ENDIF
NEXT
REM Alternatively modify the original array:
filtered% = 0
Line 498 ⟶ 979:
NEXT
END
DEF FNfilter(A%) = ((A% AND 1) = 0)</
=={{header|BCPL}}==
<syntaxhighlight lang="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')
$)</syntaxhighlight>
{{out}}
<pre>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</pre>
=={{header|Bracmat}}==
<
& ( 1 2 3 4 5 6 7 8 9 10 16 25 36 49 64 81 100:? (=.!sjt*1/2:/&!odds !sjt:?odds)$() ()
| !odds
)
)
</syntaxhighlight>
<pre>1 3 5 7 9 25 49 81</pre>
=={{header|Brat}}==
<
p 1.to(10).select { x | x % 2 == 0 }</
=={{header|Burlesque}}==
<
blsq ) 1 13r@{2.%n!}f[
{2 4 6 8 10 12}
</syntaxhighlight>
=={{header|BQN}}==
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.
<syntaxhighlight lang="bqn">_filter ← {(𝔽𝕩)/𝕩}
Odd ← 2⊸|
Odd _filter 1‿2‿3‿4‿5</syntaxhighlight>
<syntaxhighlight lang="text">⟨ 1 3 5 ⟩</syntaxhighlight>
=={{header|C}}==
<
#include <stdlib.h>
Line 566 ⟶ 1,101:
return 0;
}</
{{out}}
<pre>Filtered even: 2 4 6 8 10
Line 573 ⟶ 1,108:
=={{header|C sharp|C#}}==
{{works with|.NET|1.1}}
<
ArrayList evens = new ArrayList();
foreach( int i in array )
Line 581 ⟶ 1,116:
}
foreach( int i in evens )
System.Console.WriteLine( i.ToString() );</
{{works with|.NET|2.0}}
<
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|3.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[] evens = array.Where(i => (i % 2) == 0).ToArray();
foreach (int i in evens)
Console.WriteLine(i);</
=={{header|C++}}==
<
#include <algorithm>
#include <functional>
Line 618 ⟶ 1,153:
return 0;
}</
{{works with|C++11}}
<
#include <algorithm>
#include <iterator>
Line 638 ⟶ 1,173:
// print result
copy(evens.begin(), evens.end(), ostream_iterator<int>(cout, "\n"));
}</
=={{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.
<
import StdEnv</
Create a lazy array where each element comes from the list 1 to 10.
<
array = {x \\ x <- [1 .. 10]}</
Create (and print) a strict array where each element (coming from another array) is even.
<
Start = {x \\ x <-: array | isEven x}</
=={{header|Clojure}}==
<
(filter even? (range 0 100))
;; vec will convert any type of seq to an array
(vec (filter even? (vec (range 0 100))))</
=={{header|CoffeeScript}}==
<
{{out}}
Line 675 ⟶ 1,210:
=={{header|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:
<
> (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.
Line 687 ⟶ 1,222:
There is a destructive version that modifies the list in-place:
<
> (2 4 6 8 10)</
=={{header|Cowgol}}==
<syntaxhighlight lang="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();</syntaxhighlight>
{{out}}
<pre>2 4 6 8 10
2 4 6</pre>
=={{header|D}}==
<
import std.algorithm: filter, equal;
Line 697 ⟶ 1,309:
auto evens = data.filter!(x => x % 2 == 0); // Lazy.
assert(evens.equal([2, 4, 6, 8, 10]));
}</
===Tango Version===
{{libheader|Tango}}
<
void main() {
Line 709 ⟶ 1,321:
Stdout("Evens - ")( array[0 .. evens] ).newline; // The order of even elements is preserved
Stdout("Odds - ")( array[evens .. $].sort ).newline; // Unlike odd elements
}</
{{out}}
<pre> Evens - [ 2, 4, 6, 8, 10 ]
Line 715 ⟶ 1,327:
=={{header|Delphi}}==
===Hand-coded version===
<syntaxhighlight lang="delphi">program FilterEven;
{$APPTYPE CONSOLE}
Line 739 ⟶ 1,352:
Write(i:3);
Writeln;
end.</
===
Alternative using Boost.Int[https://github.com/MaiconSoft/DelphiBoostLib]:
{{libheader| System.SysUtils}}
{{libheader| Types}}
{{libheader| Boost.Int}}
<syntaxhighlight lang="delphi">program FilterEven;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Types,
Boost.Int;
var
Source, Destiny: TIntegerDynArray;
begin
// 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.
</syntaxhighlight>
{{out}}
<pre>
[2,4,6,8]
</pre>
=={{header|Dyalect}}==
===Non-destructively===
<
var arr = []
for x in this when pred(x) {
arr.
}
arr
}
var arr = [1..20].
print(arr)</
{{out}}
Line 801 ⟶ 1,423:
===Destructively===
<
var i = 0
while i < this.
if !pred(this[i]) {
this.
}
i += 1
Line 812 ⟶ 1,434:
var arr = [1..20]
arr.
print(arr)</
{{out}}
Line 823 ⟶ 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:
<syntaxhighlight lang="dyalect">var xs = [1..20]
var arr = xs.Iterate().Filter(x => x % 2 == 0).Map(x => x.ToString())
print(arr.ToArray())</syntaxhighlight>
{{out}}
<pre>["2", "4", "6", "8", "10", "12", "14", "16", "18", "20"]</pre>
=={{header|Déjà Vu}}==
===Non-destructively===
<syntaxhighlight lang="dejavu">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 ]</syntaxhighlight>
{{out}}
<pre>[
===Destructively===
<syntaxhighlight lang="dejavu">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</syntaxhighlight>
{{out}}
<pre>[ 0 2 4 6 8 ]</pre>
=={{header|E}}==
Line 847 ⟶ 1,498:
There are several ways this could be done.
<
accum [] for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] { _.with(x) }</
<
for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] {
result with= x
}
result</
<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()</syntaxhighlight>
=={{header|EasyLang}}==
<syntaxhighlight lang="text">
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[]
</syntaxhighlight>
=={{header|EchoLisp}}==
<
(iota 12) → { 0 1 2 3 4 5 6 7 8 9 10 11 }
Line 878 ⟶ 1,541:
→ (0 2 4 6 8 10 12 14 16 18 20 22)
</syntaxhighlight>
=={{header|Ela}}==
Line 885 ⟶ 1,547:
===Using higher-order function (non-strict version)===
<
evenList = filter' (\x -> x % 2 == 0) [1..]</
===Using comprehension (non-strict version)===
<
=={{header|Elena}}==
ELENA
<
import system'math;
import extensions;
import extensions'routines;
public program()
{
auto array := new int[]
var evens := array.filterBy::(n => n.mod
evens.forEach
}</
Using strong typed collections and extensions:
<
import system'routines'stex;
import system'math;
import extensions;
public program()
{
int[] array := new int[]
array
.filterBy::(int n => n.mod
.forEach::(int i){ console.printLine(i) }
}</
{{out}}
<pre>
Line 928 ⟶ 1,591:
=={{header|Elixir}}==
<
[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]</
=={{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}}==
<
EvenNumbers = lists:filter(fun (X) -> X rem 2 == 0 end, Numbers).</
Or using a list comprehension:
<
=={{header|Euphoria}}==
<
s = {1, 2, 3, 4, 5, 6}
evens = {}
Line 952 ⟶ 1,637:
end if
end for
? evens</
{{out}}
Line 959 ⟶ 1,644:
=={{header|F Sharp|F#}}==
<
List.filter (fun x -> x % 2 = 0) lst;;
val it : int list = [2; 4; 6]</
=={{header|Factor}}==
Line 968 ⟶ 1,653:
This code uses ''filter'' on an array.
<
! prints { 0 2 4 6 8 }</
''10 <iota>'' is already a sequence, so we can skip the conversion to array.
<
! prints V{ 0 2 4 5 8 }</
=== Destructive ===
This uses ''filter!'' to modify the original vector.
<
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''.
<
10 <iota> >vector [| v |
v [ even? ] filter drop
Line 993 ⟶ 1,678:
] call
! V{ 0 1 2 3 4 5 6 7 8 9 } after filter
! V{ 0 2 4 6 8 } after filter!</
=={{header|Fantom}}==
<
class Main
{
Line 1,009 ⟶ 1,694:
}
}
</syntaxhighlight>
=={{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}}==
<
cells over + swap do ( dest len test )
i @ over execute if
Line 1,028 ⟶ 1,732:
: even? ( n -- ? ) 1 and 0= ;
evens 0 ' even? nums 6 sel .array \ 2 4 6</
=={{header|Fortran}}==
<
implicit none
contains
Line 1,041 ⟶ 1,744:
iseven = mod(x, 2) == 0
end function iseven
end module funcs</
<
use funcs
implicit none
Line 1,059 ⟶ 1,762:
contains
function filterwith(ar, testfunc)
integer, dimension(:), pointer :: filterwith
Line 1,085 ⟶ 1,788:
end function filterwith
end program Filter</
=={{header|FreeBASIC}}==
<
Type FilterType As Function(As Integer) As Boolean
Function isEven(n As Integer) As Boolean
Return n Mod 2 = 0
End Function
Line 1,106 ⟶ 1,809:
End If
Next
If count > 0 Then Redim Preserve b(0 To count - 1) '' trim excess elements
End Sub
Line 1,122 ⟶ 1,825:
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
Line 1,150 ⟶ 1,853:
End
Data 1, 2, 3, 7, 8, 10, 11, 16, 19, 21, 22, 27</
{{out}}
Line 1,160 ⟶ 1,863:
=={{header|Frink}}==
<
b = array[1 to 100]
c = select[b, {|x| x mod 2 == 0}]
</syntaxhighlight>
=={{header|Futhark}}==
{{incorrect|Futhark|Futhark's syntax has changed, so this example will not compile}}
<syntaxhighlight lang="futhark">
fun main(as: []int): []int =
filter (fn x => x%2 == 0) as
</syntaxhighlight>
=={{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}}==
'''[https://gambas-playground.proko.eu/?gist=e73bc5db1e3bb56c598f89aa669a0825 Click this link to run this code]'''
<
'______________________________________________________________________________________________________
Public Sub Main()
Line 1,217 ⟶ 2,009:
Print sRandom.join(",")
End</
Output:
<pre>
Line 1,226 ⟶ 2,018:
=={{header|GAP}}==
<
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 ]</
=={{header|Go}}==
<
import (
Line 1,277 ⟶ 2,069:
}
*pa = a[:last]
}</
{{out}}
<pre>
Line 1,288 ⟶ 2,080:
=={{header|Groovy}}==
<
=={{header|Haskell}}==
Line 1,294 ⟶ 2,086:
In Haskell, a list is often more basic than an array:
<
evens = [x | x <- ary, even x]</
or
<
To do the same operation on an array, the simplest way it to convert it lazily into a list:
<
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.
=={{header|Icon}} and {{header|Unicon}}==
<
every put(A := [],1 to 10) # make a list of 1..10
Line 1,320 ⟶ 2,112:
procedure iseven(x) #: return x if x is even or fail
if x % 2 = 0 then return x
end</
=={{header|IDL}}==
The <tt>where()</tt> function can select elements on any logical expression. For example
<
=={{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}}==
'''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:
<
'''Examples:'''
<
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) 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 <code>select</code> that filters an array using the verb to its left.
<
isPrime=: 1&p:
Line 1,353 ⟶ 2,156:
43 89 23 2 29 43
(isEven *. isPrime) select v
2</
Destructive example:
<
(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}}==
<
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:
<
return Arrays.stream(input)
.filter(filterMethod)
.toArray(size -> (T[]) Array.newInstance(input.getClass().getComponentType(), size));
}</
Methodcall:
<
Integer[] result = filter(array, i -> (i % 2) == 0);</
Warning: This solution works not with primitive types!<br/>
For arrays with a primitive type use the wrapper class.
=={{header|JavaFX Script}}==
<
def evens = array[n | n mod 2 == 0];</
=={{header|JavaScript}}==
===ES5===
The standard way is to use the [https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/filter Array.prototype.filter] function ({{works with|JavaScript|1.6}}):
<
var evens = arr.filter(function(a) {return a % 2 == 0});</
Other ways:
<
var evens = [];
for (var i=0, ilen=arr.length; i<ilen; i++)
if (arr[i] % 2 == 0)
evens.push(arr[i]);</
{{works with|Firefox|2.0}}
<
var evens = [i for (i in numbers) if (i % 2 == 0)];
Line 1,411 ⟶ 2,233:
}
var evens2 = [i for (i in range(100)) if (i % 2 == 0)];</
{{libheader|Functional}}
<
===ES6===
<
'use strict';
Line 1,426 ⟶ 2,248:
// TEST
return [1,2,3,4,5,6,7,8,9]
.filter(isEven);
// [2, 4, 6, 8]
})();</
{{Out}}
<
=={{header|Joy}}==
<syntaxhighlight lang="joy">[1 2 3 4 5 6 7 8 9 10] [2 rem null] filter.</syntaxhighlight>
=={{header|jq}}==
jq's "select" filter is designed to make it easy to filter both arrays and streams:
<
{{Out}}
2
Line 1,444 ⟶ 2,269:
6
8
<syntaxhighlight lang="jq">
[range(1;10)] | map( select(. % 2 == 0) )
</syntaxhighlight>
{{Out}}
[2,4,6,8]
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
{{out}}
Line 1,458 ⟶ 2,284:
=={{header|K}}==
<
even:{0=x!2}
even 1 2 3 4 5
Line 1,469 ⟶ 2,295:
/ 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[&even x]}</
Destructive:
<
44 88</
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 1,495 ⟶ 2,321:
mutableList.retainAll { it % 2 == 0 }
println(mutableList.joinToString(" "))
}</
{{out}}
Line 1,502 ⟶ 2,328:
2 4 6 8
2 4 6 8
</pre>
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{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
</syntaxhighlight>
=={{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}}==
<
10 iota "2 % not" filter . "\n" .
# [ 0 2 4 6 8 ]</
=={{header|langur}}==
Using the filter() function filters by a function or regex and returns a list of values.
<syntaxhighlight lang="langur">val .list = series 7
writeln " list: ", .list
writeln "filtered: ", filter fn{div 2}, .list
</syntaxhighlight>
{{out}}
<pre>
filtered: [2, 4, 6]</pre>
=={{header|Lasso}}==
<
local(evens = (with item in #original where #item % 2 == 0 select #item) -> asstaticarray)
#evens</
<pre>staticarray(2, 4, 6, 8, 10)</pre>
Modifying the original array
<
with item in #original where #item % 2 != 0 do #original ->removeall(#item)
#original</
<pre>array(2, 4, 6, 8, 10)</pre>
=={{header|Liberty BASIC}}==
<
' to array1 counting matches as we go
dim array1(100)
Line 1,554 ⟶ 2,433:
for n=1 to count
print array2(n)
next</
=={{header|Lisaac}}==
<
a := ARRAY[INTEGER].create_with_capacity 10 lower 0;
b := ARRAY[INTEGER].create_with_capacity 10 lower 0;
Line 1,567 ⟶ 2,446:
b.add_last item;
};
};</
=={{header|Logo}}==
<
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]</
=={{header|Lua}}==
<
local ret = {}
for i, v in ipairs(t) do
Line 1,587 ⟶ 2,467:
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:
<
for i, v in ipairs(t) do
if not func(v) then table.remove(t, i) end
Line 1,601 ⟶ 2,481:
local values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
filter(values, even)
print(unpack(values))</
=={{header|M2000 Interpreter}}==
===Using Filter for arrays===
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Print (1,2,3,4,5,6,7,8)#filter(lambda ->number mod 2=0)
}
Checkit
</syntaxhighlight>
===Old style===
Line 1,623 ⟶ 2,503:
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Function GetEvenNumbers (A as array){
Line 1,635 ⟶ 2,515:
=Array([])
}
Dim A(5), B()
A(0)=10,3,6,7,11
Line 1,641 ⟶ 2,521:
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
Line 1,670 ⟶ 2,550:
A(0)=10,3,6,7,11
Filter2EvenNumbers &A()
Print A() ' 10 6
}
CheckIt
}
CheckIt
</syntaxhighlight>
=={{header|Maple}}==
<syntaxhighlight lang="maple">
evennum:=proc(nums::list(integer))
return select(x->type(x, even), nums);
end proc;
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Check for even integers:
<
gives:
<syntaxhighlight lang
To check also for approximate number (like 8.0 in the example above) a possible solution is:
<
gives:
<
notice that the function returns 8. not 8 (the dot indicates that it is a float number, not an integer).
=={{header|MATLAB}}==
<
evens = list( mod(list,2) == 0 );
end</
{{out}}
<
ans =
0 2 4 6 8 10</
=={{header|Maxima}}==
<
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Line 1,718 ⟶ 2,597:
sublist(a, lambda([n], mod(n, 3) = 0));
[3, 6, 9, 12, 15, 18]</
=={{header|MAXScript}}==
<
newArr = for i in arr where (mod i 2 == 0) collect i</
=={{header|min}}==
{{works with|min|0.19.3}}
<
{{out}}
<pre>
Line 1,734 ⟶ 2,613:
=={{header|MiniScript}}==
We define a ''filter'' method on the list type that returns a new list containing elements filtered by the given function.
<
result = []
for item in self
Line 1,747 ⟶ 2,626:
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.
<
for i in range(self.len-1, 0)
if not f(self[i]) then self.remove i
Line 1,762 ⟶ 2,641:
end function
print nums</
=={{header|ML}}==
==={{header|Standard ML}}===
<
List.filter (fn x => x mod 2 = 0) ary</
==={{header|MLite}}===
MLite is similar to Standard ML, though '=>' becomes '=' and 'List.' is elided:
<
filter (fn x = x mod 2 = 0) ary;</
=={{header|MUMPS}}==
<
;NEW I,J,A,B - Not making new, so we can show the values
;Populate array A
Line 1,780 ⟶ 2,659:
;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:<pre>WRITE
Line 1,803 ⟶ 2,682:
=={{header|Nemerle}}==
Lists have a built-in method for filtering:
<
def filtered = original.Filter(fun(n) {n % 2 == 0});
WriteLine($"$filtered");</
The following would work for arrays:
<
{
def b = $[x | x in a, (f(x))];
b.ToArray()
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
numeric digits 5000
Line 1,831 ⟶ 2,710:
sd1 = Rexx[]
sd2 = Rexx[]
say 'Test data:'
sd1 = makeSampleData(100)
Line 1,877 ⟶ 2,756:
ry = Rexx[] clist.toArray(Rexx[clist.size()])
return ry
</syntaxhighlight>
{{out}}
<pre>
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):
Line 1,894 ⟶ 2,773:
=={{header|NewLISP}}==
<
(2 4 6 8 10)
</syntaxhighlight>
=={{header|NGS}}==
<syntaxhighlight lang="ngs">F even(x:Int) x % 2 == 0
evens = Arr(1...10).filter(even)</syntaxhighlight>
=={{header|Nial}}==
<
=0 2 4 6 8 10</
=={{header|Nim}}==
<
let values =
# 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</syntaxhighlight>
{{out}}
<pre>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]</pre>
=={{header|Objeck}}==
<
use Structure;
Line 1,932 ⟶ 2,834:
}
}
</syntaxhighlight>
=={{header|Objective-C}}==
{{works with|Cocoa|Mac OS X 10.6+}}
<
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:3],
Line 1,942 ⟶ 2,844:
[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|Mac OS X 10.5+}}
<
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:3],
Line 1,951 ⟶ 2,853:
[NSNumber numberWithInt:5], nil];
NSPredicate *isEven = [NSPredicate predicateWithFormat:@"modulus:by:(SELF, 2) == 0"];
NSArray *evens = [numbers filteredArrayUsingPredicate:isEven];</
{{works with|GNUstep}}
<
@interface NSNumber ( ExtFunc )
Line 1,979 ⟶ 2,881:
NSPredicate *isEven = [NSPredicate predicateWithFormat:@"modulo2 == 0"];
NSArray *evens = [numbers filteredArrayUsingPredicate:isEven];
NSLog(@"%@", evens);
Line 1,985 ⟶ 2,887:
[pool release];
return 0;
}</
=={{header|OCaml}}==
It is easier to do it with a list:
<
let even_lst = List.filter (fun x -> x mod 2 = 0) lst</
=={{header|Octave}}==
<
evennums = arr( mod(arr, 2) == 0 );
disp(evennums);</
=={{header|Oforth}}==
<syntaxhighlight lang
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
(filter even? '(1 2 3 4 5 6 7 8 9 10))
</syntaxhighlight>
=={{header|ooRexx}}==
<
a=.array~new
b=.array~new
Line 2,032 ⟶ 2,938:
Say 'Filtered values (destructive filtering):' a~makestring(line,' ')
Exit
filter: Return arg(1)//2=0</
{{out}}
<pre>Unfiltered values: 1412 2244 6778 4002 439 3335 5877 8273 7882 1469
Line 2,040 ⟶ 2,946:
=={{header|Oz}}==
It is easier to do it with a list:
<
Lst = [1 2 3 4 5]
LstEven = {Filter Lst IsEven}</
=={{header|PARI/GP}}==
{{PARI/GP select}}
<
select(iseven, [2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17])</
Or in anonymous form
<
=={{header|Pascal}}==
Line 2,058 ⟶ 2,964:
{{works with|Delphi}}<br>
{{works with|Turbo Pascal}}
<
numbers:array[0..9] of integer = (0,1,2,3,4,5,6,7,8,9);
Line 2,066 ⟶ 2,972:
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().
Line 2,072 ⟶ 2,978:
=={{header|Peloton}}==
Fixed length English dialect
<
<@ DEFLST>evens</@>
<@ ENULSTLIT>numbers|
Line 2,079 ⟶ 2,985:
<@ LETLSTELTLST>evens|...</@>
</@>
</@></
=={{header|Perl}}==
<
my @even = grep { $_%2 == 0 } @a;</
=={{header|Phix}}==
{{libheader|Phix/basics}}
===basic task===
<!--<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;">return</span> <span style="color: #7060A8;">remainder<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">2<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?<span style="color: #7060A8;">filter<span style="color: #0000FF;">(<span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">10<span style="color: #0000FF;">)<span style="color: #0000FF;">,<span style="color: #000000;">even<span style="color: #0000FF;">)
<!--</syntaxhighlight>-->
{{out}}
<pre>
{2,4,6,8,10}
</pre>
===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.
<!--<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;">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;">procedure</span> <span style="color: #000000;">main<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">10<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span>
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">filter<span style="color: #0000FF;">(<span style="color: #000000;">s<span style="color: #0000FF;">,<span style="color: #000000;">even<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- copy-on-write here...</span>
<span style="color: #0000FF;">?<span style="color: #000000;">s</span> <span style="color: #000080;font-style:italic;">-- still all 10</span>
<span style="color: #0000FF;">?<span style="color: #000000;">t</span> <span style="color: #000080;font-style:italic;">-- 5</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">filter<span style="color: #0000FF;">(<span style="color: #000000;">s<span style="color: #0000FF;">,<span style="color: #000000;">even<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- ...but automatic pass by reference occurs here</span>
<span style="color: #0000FF;">?<span style="color: #000000;">s</span> <span style="color: #000080;font-style:italic;">-- 5</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;">)
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,148 ⟶ 3,029:
{2,4,6,8,10}
</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
<!--<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: #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: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length<span style="color: #0000FF;">(<span style="color: #000000;">a<span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">fn<span style="color: #0000FF;">(<span style="color: #000000;">a<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]<span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append<span style="color: #0000FF;">(<span style="color: #000000;">res<span style="color: #0000FF;">,<span style="color: #000000;">a<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]<span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function
<!--</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:
<!--<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: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length<span style="color: #0000FF;">(<span style="color: #000000;">a<span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">fn<span style="color: #0000FF;">(<span style="color: #000000;">a<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]<span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">l</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">a<span style="color: #0000FF;">[<span style="color: #000000;">l<span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">a<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">a<span style="color: #0000FF;">[<span style="color: #000000;">1<span style="color: #0000FF;">..<span style="color: #000000;">l<span style="color: #0000FF;">]</span> <span style="color: #000080;font-style:italic;">-- (can occur in situ)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">10<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span>
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">lhd_filter<span style="color: #0000FF;">(<span style="color: #000000;">s<span style="color: #0000FF;">,<span style="color: #000000;">even<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- copy on write here...</span>
<span style="color: #0000FF;">?<span style="color: #000000;">s</span> <span style="color: #000080;font-style:italic;">-- still all 10</span>
<span style="color: #0000FF;">?<span style="color: #000000;">t</span> <span style="color: #000080;font-style:italic;">-- 5</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">lhd_filter<span style="color: #0000FF;">(<span style="color: #000000;">s<span style="color: #0000FF;">,<span style="color: #000000;">even<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- ...but automatic pass by reference occurs here</span>
<span style="color: #0000FF;">?<span style="color: #000000;">s</span> <span style="color: #000080;font-style:italic;">-- 5</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;">)
<!--</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.
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.
=={{header|PHL}}==
<
extern printf;
Line 2,175 ⟶ 3,081:
var evens = arr.filter(#(i) i % 2 == 0);
printf("%s\n", evens::str);
return 0;
]</
=={{header|PHP}}==
Using a standard loop
<
$evens = array();
foreach ($arr as $val){
if ($val % 2 == 0) $evens[] = $val);
}
print_r($evens);</
Using a filter function
<
$arr = range(1,5);
$evens = array_filter($arr, "is_even");
print_r($evens);</
=={{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}}==
<
(1 2 3 4 5 6 7 8 9) )</
{{out}}
<pre>-> (2 4 6 8)</pre>
=={{header|PL/I}}==
<
filter_values: procedure options (main); /* 15 November 2013 */
declare a(20) fixed, b(*) fixed controlled;
Line 2,228 ⟶ 3,150:
end filter;
end filter_values;</
Results:
<pre>
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
</pre>
Line 2,241 ⟶ 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:
<
;;; satisfying pred
define filter_array(ar, pred);
Line 2,255 ⟶ 3,177:
;;; Use it
filter_array({1, 2, 3, 4, 5},
procedure(x); not(testbit(x, 0)); endprocedure) =></
=={{header|PostScript}}==
{{libheader|initlib}}
<
[1 2 3 4 5 6 7 8 9 10] {2 mod 0 eq} find
</syntaxhighlight>
=={{header|PowerShell}}==
<
$array | Where-Object { $_ % 2 -eq 0 }</
=={{header|Prolog}}==
===findall===
<
Usage:
<
E = [2, 4, 6, 8, 10]</
===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
<
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 <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
<
%% filter(Pred, LstIn, LstOut)
Line 2,295 ⟶ 3,217:
filter(Pred, T, L1),
( call(Pred,H) -> L = [H|L1]; L = L1).
</syntaxhighlight>
Usage :
<
L = [2,4,6,8] .
</syntaxhighlight>
=={{header|PureBasic}}==
<
Dim Evens.i(0)
Line 2,328 ⟶ 3,250:
For i=0 To ArraySize(Evens())
Print(Str(Evens(i))+" ")
Next</
{{out}}
List of Randoms
32 35 89 91 11 33 12 22 42 43
List of Even(s)
32 12 22 42
Line 2,340 ⟶ 3,262:
{{works with|Python|2.4}}
<
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:
<
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.
Line 2,357 ⟶ 3,279:
One can also assign to a slice (of a list or other mutable indexed object. Thus the following:
<
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|3}}
<
from functools import (reduce)
Line 2,459 ⟶ 3,381:
if __name__ == '__main__':
main()</
{{Out}}
<pre>By descending generality and increasing brevity:
Line 2,467 ⟶ 3,389:
(x for x in xs if even(x)) -> [0, 2, 4, 6, 8, 10]
filter(even, xs) -> [0, 2, 4, 6, 8, 10]</pre>
=={{header|Quackery}}==
<syntaxhighlight lang="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</syntaxhighlight>
{{out}}
<pre>Ten arbitrary digits: [ 1 6 1 2 2 1 8 5 5 4 ]
Only the even digits: [ 6 2 2 8 4 ]</pre>
===Destructively===
<syntaxhighlight lang="quackery"> [ ]'[ 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</syntaxhighlight>
{{out}}
<pre>Ten shuffled digits: [ 5 6 8 2 1 4 0 3 9 7 ]
Less the odd digits: [ 6 8 2 4 0 ]</pre>
=={{header|Q}}==
<
=={{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}}==
<
evennums <- a[ a%%2 == 0 ]
print(evennums)</
=={{header|Racket}}==
The classic way:
<syntaxhighlight lang="racket">
-> (filter even? '(0 1 2 3 4 5 6 7 8 9))
'(0 2 4 6 8)
</syntaxhighlight>
getting the list of non-evens too:
<syntaxhighlight lang="racket">
-> (partition even? '(0 1 2 3 4 5 6 7 8 9))
'(0 2 4 6 8)
'(1 3 5 7 9)
</syntaxhighlight>
Finally, using a for loop, similar to list comprehension:
<syntaxhighlight lang="racket">
-> (for/list ([x '(0 1 2 3 4 5 6 7 8 9)] #:when (even? x)) x)
'(0 2 4 6 8)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
<syntaxhighlight lang="raku" line>my @a = 1..6;
my @even = grep * %% 2, @a;</syntaxhighlight>
Alternatively:
<syntaxhighlight lang="raku" line>my @a = 1..6;
my @even = @a.grep(* %% 2);</syntaxhighlight>
Destructive:
<syntaxhighlight lang="raku" line>my @a = 1..6;
@a .= grep(* %% 2);</syntaxhighlight>
=={{header|Raven}}==
<
group nums each
dup 1 & if drop
list as evens</
=={{header|REBOL}}==
<
evens: [] repeat element a [if even? element [append evens element]]
print mold evens</
{{out}}
<pre>[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]</pre>
=={{header|Red}}==
<
orig: [] repeat i 10 [append orig i]
?? orig
Line 2,522 ⟶ 3,705:
remove-each ele orig [odd? ele] ;; destructive
?? orig
</syntaxhighlight>
{{out}}
<pre>orig: [1 2 3 4 5 6 7 8 9 10]
cpy: [2 4 6 8 10]
orig: [2 4 6 8 10]
>>
</pre>
=={{header|REXX}}==
===using two arrays===
This example uses two arrays. The '''random''' BIF is used to generate the numbers.
<
If datatype(seed,'W') Then
End
End
End </syntaxhighlight>
{{out|output|text= when using the input of: <tt> , 12345 </tt>}}
The '''12345''' is the '''random''' BIF ''seed'' so that the random numbers can be repeated when re-running the REXX program.
<pre>
new.1 = 17520
Line 2,586 ⟶ 3,762:
new.23 = 44360
</pre>
===Using a control array===
<syntaxhighlight lang="rexx">
Call random,,seed /* use RANDOM seed for repeatability*/
End
If
even.j=1 /* turn on the even bit */
End
If even.k Then
End</syntaxhighlight>
<pre>
x.3 = 52754
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===
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
<
Call random,,seed /* use RANDOM seed for repeatability*/
End
Do j=1 To n /* process the elements of x.* */
If
Drop
End
Do k=1 To n /* display all the numbers */
If
Say right('x.'k,20) '=' right(x.k,9)
End</syntaxhighlight>
For the following input: <tt> 20 12345 </tt>
=={{header|Ring}}==
<syntaxhighlight lang="text">
aList = [1, 2, 3, 4, 5, 6]
bArray = list(3)
Line 2,640 ⟶ 3,822:
func evenSelect aArray
i = 0
for n = 1 to len(aArray)
if (aArray[n] % 2) = 0
i = i + 1
Line 2,647 ⟶ 3,829:
next
return bArray
</syntaxhighlight>
=={{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}}==
Enumerable#select is the filter that returns a new Array.
<
ary = [1, 2, 3, 4, 5, 6]
even_ary = ary.select {|elem| elem.even?}
Line 2,660 ⟶ 3,883:
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.select! {|elem| elem.even?}
p ary # => [2, 4, 6]</
Shorthand:
<syntaxhighlight lang="ruby">ary = [1, 2, 3, 4, 5, 6]
ary.select!(&:even?)
p ary # => [2, 4, 6]</syntaxhighlight>
=={{header|Run BASIC}}==
<
count = 100
for i = 1 to 100
Line 2,676 ⟶ 3,905:
count = count - (a1(i) mod 2)
next
'dim the extract and fill it
dim a2(count)
Line 2,685 ⟶ 3,914:
end if
next
for i = 1 to count
print a2(i)
next</
=={{header|Rust}}==
<
println!("new vec filtered: ");
let nums: Vec<i32> = (1..20).collect();
Line 2,702 ⟶ 3,931:
nums.retain(|x| x % 2 == 0);
println!("{:?}", nums);
}</
{{out}}
Line 2,715 ⟶ 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.
<
x!;</
Here's a version that walks an array destructively removing the non-even elements:
<
variable write_position := 0;
iterate (read_position; [0...9])
Line 2,734 ⟶ 3,963:
my_array := my_array[0...write_position - 1];
iterate(x; my_array)
x!;</
=={{header|Sather}}==
<
include ARRAY{T};
Line 2,759 ⟶ 3,988:
#OUT + "\n";
end;
end;</
=={{header|Scala}}==
<
=={{header|Scheme}}==
Filter function definition:
<syntaxhighlight lang="scheme">
(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)))))))
</syntaxhighlight>
Usage in the interactive prompt:
<syntaxhighlight lang="scheme">> (filter even? '(1 2 3 4 5 6 7 8 9 10))
(2 4 6 8 10)</syntaxhighlight>
Or as a function:
<
(filter even? lst))
(select-even '(1 2 3 4 5 6 7 8 9 10))</
=={{header|Seed7}}==
<
var array integer: evens is 0 times 0;
var integer: number is 0;
Line 2,784 ⟶ 4,025:
evens &:= [] (number);
end if;
end for;</
=={{header|SequenceL}}==
Filters are primarily written in SequenceL using partial Indexed Functions.<br>
<
{{out}}
Line 2,806 ⟶ 4,036:
[2,4]
</pre>
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">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]</syntaxhighlight>
=={{header|Slate}}==
<
=={{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}}==
Creates a new array:
<syntaxhighlight lang="smalltalk">#(1 2 3 4 5) select: [:number | number even]</syntaxhighlight>
or for short:
<syntaxhighlight lang="smalltalk">#(1 2 3 4 5) select:#even</syntaxhighlight>
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.
=={{header|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 table #nos (v int)
declare @n int set @n=1
Line 2,830 ⟶ 4,094:
-- Clean up so you can edit and repeat:
drop table #nos
drop table #evens</
'{{works with|MySQL}}
<
insert into nos values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
create temporary table evens (v int);
Line 2,839 ⟶ 4,103:
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 :
<
=={{header|Stata}}==
<
a=2,9,4,7,5,3,6,1,8
Line 2,853 ⟶ 4,117:
// Select the indices of even elements of a
selectindex(mod(a,2):==0)
end</
=={{header|Swift}}==
<
let even_numbers = numbers.filter { $0 % 2 == 0 }
println(even_numbers)</
{{out}}
<pre>
[2, 4, 6]
</pre>
=={{header|Tcl}}==
<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}]</syntaxhighlight>
{{out}}
<pre>56 62 76 82 94 28 90 52 44</pre>
<br>
Inplace way, quite the inefficient contraption compared to mapping:
<syntaxhighlight lang="tcl">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</syntaxhighlight>
{{out}}
<pre>56 62 76 82 94 28 90 52 44</pre>
Explanation: https://wiki.tcl-lang.org/page/lreplace, section "Performance: Modifying a List In-Place"<br>
Proof by timing removal of the end element of lists of different lengths:
<syntaxhighlight lang="tcl">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}]"
}</syntaxhighlight>
{{out}}
<pre>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</pre>
=={{header|Toka}}==
<
10 cells is-array even
{
Line 2,887 ⟶ 4,194:
[ 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
Line 2,893 ⟶ 4,200:
} is copy-even
10 0 [ i i table array.put ] countedLoop
table 10 copy-even</
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
arr="1'4'9'16'25'36'49'64'81'100",even=""
Line 2,904 ⟶ 4,211:
ENDLOOP
PRINT even
</syntaxhighlight>
{{out}}
<pre>
Line 2,913 ⟶ 4,220:
{{works with|Bash}}
<
unset e[@]
for ((i=0;i<${#a[@]};i++)); do
[ $((a[$i]%2)) -eq 0 ] && e[$i]="${a[$i]}"
done</
Or, using '''grep''':
<
read -a e -d\n < <(printf '%s\n' "${a[@]}" | grep '[02468]$')</
Either way, to display the results:
<
echo "${e[@]}"</
{{out}}
Line 2,934 ⟶ 4,241:
=={{header|UnixPipes}}==
<
=={{header|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.
Line 2,948 ⟶ 4,255:
predicate <code>p</code> is to write <code>p*~</code>, as shown below.
<
#import nat
Line 2,955 ⟶ 4,262:
#cast %nL
y = (not remainder\2)*~ x</
{{out}}
Line 2,967 ⟶ 4,274:
of other ways to do it.
Selecting according to a binary predicate can be done like this.
<
The value of <code>z</code> will be the divisors of 36 appearing in the list.
<pre>
Line 2,984 ⟶ 4,291:
modified by appending an <code>F</code>, it becomes a selection filter.
For example
<
using the <code>x</code> defined above will evaluate to
<pre>
Line 2,992 ⟶ 4,299:
=={{header|V}}==
<
[1 2 3 4 5 6 7 8 9] [even?] filter
=[2 4 6 8]</
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 3,004 ⟶ 4,311:
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
Line 3,045 ⟶ 4,352:
Private Function IsEven(Number As Long) As Boolean
IsEven = (CLng(Right(CStr(Number), 1)) And 1) = 0
End Function</
{{Out}}
Line 3,051 ⟶ 4,358:
Count of new array : 50000, first item : 2, last item : 100000
Count of initial array (filtered): 50000, first item : 2, last item : 100000</pre>
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
test_arr_1 = Array(1,2,3,4,5,6,7,8,9,10)
test_arr_2 = Array(1,2,3,4,5,6,7,8,9,10)
Line 3,101 ⟶ 4,407:
ReDim Preserve arr(UBound(arr)-count)
filter_destruct = Join(arr,",")
End Function</
{{Out}}
Line 3,116 ⟶ 4,422:
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
<
Sub Main()
Line 3,157 ⟶ 4,463:
End Module
</syntaxhighlight>
{{out}}
Line 3,184 ⟶ 4,490:
8
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>
=={{header|WDTE}}==
<
let s => import 'stream';
Line 3,194 ⟶ 4,528:
-> s.collect
-- io.writeln io.stdout
;</
{{out}}
Line 3,202 ⟶ 4,536:
=={{header|Wrapl}}==
<
<tt>a</tt> will be the list <tt>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</tt>
<
<tt>e</tt> will be the list <tt>[2, 4, 6, 8, 10]</tt>
=={{header|Wren}}==
<syntaxhighlight lang="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)")</syntaxhighlight>
{{out}}
<pre>
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]
</pre>
=={{header|XPL0}}==
Line 3,211 ⟶ 4,580:
There is no 'sizeof' operator, unfortunately.
<
proc Filter(A, B, Option); \Select all even numbers from array A
Line 3,238 ⟶ 4,607:
[IntOut(0, Array(I)); ChOut(0, ^ )];
CrLf(0);
]</
{{out}}
<pre>
4 2 6 4
4 2 6 4
</pre>
=={{header|XQuery}}==
<
(: Sequence of numbers from 1 to 10 :)
let $array := (1 to 10)
Line 3,265 ⟶ 4,634:
<long>{$long}</long>
</result>
</syntaxhighlight>
{{out}}
<
<?xml version="1.0" encoding="UTF-8"?>
<result>
Line 3,274 ⟶ 4,643:
<long>2 4 6 8 10</long>
</result>
</syntaxhighlight>
=={{header|XSLT}}==
<
<xsl:value-of select="@value" />
</xsl:for-each></
=={{header|Z80 Assembly}}==
{{untested}}
<syntaxhighlight lang="z80">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</syntaxhighlight>
{{out}}
There was no code showing the contents of OutputArray to the screen, so here's a hexdump instead:
<pre>
00 02 04 06 08 0A 0C 0E
</pre>
=={{header|zkl}}==
<
.filter(fcn(n){(0).isType(n) and n.isOdd})
//-->L(1,9,25,49,81)</
=={{header|ZX Spectrum Basic}}==
<
20 DIM a(items)
30 FOR i=1 TO items
Line 3,300 ⟶ 4,715:
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</
|