Filter
Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array.
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
ActionScript
<lang actionscript>var arr:Array = new Array(1, 2, 3, 4, 5); var evens:Array = new Array(); for (var i:int = 0; i < arr.length(); i++) {
if (arr[i] % 2 == 0) evens.push(arr[i]);
}</lang>
Ada
<lang 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;</lang> Here is a non-recursive solution: <lang ada>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;</lang>
ALGOL 68
<lang algol68>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))</lang> Output:
+2 +4 +6 +8 +10 +4 +16 +36 +64 +100
AmigaE
<lang amigae>PROC main()
DEF l : PTR TO LONG, r : PTR TO LONG, x l := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] r := List(ListLen(l)) SelectList({x}, l, r, `Mod(x,2)=0) ForAll({x}, r, `WriteF('\d\n', x))
ENDPROC</lang>
AppleScript
<lang applescript>set array to {1, 2, 3, 4, 5, 6} set evens to {} repeat with i in array if (i mod 2 = 0) then set end of evens to i's contents end repeat
return evens</lang>Result is (a list):
{2, 4, 6}
Here's a more generic version with the same result:
<lang AppleScript>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)</lang>
AutoHotkey
<lang 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)
}</lang>
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. <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}' 4 6 8 2</lang>
BBC BASIC
<lang bbcbasic> 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)</lang>
Brat
<lang brat>#Prints [2, 4, 6, 8, 10] p 1.to(10).select { x | x % 2 == 0 }</lang>
C
<lang 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;
}</lang>output
Filtered even: 2 4 6 8 10 In-place filtered not multiple of 3: 1 2 4 5 7 8 10
C#
<lang csharp>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() );</lang>
<lang csharp>List<int> array = new List<int>( new int[] { 1, 2, 3, 4, 5 } ); List<int> evens = array.FindAll( delegate( int i ) { return (i%2)==0; } ); foreach( int i in evens )
System.Console.WriteLine( i.ToString() );</lang>
<lang csharp>IEnumerable<int> array = new List<int>( new int[] { 1, 2, 3, 4, 5 } ); IEnumerable<int> evens = array.Where( delegate( int i ) { return (i%2)==0; } ); foreach( int i in evens )
System.Console.WriteLine( i.ToString() );</lang>
Replacing the delegate with the more concise lambda expression syntax. <lang csharp>int[] array = { 1, 2, 3, 4, 5 }; int[] evens = array.Where(i => (i % 2) == 0).ToArray();
foreach (int i in evens)
Console.WriteLine(i);</lang>
C++
<lang cpp>#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;
}</lang>
Using new features of C++0x:
<lang cpp>#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"));
}</lang>
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.
<lang clean>module SelectFromArray
import StdEnv</lang>
Create a lazy array where each element comes from the list 1 to 10.
<lang clean>array :: {Int} array = {x \\ x <- [1 .. 10]}</lang>
Create (and print) a strict array where each element (coming from another array) is even.
<lang clean>Start :: {!Int} Start = {x \\ x <-: array | isEven x}</lang>
Clojure
<lang lisp>;; range and filter create lazy seq's (filter even? (range 0 100))
- vec will convert any type of seq to an array
(vec (filter even? (vec (range 0 100))))</lang>
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:
<lang lisp>(remove-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10)) > (2 4 6 8 10)</lang>
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:
<lang lisp>(delete-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10)) > (2 4 6 8 10)</lang>
D
<lang d>import std.algorithm;
void main() {
auto array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
auto evens = filter!q{a % 2 == 0}(array); // lazy
assert(equal(evens, [2, 4, 6, 8, 10]));
}</lang>
<lang d>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
}</lang> Output:
Evens - [ 2, 4, 6, 8, 10 ] Odds - [ 1, 3, 5, 7, 9 ]
Delphi
<lang Delphi>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.</lang>
E
There are several ways this could be done.
<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>
<lang e>var result := [] for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] {
result with= x
} result</lang>
<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>
Ela
Using higher-order function (non-strict version)
<lang ela>open Core
let evenList = filter' (\x -> x % 2 == 0) [1..]</lang>
Using comprehension (non-strict version)
<lang ela>let evenList = [& x \\ x <- [1..] | x % 2 == 0]</lang>
Erlang
<lang erlang>Numbers = lists:seq(1, 5). EvenNumbers = lists:filter(fun (X) -> X rem 2 == 0 end, Numbers).</lang>
Or using a list comprehension:
<lang erlang>EvenNumbers = [X || X <- Numbers, X rem 2 == 0].</lang>
Euphoria
<lang 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</lang>
Output:
{2,4,6}
F#
<lang fsharp>let evenList = List.filter (fun i -> i%2 = 0 ) let evenList2 = fun list -> [for i in list do if i%2=0 then yield i] let evenArray = Array.filter (fun i -> i%2 = 0 ) let evenSeq = fun list -> seq { for i in list do if i%2=0 then yield i}</lang>
Factor
This code uses filter on an array.
<lang factor>10 iota >array [ even? ] filter . ! prints { 0 2 4 6 8 }</lang>
10 iota is already a sequence, so we can skip the conversion to array.
<lang factor>10 iota [ even? ] filter . ! prints V{ 0 2 4 5 8 }</lang>
Destructive
This uses filter! to modify the original vector.
<lang factor>USE: vectors 10 iota >vector [ even? ] filter! . ! prints V{ 0 2 4 5 8 }</lang>
To prove that filter! is destructive but filter is non-destructive, I assign the original vector to v.
<lang factor>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!</lang>
Forth
<lang 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</lang>
Fortran
<lang 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</lang>
<lang fortran>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</lang>
GAP
<lang 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 ]</lang>
Go
<lang go>package main
import (
"fmt" "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]
}</lang> 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
<lang groovy> def evens = [1, 2, 3, 4, 5].findAll{it % 2 == 0}</lang>
Haskell
In Haskell, a list is often more basic than an array:
<lang haskell>ary = [1..10] evens = [x | x <- ary, even x]</lang> or <lang haskell>evens = filter even ary</lang>
To do the same operation on an array, the simplest way it to convert it lazily into a list:
<lang haskell>import Data.Array
ary = listArray (1,10) [1..10] evens = listArray (1,n) l where
n = length l l = [x | x <- elems ary, even x]</lang>
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
<lang Icon>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</lang>
IDL
The where() function can select elements on any logical expression. For example
<lang idl>result = array[where(NOT array AND 1)]</lang>
J
Solution:
With any verb (function) f
that returns a boolean for each element of a vector v
, the following is the generic solution:
<lang j> (#~ f) v</lang>
Examples: <lang j> ] v=: 20 ?@$ 100 NB. vector of 20 random integers between 0 and 99 63 92 51 92 39 15 43 89 36 69 40 16 23 2 29 91 57 43 55 22
v #~ -.2| v
92 92 36 40 16 2 22</lang>
Or using the generic form suggested above: <lang j> isEven=: 0 = 2&| NB. verb testing for even numbers
(#~ isEven) v
92 92 36 40 16 2 22</lang>
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.
<lang j> 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</lang>
Destructive example:
<lang j> v=: isEven select v</lang>
(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.)
Java
<lang java>int[] array = {1, 2, 3, 4, 5 }; List<Integer> evensList = new ArrayList<Integer>(); for (int i: array) {
if (i % 2 == 0) evensList.add(i);
} int[] evens = evensList.toArray(new int[0]);</lang>
JavaFX Script
<lang javafx>def array = [1..100]; def evens = array[n | n mod 2 == 0];</lang>
JavaScript
The standard way is to use the Array.prototype.filter function (
):
<lang javascript>var arr = [1,2,3,4,5]; var evens = arr.filter(function(a) {return a % 2 == 0});</lang>
Other ways: <lang javascript>var arr = [1,2,3,4,5]; var evens = []; for (var i=0, ilen=arr.length; i<ilen; i++)
if (arr[i] % 2 == 0) evens.push(arr[i]);</lang>
<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)];
function range(limit) {
for(var i = 0; i < limit; i++) { yield i; }
}
var evens2 = [i for (i in range(100)) if (i % 2 == 0)];</lang>
<lang javascript>Functional.select("+1&1", [1,2,3,4]) // [2, 4]</lang>
Liberty BASIC
<lang lb>' 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</lang>
Lisaac
<lang 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; };
};</lang>
Logo
<lang logo>to even? :n
output equal? 0 modulo :n 2
end show filter "even? [1 2 3 4] ; [2 4]
show filter [equal? 0 modulo ? 2] [1 2 3 4]</lang>
Lua
<lang 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)))</lang>
Mathematica
Check for even integers: <lang Mathematica>Select[{4, 5, Pi, 2, 1.3, 7, 6, 8.0}, EvenQ]</lang> gives: <lang Mathematica>{4, 2, 6}</lang> 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> gives: <lang Mathematica>{4, 2, 6, 8.}</lang> notice that the function returns 8. not 8 (the dot indicates that it is a float number, not an integer).
MATLAB
<lang MATLAB>function evens = selectEvenNumbers(list)
evens = list( mod(list,2) == 0 );
end</lang>
Sample Output: <lang MATLAB>>> selectEvenNumbers([0 1 2 3 4 5 6 7 8 9 10])
ans =
0 2 4 6 8 10</lang>
MAXScript
<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>
MUMPS
<lang 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</lang>
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: <lang Nemerle>def original = $[1 .. 100]; def filtered = original.Filter(fun(n) {n % 2 == 0}); WriteLine($"$filtered");</lang> The following would work for arrays: <lang Nemerle>Filter[T] (a : array[T], f : T -> bool) : array[T] {
def b = $[x | x in a, (f(x))]; b.ToArray()
}</lang>
NewLISP
<lang NewLISP>> (filter (fn (x) (= (% x 2) 0)) '(1 2 3 4 5 6 7 8 9 10)) (2 4 6 8 10) </lang>
Nial
<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>
Objeck
<lang 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; } }
} </lang>
Objective-C
<lang objc>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; } ]];</lang>
<lang objc>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];</lang>
<lang objc>#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;
}</lang>
OCaml
It is easier to do it with a list: <lang ocaml>let lst = [1;2;3;4;5;6] let even_lst = List.filter (fun x -> x mod 2 = 0) lst</lang>
Octave
<lang octave>arr = [1:100]; evennums = arr( mod(arr, 2) == 0 ); disp(evennums);</lang>
Oz
It is easier to do it with a list: <lang oz>declare Lst = [1 2 3 4 5] LstEven = {Filter Lst IsEven}</lang>
PARI/GP
<lang parigp>selecteven(v)=vecextract(v,1<<(#v\2*2+1)\3);</lang>
Pascal
Arrays are supported in all versions of pascal so this simple example will cover the entire gamut.
<lang 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.');</lang>
The odd() function is a standard library function of pascal as is the function even().
Perl
<lang perl>my @a = (1, 2, 3, 4, 5, 6); my @even = grep { $_%2 == 0 } @a;</lang>
Perl 6
<lang perl6>my @a = 1, 2, 3, 4, 5, 6; my @even = grep * %% 2, @a;</lang>
Alternatively:
<lang perl6>my @even = @a.grep(* %% 2);</lang>
PHP
Using a standard loop <lang php>$arr = range(1,5); $evens = array(); foreach ($arr as $val){
if ($val % 2 == 0) $evens[] = $val);
} print_r($evens);</lang>
Using a filter function <lang php>function is_even($var) { return(!($var & 1)); } $arr = range(1,5); $evens = array_filter($arr, "is_even"); print_r($evens);</lang>
PicoLisp
<lang PicoLisp>(filter '((N) (not (bit? 1 N)))
(1 2 3 4 5 6 7 8 9) )</lang>
Output:
-> (2 4 6 8)
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:
<lang pop11>;;; 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) =></lang>
PostScript
<lang postscript> [1 2 3 4 5 6 7 8 9 10] {2 mod 0 eq} find </lang>
PowerShell
<lang powershell>$array = -15..37 $array | Where-Object { $_ % 2 -eq 0 }</lang>
Prolog
findall
<lang prolog>evens(D, Es) :- findall(E, (member(E, D), E mod 2 =:= 0), Es).</lang>
Usage:
<lang prolog>?- evens([1,2,3,4,5,6,7,8,9,10],E). E = [2, 4, 6, 8, 10]</lang>
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 <lang Prolog>?- use_module(library(lambda)). true.
?- include((\X^(X mod 2 =:= 0)), [1,2,3,4,5,6,7,8,9], L). L = [2,4,6,8].</lang>
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 <lang prolog>:- 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). </lang> Usage : <lang prolog> ?- filter(\X^(X mod 2 =:= 0), [1,2,3,4,5,6,7,8,9], L). L = [2,4,6,8] . </lang>
Protium
Fixed length English dialect <lang html><@ LETCNWLSTLIT>numbers|1 2 3 4 5 6 7 8 9 10 11 12</@> <@ DEFLST>evens</@> <@ ENULSTLIT>numbers| <@ TSTEVEELTLST>...</@> <@ IFF> <@ LETLSTELTLST>evens|...</@> </@> </@></lang>
PureBasic
<lang 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</lang>
Output can look like
List of Randoms 32 35 89 91 11 33 12 22 42 43 List of Even(s) 32 12 22 42
Python
<lang python>values = range(10) evens = [x for x in values if not x & 1] ievens = (x for x in values if not x & 1) # lazy
- alternately but less idiomatic:
evens = filter(lambda x: not x & 1, values)</lang>
Alternative using the slice syntax with its optional "stride" expression:
<lang python>values = range(10) evens = values[::2]</lang>
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:
<lang python>values = range(10) values[::2] = [11,13,15,17,19] print values 11, 1, 13, 3, 15, 5, 17, 7, 19, 9</lang>
R
<lang R>a <- 1:100 evennums <- a[ a%%2 == 0 ] print(evennums)</lang>
Raven
<lang raven>[ 0 1 2 3 4 5 6 7 8 9 ] as nums group nums each
dup 1 & if drop
list as evens</lang>
REBOL
<lang 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</lang>
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]
REXX
This example shows that array element indexes may be negative and the array bounds need not be declared. <lang rexx> /*REXX program selects all even numbers from an array ==> a new array. */ numeric digits 210000 /*handle past 1m for Fibonacci.*/ old.= /*the OLD array, all null so far.*/ new.= /*the NEW array, all null so far.*/
do j=-40 to 40; old.j=fib(j); end /*put 81 Fibonacci numbs ==> OLD */
news=0 /*numb. of elements in NEW so far*/
/*══════════════════════════════════════════════════════════════════════*/
do k=-40 while old.k\== /*process the OLD array elements.*/ if old.k//2 \== 0 then iterate /*if element isn't even, skip it.*/ news=news+1 /*bump the number of NEW elements*/ new.news=old.k /*assign it to the NEW array. */ end
/*══════════════════════════════════════════════════════════════════════*/
do j=1 for news; say 'new.'j"="new.j; end /*show all NEW numbers.*/
exit
/*─────────────────────────────────────FIB subroutine (non-recursive)───*/
fib: procedure; parse arg n; na=abs(n); if na<2 then return na /*special*/
a=0; b=1
do j=2 to na; s=a+b; a=b; b=s; end
if n>0 | na//2==1 then return s /*if positive or odd negative... */
else return -s /*return a negative Fib number. */
</lang> Output:
new.1=63245986 new.2=-14930352 new.3=3524578 new.4=-832040 new.5=196418 new.6=-46368 new.7=10946 new.8=-2584 new.9=610 new.10=-144 new.11=34 new.12=-8 new.13=2 new.14=0 new.15=2 new.16=8 new.17=34 new.18=144 new.19=610 new.20=2584 new.21=10946 new.22=46368 new.23=196418 new.24=832040 new.25=3524578 new.26=14930352 new.27=63245986
Ruby
Enumerable#select is the filter that returns a new Array. This example calls Integer#even?, which is new to Ruby 1.8.7.
<lang ruby># 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]</lang>
If you want this code to work with Ruby older than 1.8.7, then you may define Integer#even?.
<lang ruby># Integer#even? is new to Ruby 1.8.7.
- Define it for older Ruby.
unless Integer.method_defined? :even? class Integer def even? self % 2 == 0 end end end</lang>
Destructive
Array#select! is the destructive version which modifies the original Array. Array#select! is new to Ruby 1.9.2.
<lang ruby>ary = [1, 2, 3, 4, 5, 6] ary.select! {|elem| elem.even?} p ary # => [2, 4, 6]</lang>
For Ruby older than 1.9.2, you can easily define Array#select! around the older Array#delete_if method.
<lang ruby># Array#select! is new to Ruby 1.9.2.
- Define it for older Ruby.
unless Array.method_defined? :select! class Array def select! enum_for(:select!) unless block_given? delete_if { |elem| not yield elem } self end end end</lang>
Sather
<lang 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;</lang>
Scala
<lang scala>(1 to 100).filter(_ % 2 == 0)</lang>
Scheme
In the interactive prompt: <lang scheme>> (filter even? '(1 2 3 4 5 6 7 8 9 10)) (2 4 6 8 10)</lang> Or as a function: <lang scheme>(define (select-even lst)
(filter even? lst))
(select-even '(1 2 3 4 5 6 7 8 9 10))</lang>
Seed7
<lang seed7>var array integer: arr is [] (1, 2, 3, 4, 5); var array integer: evens is 0 times 0; var integer: number is 0;
for number range arr do
if not odd(number) then evens &:= [] (number); end if;
end for;</lang>
Slate
<lang slate>#(1 2 3 4 5) select: [| :number | number isEven].</lang>
Smalltalk
<lang smalltalk>#(1 2 3 4 5) select: [:number | number even]</lang>
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.
<lang sql>--Create the original array (table #nos) with numbers from 1 to 10 create table #nos (v int) declare @n int set @n=1 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</lang>
'
<lang sql>create temporary table nos (v int); insert into nos values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10); create temporary table evens (v int); 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;</lang>
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>
Standard ML
<lang sml>val ary = [1,2,3,4,5,6]; List.filter (fn x => x mod 2 = 0) ary</lang>
Tcl
Tcl doesn't really have a concept of a "number" per se - strictly speaking its only data type is the string (but a string can be interpreted as a number, of course). The generic way of getting certain elements from an array looks roughly like this:
<lang tcl>foreach key [array names arr] {if { <condition> } then {puts $arr($key)}}</lang>
In this case, we can do this particular challenge with: <lang tcl>foreach {key val} [array get srcArray] {
if {[string is integer -strict $key] && !($key%2)} { set dstArray($key) $val }
}</lang>
If we were using Tcl's lists and interpreting the challenge to mean getting just the elements at index 0, 2, 4, ... <lang tcl>foreach {even odd} $srcList {
lappend dstList $even
}</lang>
Toka
<lang 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</lang>
TUSCRIPT
<lang 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 </lang> Output:
4'16'36'64'100
UNIX Shell
<lang bash>a=(1 2 3 4 5) unset e[@] for ((i=0;i<${#a[@]};i++)); do
[ $((a[$i]%2)) -eq 0 ] && e[$i]="${a[$i]}"
done
echo "${a[@]}" echo "${e[@]}"</lang> Output:
1 2 3 4 5 2 4
UnixPipes
<lang bash>yes \ | cat -n | while read a; do ; expr $a % 2 >/dev/null && echo $a ; done</lang>
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.
<lang Ursala>#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</lang>
The output will be
<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.
<lang Ursala>z = (not remainder)~| (36,<1,2,3,4,5,6,7,8,9,10,11,12>)</lang>
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
<lang Ursala>shortcut = ~&ihBF x</lang>
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
<lang v>[even? dup 2 / >int 2 * - zero?].
[1 2 3 4 5 6 7 8 9] [even?] filter =[2 4 6 8]</lang>
Wrapl
<lang wrapl>VAR a <- ALL 1:to(10);</lang> a will be the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] <lang wrapl>VAR e <- ALL a:values \ $ % 2 = 0;</lang> e will be the list [2, 4, 6, 8, 10]
XQuery
<lang 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>{$short}</long> </result>
</lang>
The output of this query is: <lang xml> <?xml version="1.0" encoding="UTF-8"?> <result>
<short>2 4 6 8 10</short> <long>2 4 6 8 10</long>
</result> </lang>
XSLT
<lang xml><xsl:for-each select="nodes[@value mod 2 = 0]">
<xsl:value-of select="@value" />
</xsl:for-each></lang>