Filter: Difference between revisions
m (→{{header|Python}}: add lang tag) |
m (Not sure what UnderBot will do with excessive extra whitespace like this, so I'll just remove it when I see it until someone tells me to stop) |
||
Line 121: | Line 121: | ||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
<lang applescript> |
<lang applescript>set array to {1, 2, 3, 4, 5} |
||
set evens to {} |
|||
repeat with i in array |
|||
-- very important -- list index starts at 1 not 0 |
|||
if (i mod 2 = 0) then set evens to evens & i |
|||
end repeat</lang> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
Line 151: | Line 151: | ||
=={{header|C}}== |
=={{header|C}}== |
||
<lang c> |
<lang c>int arr[5] = {1,2,3,4,5}; |
||
int *result; |
|||
int memoryReqd = 0,length = sizeof(arr)/sizeof(arr[0]), i,j; |
|||
for (i=0; i<length; i++) |
|||
{ |
|||
if(0 == arr[i]%2) |
|||
{ |
{ |
||
memoryReqd++; |
|||
{ |
|||
memoryReqd++; |
|||
} |
|||
} |
} |
||
} |
|||
result = (int*)malloc(memoryReqd*sizeof(int)); |
|||
for(i=0,j=0; i<length; i++) |
|||
{ |
|||
if(0 == arr[i]%2) |
|||
{ |
{ |
||
result[j++]=arr[i]; |
|||
} |
|||
⚫ | |||
result[j++]=arr[i]; |
|||
} |
|||
⚫ | |||
Test our resultant array: |
Test our resultant array: |
||
<lang c> |
<lang c>for(i=0; i<memoryReqd; i++) |
||
{ |
|||
{ |
|||
printf("%d\n",result[i]); |
|||
}</lang> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
Line 248: | Line 248: | ||
In this example, the goal is to find the even numbers. The most straight-forward function is to use remove-if-not, which removes elements from the list that does ''not'' pass the predicate. The predicate, in this case, tests to see if an element is even. Therefore, the remove-if-not acts like a filter: |
In this example, the goal is to find the even numbers. The most straight-forward function is to use remove-if-not, which removes elements from the list that does ''not'' pass the predicate. The predicate, in this case, tests to see if an element is even. Therefore, the remove-if-not acts like a filter: |
||
<lang lisp> |
<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. There is a destructive version that modifies the list in-place: |
However, this function is non-destructive, meaning the function creates a brand new list. This might be too prohibitive for very large lists. There is a destructive version that modifies the list in-place: |
||
<lang lisp> |
<lang lisp>(delete-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10)) |
||
> (2 4 6 8 10)</lang> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
Line 323: | Line 323: | ||
In Haskell, a list is often more basic than an array: |
In Haskell, a list is often more basic than an array: |
||
<lang haskell> |
<lang haskell>ary = [1..10] |
||
evens = [x | x <- ary, even x]</lang> |
|||
or |
or |
||
<lang haskell> |
<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: |
To do the same operation on an array, the simplest way it to convert it lazily into a list: |
||
<lang haskell> |
<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. |
Note that the bounds must be known before creating the array, so the temporary list will be fully evaluated before the array is created. |
||
Line 374: | Line 374: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
<lang java> |
<lang java>int[] array = new int[] {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> |
|||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
<lang javascript> |
<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> |
|||
{{works with|Firefox|2.0}} |
{{works with|Firefox|2.0}} |
||
<lang javascript> |
<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> |
|||
{{libheader|Functional}} |
{{libheader|Functional}} |
||
<lang javascript> |
<lang javascript>Functional.select("+1&1", [1,2,3,4]) // [2, 4]</lang> |
||
=={{header|Lisaac}}== |
=={{header|Lisaac}}== |
||
Line 430: | Line 430: | ||
Check for even integers: |
Check for even integers: |
||
<lang Mathematica> |
<lang Mathematica> |
||
Select[{4, 5, Pi, 2, 1.3, 7, 6, 8.0}, EvenQ] |
|||
</lang> |
</lang> |
||
gives: |
gives: |
||
<lang Mathematica> |
<lang Mathematica> |
||
{4, 2, 6} |
|||
</lang> |
</lang> |
||
To check also for approximate number (like 8.0 in the example above) a possible solution is: |
To check also for approximate number (like 8.0 in the example above) a possible solution is: |
||
<lang Mathematica> |
<lang Mathematica> |
||
Select[{4, 5, Pi, 2, 1.3, 7, 6, 8.0}, Mod[#, 2] == 0 &] |
|||
</lang> |
</lang> |
||
gives: |
gives: |
||
<lang Mathematica> |
<lang Mathematica> |
||
{4, 2, 6, 8.} |
|||
</lang> |
</lang> |
||
notice that the function returns 8. not 8 (the dot indicates that it is a float number, not an integer). |
notice that the function returns 8. not 8 (the dot indicates that it is a float number, not an integer). |
||
Line 538: | Line 538: | ||
Using a filter function |
Using a filter function |
||
<lang php> |
<lang php>function is_even($var) { return(!($var & 1)); } |
||
$arr = range(1,5); |
|||
$evens = array_filter($arr, "is_even"); |
|||
print_r($evens);</lang> |
|||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
Line 611: | Line 611: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
<lang ruby> |
<lang ruby>ary = [1,2,3,4,5,6] #or ary = (1..6).to_a |
||
even_ary = ary.select{|el|el%2==0} |
|||
# => [2, 4, 6]</lang> |
|||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
Revision as of 14:56, 19 November 2009
You are encouraged to solve this task according to the task description, using any language you may know.
Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an 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 algol>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} set evens to {} repeat with i in array
-- very important -- list index starts at 1 not 0 if (i mod 2 = 0) then set evens to evens & i
end repeat</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.
$ 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
C
<lang c>int arr[5] = {1,2,3,4,5}; int *result; int memoryReqd = 0,length = sizeof(arr)/sizeof(arr[0]), i,j; for (i=0; i<length; i++) {
if(0 == arr[i]%2) { memoryReqd++; }
} result = (int*)malloc(memoryReqd*sizeof(int)); for(i=0,j=0; i<length; i++) {
if(0 == arr[i]%2) { result[j++]=arr[i]; }
}</lang>
Test our resultant array: <lang c>for(i=0; i<memoryReqd; i++) {
printf("%d\n",result[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>
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>
Clean
The standard environment is required for list and array comprehensions. We specify the types of the functions because array comprehensions are overloaded. Clean provides lazy, strict, and unboxed arrays.
module SelectFromArray import StdEnv
Create a lazy array where each element comes from the list 1 to 10.
array :: {Int} array = {x \\ x <- [1 .. 10]}
Create (and print) a strict array where each element (coming from another array) is even.
Start :: {!Int} Start = {x \\ x <-: array | isEven x}
Clojure
<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. 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 tango.core.Array; import 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 ]
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>
Erlang
Numbers = lists:seq(1, 5). EvenNumbers = lists:filter(fun (X) -> X rem 2 == 0 end, Numbers).
Or using a list comprehension:
EvenNumbers = [X || X <- Numbers, X rem 2 == 0].
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
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.
IDL
The where() function can select elements on any logical expression. For example
result = array[where(NOT array AND 1)]
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>
Java
<lang java>int[] array = new int[] {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>
JavaScript
<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>
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
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]
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).
MAXScript
arr = #(1, 2, 3, 4, 5, 6, 7, 8, 9) newArr = for i in arr where (mod i 2 == 0) collect i
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
Objective-C
<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:
let lst = [1;2;3;4;5;6] let even_lst = List.filter (fun x -> x mod 2 = 0) lst
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:
Lst = [1 2 3 4 5] LstEven = {Filter Lst fun{$ X} X mod 2 == 0 end}
Perl
<lang perl>my @list = (1, 2, 3, 4, 5, 6); my @even = grep { 0 == $_%2; } @list;</lang>
Perl 6
<lang perl6>my @list = 1, 2, 3, 4, 5, 6; my @even = grep { $_ % 2 == 0 }, @list;</lang>
Alternatively:
<lang perl6>my @even = @list.grep({ $_ % 2 == 0 });</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>
Pop11
Most natural solution in Pop11 would probably use list. Below we accumulate filtered elements on the stack and then allocate array for the result:
;;; Generic filtering procedure which selects from ar elements ;;; satisfying pred define filter_array(ar, pred); lvars i, k; stacklength() -> k; for i from 1 to length(ar) do ;;; if element satisfies pred we leave it on the stack if pred(ar(i)) then ar(i) endif; endfor; ;;; Collect elements from the stack into a vector return (consvector(stacklength() - k)); enddefine; ;;; Use it filter_array({1, 2, 3, 4, 5}, procedure(x); not(testbit(x, 0)); endprocedure) =>
PowerShell
<lang powershell>$array = -15..37 $array | Where-Object { $_ % 2 -eq 0 }</lang>
Prolog
evens(D, Es) :- findall(E, (member(E, D), E mod 2 =:= 0), Es).
Usage:
?- evens([1,2,3,4,5,6,7,8,9,10],E). E = [2, 4, 6, 8, 10]
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
[ 0 1 2 3 4 5 6 7 8 9 ] as nums group nums each dup 1 & if drop list as evens
Ruby
<lang ruby>ary = [1,2,3,4,5,6] #or ary = (1..6).to_a even_ary = ary.select{|el|el%2==0}
- => [2, 4, 6]</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;
Scala
val a = Array(1, 2, 3, 4, 5) val even = a.filter{x => x % 2 == 0}
Or
val even = for(val x <- a; x % 2 == 0) yield x
Slate
<lang slate>#(1 2 3 4 5) select: [| :number | number isEven].</lang>
Smalltalk
#(1 2 3 4 5) select: [:number | number even]
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.
--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
'
create temporary table nos (v int); insert into nos values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10); create temporary table evens (v int); insert into evens select v from nos where v%2=0; select * from evens order by v; /*2,4,6,8,10*/ drop table nos; drop table evens;
Or to be shorter, you could create the table evens directly from the query result :
create temporary table evens select * from nos where v%2=0;
Standard ML
val ary = [1,2,3,4,5,6]; List.filter (fn x => x mod 2 = 0) ary
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
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
UnixPipes
yes \ | cat -n | while read a; do ; expr $a % 2 >/dev/null && echo $a ; done
Ursala
Ursala doesn't have arrays, except when the run time system transparently converts a list to an array as needed for an external math library function call. However, selection can be done on lists.
Unary predicates
The most common way to select items from a list according to a unary predicate p is to write p*~, as shown below.
<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 differs from writing (not remainder/36)*~ with the operator above because 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
[even? dup 2 / >int 2 * - zero?].
[1 2 3 4 5 6 7 8 9] [even?] filter =[2 4 6 8]
Wrapl
VAR l <- ALL 1:to(10);
l will be the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
VAR m <- ALL l:values \ $ % 2 = 0;
m will be the list [2, 4, 6, 8, 10]
XSLT
<lang xml>
<xsl:for-each select="nodes[@value mod 2 = 0]"> <xsl:value-of select="@value" /> </xsl:for-each>
</lang>
- Programming Tasks
- Basic language learning
- Iteration
- ActionScript
- Ada
- ALGOL 68
- AmigaE
- AppleScript
- AutoHotkey
- AWK
- C
- C++
- C sharp
- Clean
- Clojure
- Common Lisp
- D
- Tango
- E
- Erlang
- Forth
- Groovy
- Haskell
- IDL
- J
- Java
- JavaScript
- Functional
- Lisaac
- Logo
- Mathematica
- MAXScript
- Nial
- Objective-C
- OCaml
- Octave
- Oz
- Perl
- Perl 6
- PHP
- Pop11
- PowerShell
- Prolog
- Python
- R
- Raven
- Ruby
- Seed7
- Scala
- Slate
- Smalltalk
- SQL
- Standard ML
- Tcl
- Toka
- UnixPipes
- Ursala
- V
- Wrapl
- XSLT