Apply a callback to an array: Difference between revisions

Content added Content deleted
m (Fixed lang tags.)
Line 3: Line 3:


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang actionscript>
<lang actionscript>package
package
{
{
public class ArrayCallback
public class ArrayCallback
Line 22: Line 21:
}
}
}
}
}</lang>
}
</lang>


=={{header|Ada}}==
=={{header|Ada}}==
{{works with|GNAT|GPL 2005}}
{{works with|GNAT|GPL 2005}}
<lang ada>
<lang ada>with Ada.Text_Io;
with Ada.Text_Io;
with Ada.Integer_text_IO;
with Ada.Integer_text_IO;
Line 64: Line 61:
begin
begin
Map(Sample, Display'access);
Map(Sample, Display'access);
end Call_Back_Example;
end Call_Back_Example;</lang>
</lang>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
PROC call back proc = (INT location, INT value)VOID:
<lang algol68> PROC call back proc = (INT location, INT value)VOID:
(
(
printf(($"array["g"] = "gl$, location, value))
printf(($"array["g"] = "gl$, location, value))
);
);

PROC map = (REF[]INT array, PROC (INT,INT)VOID call back)VOID:
(
FOR i FROM LWB array TO UPB array DO
call back(i, array[i])
OD
);
main:
PROC map = (REF[]INT array, PROC (INT,INT)VOID call back)VOID:
(
(
FOR i FROM LWB array TO UPB array DO
[4]INT array := ( 1, 4, 9, 16 );
call back(i, array[i])
map(array, call back proc)
)</lang>
OD
);
main:
(
[4]INT array := ( 1, 4, 9, 16 );
map(array, call back proc)
)
Output:
Output:
array[ +1] = +1
<lang algol68>array[ +1] = +1
array[ +2] = +4
array[ +2] = +4
array[ +3] = +9
array[ +3] = +9
array[ +4] = +16
array[ +4] = +16</lang>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>
<lang AutoHotkey>map("callback", "3,4,5")
map("callback", "3,4,5")
callback(array)
callback(array)
{
{
Line 103: Line 98:
{
{
%callback%(array)
%callback%(array)
}</lang>
}
</lang>




=={{header|AWK}}==
=={{header|AWK}}==
$ awk 'func psqr(x){print x,x*x}BEGIN{split("1 2 3 4 5",a);for(i in a)psqr(a[i])}'
<lang awk>$ awk 'func psqr(x){print x,x*x}BEGIN{split("1 2 3 4 5",a);for(i in a)psqr(a[i])}'
4 16
4 16
5 25
5 25
1 1
1 1
2 4
2 4
3 9
3 9</lang>


=={{header|C}}==
=={{header|C}}==
Line 175: Line 169:


{{works with|Visual C sharp|Visual C#|2005}}
{{works with|Visual C sharp|Visual C#|2005}}
<lang csharp>
<lang csharp>using System;
using System;


static class Program
static class Program
Line 209: Line 202:
Console.WriteLine(value * value);
Console.WriteLine(value * value);
}
}
}</lang>
}
</lang>


{{works with|C sharp|C#|3.0+}}
{{works with|C sharp|C#|3.0+}}
This version uses the C# 3 lambda notation.
This version uses the C# 3 lambda notation.


<lang csharp>
<lang csharp>int[] intArray = { 1, 2, 3, 4, 5 };
int[] intArray = { 1, 2, 3, 4, 5 };
Array.ForEach(intArray, i => Console.WriteLine(i * i));</lang>
Array.ForEach(intArray, i => Console.WriteLine(i * i));
</lang>


=={{header|C++}}==
=={{header|C++}}==
Line 224: Line 214:
{{works with|g++|4.1.1}}
{{works with|g++|4.1.1}}
===C-Style Array===
===C-Style Array===
<lang cpp>
<lang cpp>#include <iostream> //cout for printing
#include <iostream> //cout for printing
#include <algorithm> //for_each defined here
#include <algorithm> //for_each defined here


Line 240: Line 229:
return 0;
return 0;
}
}
//prints 1 4 9 16 25
//prints 1 4 9 16 25</lang>
</lang>


===std::vector===
===std::vector===
{{libheader|STL}}
{{libheader|STL}}
<lang cpp>#include <iostream> // cout for printing
<lang cpp>
#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
#include <algorithm> // for_each defined here
#include <vector> // stl vector class
#include <vector> // stl vector class
Line 267: Line 254:
return 0;
return 0;
}
}
//prints 1 4 9 16 25
//prints 1 4 9 16 25</lang>
</lang>


More tricky with binary function
More tricky with binary function
<lang cpp>#include <iostream> // cout for printing
<lang>
#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
#include <algorithm> // for_each defined here
#include <vector> // stl vector class
#include <vector> // stl vector class
Line 295: Line 280:
return 0;
return 0;
}
}
//prints 1x 2x 3x 4x 5x
//prints 1x 2x 3x 4x 5x</lang>
</lang>


===Boost.Lambda===
===Boost.Lambda===
{{libheader|Boost}}
{{libheader|Boost}}
<lang cpp>
<lang cpp>using namespace std;
using namespace std;
using namespace boost::lambda;
using namespace boost::lambda;
vector<int> ary(10);
vector<int> ary(10);
int i = 0;
int i = 0;
for_each(ary.begin(), ary.end(), _1 = ++var(i)); // init array
for_each(ary.begin(), ary.end(), _1 = ++var(i)); // init array
transform(ary.begin(), ary.end(), ostream_iterator<int>(cout, " "), _1 * _1); // square and output
transform(ary.begin(), ary.end(), ostream_iterator<int>(cout, " "), _1 * _1); // square and output</lang>
</lang>


=={{header|Clean}}==
=={{header|Clean}}==
Line 313: Line 295:
Define a function and an initial (unboxed) array.
Define a function and an initial (unboxed) array.


<lang clean>
<lang clean>square x = x * x
square x = x * x


values :: {#Int}
values :: {#Int}
values = {x \\ x <- [1 .. 10]}
values = {x \\ x <- [1 .. 10]}</lang>
</lang>


One can easily define a map for arrays, which is overloaded and works for all kinds of arrays (lazy, strict, unboxed).
One can easily define a map for arrays, which is overloaded and works for all kinds of arrays (lazy, strict, unboxed).


<lang clean>
<lang clean>mapArray f array = {f x \\ x <-: array}</lang>
mapArray f array = {f x \\ x <-: array}
</lang>


Apply the function to the initial array (using a comprehension) and print result.
Apply the function to the initial array (using a comprehension) and print result.


<lang clean>
<lang clean>Start :: {#Int}
Start = mapArray square values</lang>
Start :: {#Int}
Start = mapArray square values
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 337: Line 313:
Imperative: print 1, 2, 3, 4 and 5:
Imperative: print 1, 2, 3, 4 and 5:


<lang lisp>
<lang lisp>(map nil #'print #(1 2 3 4 5))</lang>
(map nil #'print #(1 2 3 4 5))
</lang>


Functional: collect squares into new vector that is returned:
Functional: collect squares into new vector that is returned:


<lang lisp>
<lang lisp>(defun square (x) (* x x))
(defun square (x) (* x x))
(map 'vector #'square #(1 2 3 4 5))</lang>
(map 'vector #'square #(1 2 3 4 5))
</lang>


Destructive, like the Javascript example; add 1 to every slot of vector *a*:
Destructive, like the Javascript example; add 1 to every slot of vector *a*:


<lang lisp>
<lang lisp>(defvar *a* (vector 1 2 3))
(defvar *a* (vector 1 2 3))
(map-into *a* #'1+ *a*)</lang>
(map-into *a* #'1+ *a*)
</lang>


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


<lang lisp>;; apply a named function, inc
<lang clojure>
(map inc [1 2 3 4])</lang>
;; apply a named function, inc
(map inc [1 2 3 4])
</lang>


<lang clojure>
<lang lisp>;; apply a function
(map (fn [x] (* x x)) [1 2 3 4])</lang>
;; apply a function
(map (fn [x] (* x x)) [1 2 3 4])
</lang>


<lang lisp>;; shortcut syntax for a function
<lang clojure>
(map #(* % %) [1 2 3 4])</lang>
;; shortcut syntax for a function
(map #(* % %) [1 2 3 4])
</lang>


=={{header|D}}==
=={{header|D}}==
<lang d>U[] map(T, U)(T[] array, U delegate(T) dg) {
<lang d>
U[] map(T, U)(T[] array, U delegate(T) dg) {
auto result = new U[array.length];
auto result = new U[array.length];
Line 387: Line 350:
[1, 2, 3, 4, 5].map( (int i) { return i+5; } )
[1, 2, 3, 4, 5].map( (int i) { return i+5; } )
);
);
}</lang>
}
</lang>
Using std.algorithm:
Using std.algorithm:
<lang d>writefln(map!("a + 5")([1, 2, 3, 4, 5]));</lang>
<lang d>
writefln(map!("a + 5")([1, 2, 3, 4, 5]));
</lang>


=={{header|E}}==
=={{header|E}}==


<lang e>
<lang e>def array := [1,2,3,4,5]
def array := [1,2,3,4,5]
def square(value) {
def square(value) {
return value * value
return value * value
}</lang>
}
</lang>


Example of builtin iteration:
Example of builtin iteration:


<lang e>
<lang e>def callback(index, value) {
def callback(index, value) {
println(`Item $index is $value.`)
println(`Item $index is $value.`)
}
}
array.iterate(callback)
array.iterate(callback)</lang>
</lang>


There is no built-in map function '''yet'''. The following is one of the ways one could be implemented, returning a plain list (which is usually an array in implementation).
There is no built-in map function '''yet'''. The following is one of the ways one could be implemented, returning a plain list (which is usually an array in implementation).


<lang e>
<lang e>def map(func, collection) {
def map(func, collection) {
def output := [].diverge()
def output := [].diverge()
for item in collection {
for item in collection {
Line 422: Line 377:
return output.snapshot()
return output.snapshot()
}
}
println(map(square, array))
println(map(square, array))</lang>
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
Line 429: Line 383:
This is a word that will call a given function on each cell in an array.
This is a word that will call a given function on each cell in an array.


<lang forth>
<lang forth>: map ( addr n fn -- )
-rot cells bounds do i @ over execute i ! cell +loop ;</lang>
: map ( addr n fn -- )
-rot cells bounds do i @ over execute i ! cell +loop ;
</lang>


Example usage:
Example usage:


<lang forth>
<lang forth>create data 1 , 2 , 3 , 4 , 5 ,
create data 1 , 2 , 3 , 4 , 5 ,
data 5 ' 1+ map \ adds one to each element of data</lang>
data 5 ' 1+ map \ adds one to each element of data
</lang>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 445: Line 395:


{{Works with |Fortran|ISO 95 and later}}
{{Works with |Fortran|ISO 95 and later}}
<lang fortran>
<lang fortran>module arrCallback
module arrCallback
contains
contains
elemental function cube( x )
elemental function cube( x )
Line 454: Line 403:
cube = x * x * x
cube = x * x * x
end function cube
end function cube
end module arrCallback
end module arrCallback</lang>
</lang>


<lang fortran>
<lang fortran>program testAC
program testAC
use arrCallback
use arrCallback
implicit none
implicit none
Line 474: Line 421:
write(*,*) b(i,:)
write(*,*) b(i,:)
end do
end do
end program testAC
end program testAC</lang>
</lang>


{{Works with|ANSI FORTRAN| 77 (with MIL-STD-1753 structured DO) and later}}
{{Works with|ANSI FORTRAN| 77 (with MIL-STD-1753 structured DO) and later}}
<lang fortran>
<lang fortran> program test
program test
C
C
C-- Declare array:
C-- Declare array:
Line 492: Line 437:
end do
end do
C
C
end
end</lang>
</lang>


=={{header|FP}}==
=={{header|FP}}==
{square * . [id, id]}
<lang fp>{square * . [id, id]}
& square: <1,2,3,4,5>
& square: <1,2,3,4,5></lang>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
Apply a named function to each member of the array. The result is a new array of the same size as the input.
Apply a named function to each member of the array. The result is a new array of the same size as the input.
let evenp x = x % 2 = 0
<lang fsharp>let evenp x = x % 2 = 0
let result = Array.map evenp [| 1; 2; 3; 4; 5; 6 |]
let result = Array.map evenp [| 1; 2; 3; 4; 5; 6 |]</lang>
The same can be done using anonymous functions, this time squaring the members of the input array.
The same can be done using anonymous functions, this time squaring the members of the input array.
let result = Array.map (fun x -> x * x) [|1; 2; 3; 4; 5|]
<lang fsharp>let result = Array.map (fun x -> x * x) [|1; 2; 3; 4; 5|]</lang>


=={{header|Groovy}}==
=={{header|Groovy}}==


Print each value in a list
Print each value in a list
<lang groovy>
<lang groovy>[1,2,3,4].each { println it }</lang>
[1,2,3,4].each { println it }
</lang>


Create a new list containing the squares of another list
Create a new list containing the squares of another list
<lang groovy>
<lang groovy>[1,2,3,4].collect { it * it }</lang>
[1,2,3,4].collect { it * it }
</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==
Line 522: Line 462:
===List===
===List===
{{works with|GHC}}
{{works with|GHC}}
<lang haskell>
<lang haskell>let square x = x*x
let square x = x*x
let values = [1..10]
let values = [1..10]
map square values
map square values</lang>
</lang>


Using list comprehension to generate a list of the squared values
Using list comprehension to generate a list of the squared values
<lang haskell>
<lang haskell>[square x | x <- values]</lang>
[square x | x <- values]
</lang>


Using function composition to create a function that will print the squares of a list
Using function composition to create a function that will print the squares of a list
<lang haskell>
<lang haskell>let printSquares = mapM_ (print.square)
let printSquares = mapM_ (print.square)
printSquares values</lang>
printSquares values
</lang>


===Array===
===Array===
{{works with|GHC}}
{{works with|GHC}}
<lang haskell>
<lang haskell>import Data.Array.IArray
import Data.Array.IArray
let square x = x*x
let square x = x*x
let values = array (1,10) [(i,i)|i <- [1..10]] :: Array Int Int
let values = array (1,10) [(i,i)|i <- [1..10]] :: Array Int Int
amap square values
amap square values</lang>
</lang>


=={{header|Icon}}==
=={{header|Icon}}==
<lang icon>
<lang icon>procedure main()
procedure main()
local lst
local lst
lst := [10, 20, 30, 40]
lst := [10, 20, 30, 40]
Line 558: Line 489:
procedure callback(arg)
procedure callback(arg)
write("->", arg)
write("->", arg)
end
end</lang>
</lang>


=={{header|IDL}}==
=={{header|IDL}}==
Line 565: Line 495:
Hard to come up with an example that isn't completely contrived. IDL doesn't really distinguish between a scalar and an array; thus
Hard to come up with an example that isn't completely contrived. IDL doesn't really distinguish between a scalar and an array; thus


b = a^3
<lang idl>b = a^3</lang>


will yield a scalar if <tt>a</tt> is scalar or a vector if <tt>a</tt> is a vector or an n-dimensional array if <tt>a</tt> is an n-dimensional array
will yield a scalar if <tt>a</tt> is scalar or a vector if <tt>a</tt> is a vector or an n-dimensional array if <tt>a</tt> is an n-dimensional array


=={{header|Io}}==
=={{header|Io}}==
list(1,2,3,4,5) map(squared)
<lang io>list(1,2,3,4,5) map(squared)</lang>


=={{header|J}}==
=={{header|J}}==
Line 590: Line 520:
So if you want to perform an action (which doesn't return anything) on an array of int's:
So if you want to perform an action (which doesn't return anything) on an array of int's:


<lang java>
<lang java>interface IntToVoid {
interface IntToVoid {
void run(int x);
void run(int x);
}
}
Line 601: Line 530:
}
}
}.run(z);
}.run(z);
}</lang>
}
</lang>


Or if you want to perform "map" - return an array of the results of function applications:
Or if you want to perform "map" - return an array of the results of function applications:


<lang java>
<lang java>interface IntToInt {
interface IntToInt {
int run(int x);
int run(int x);
}
}
Line 619: Line 546:
}
}
}.run(myIntArray[i]);
}.run(myIntArray[i]);
}</lang>
}
</lang>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 626: Line 552:
Portable technique:
Portable technique:


<lang javascript>
<lang javascript>function map(a, func) {
function map(a, func) {
for (var i in a)
for (var i in a)
a[i] = func(a[i]);
a[i] = func(a[i]);
Line 633: Line 558:


var a = [1, 2, 3, 4, 5];
var a = [1, 2, 3, 4, 5];
map(a, function(v) { return v * v; });
map(a, function(v) { return v * v; });</lang>
</lang>


{{libheader|BeyondJS}}
{{libheader|BeyondJS}}
With the [http://w3future.com/html/beyondJS/ BeyondJS] library:
With the [http://w3future.com/html/beyondJS/ BeyondJS] library:


<lang javascript>
<lang javascript>var a = (1).to(10).collect(Math.pow.curry(undefined,2));</lang>
var a = (1).to(10).collect(Math.pow.curry(undefined,2));
</lang>


With Firefox 2.0:
With Firefox 2.0:


<lang javascript>
<lang javascript>function cube(num) {
function cube(num) {
return Math.pow(num, 3);
return Math.pow(num, 3);
}
}
Line 660: Line 581:
// array comprehension
// array comprehension
var cubes2 = [cube(n) for each (n in numbers)];
var cubes2 = [cube(n) for each (n in numbers)];
var cubes3 = [n * n * n for each (n in numbers)];
var cubes3 = [n * n * n for each (n in numbers)];</lang>
</lang>


{{libheader|Functional}}
{{libheader|Functional}}
<lang javascript>
<lang javascript>Functional.map('x*x*x', [1,2,3,4,5])</lang>
Functional.map('x*x*x', [1,2,3,4,5])
</lang>


=={{header|Joy}}==
=={{header|Joy}}==
<lang joy>
<lang joy>[1 2 3 4 5] [dup *] map.</lang>
[1 2 3 4 5] [dup *] map.
</lang>


=={{header|Lisaac}}==
=={{header|Lisaac}}==
<lang Lisaac>
<lang Lisaac>+ a : ARRAY[INTEGER];
+ a : ARRAY[INTEGER];
+ b : BLOCK;
+ b : BLOCK;


Line 688: Line 603:
};
};


a.foreach b;
a.foreach b;</lang>
</lang>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>
<lang logo>to square :x
to square :x
output :x * :x
output :x * :x
end
end
show map "square [1 2 3 4 5] ; [1 4 9 16 25]
show map "square [1 2 3 4 5] ; [1 4 9 16 25]
show map [? * ?] [1 2 3 4 5] ; [1 4 9 16 25]
show map [? * ?] [1 2 3 4 5] ; [1 4 9 16 25]
foreach [1 2 3 4 5] [print square ?] ; 1 4 9 16 25, one per line
foreach [1 2 3 4 5] [print square ?] ; 1 4 9 16 25, one per line</lang>
</lang>


=={{header|Lua}}==
=={{header|Lua}}==


Say we have an array:
Say we have an array:
<lang lua>
<lang lua>myArray = {1, 2, 3, 4, 5}</lang>
myArray = {1, 2, 3, 4, 5}
</lang>
A map function for this would be
A map function for this would be
<lang lua>
<lang lua>map = function(f, data)
map = function(f, data)
local result = {}
local result = {}
for k,v in ipairs(data) do
for k,v in ipairs(data) do
Line 715: Line 624:
end
end
return result
return result
end
end</lang>
</lang>
Together with our array and a square function this yields:
Together with our array and a square function this yields:
<lang lua>
<lang lua>myFunc = function(x) return x*x end
myFunc = function(x) return x*x end


print(unpack( map(myFunc, myArray) ))
print(unpack( map(myFunc, myArray) ))
--> 1 4 9 16 25
--> 1 4 9 16 25</lang>
</lang>
If you used pairs() instead of ipairs(), this would even work on a hash table in general.
If you used pairs() instead of ipairs(), this would even work on a hash table in general.


=={{header|M4}}==
=={{header|M4}}==
<lang M4>define(`foreach', `pushdef(`$1')_foreach($@)popdef(`$1')')dnl
<lang M4>
define(`foreach', `pushdef(`$1')_foreach($@)popdef(`$1')')dnl
define(`_arg1', `$1')dnl
define(`_arg1', `$1')dnl
define(`_foreach', `ifelse(`$2', `()', `',
define(`_foreach', `ifelse(`$2', `()', `',
Line 736: Line 641:
dnl
dnl
define(`z',`eval(`$1*2') ')dnl
define(`z',`eval(`$1*2') ')dnl
apply(`(1,2,3)',`z')
apply(`(1,2,3)',`z')</lang>
</lang>


Output:
Output:
Line 774: Line 678:
=={{header|Nial}}==
=={{header|Nial}}==


<lang nial>
<lang nial>each (* [first, first] ) 1 2 3 4
=1 4 9 16</lang>
each (* [first, first] ) 1 2 3 4
=1 4 9 16
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
This function is part of the standard library:
This function is part of the standard library:


<lang ocaml>
<lang ocaml>Array.map</lang>
Array.map
</lang>


Usage example:
Usage example:
<lang ocaml>
<lang ocaml>let square x = x * x;;
let square x = x * x;;
let values = Array.init 10 ((+) 1);;
let values = Array.init 10 ((+) 1);;
Array.map square values;;
Array.map square values;;</lang>
</lang>


=={{header|Octave}}==
=={{header|Octave}}==
Line 809: Line 707:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>
<lang oz>functor
functor
import
import
Application System
Application System
Line 836: Line 733:


{Application.exit 0}
{Application.exit 0}
end
end</lang>
</lang>
=={{header|Perl}}==
=={{header|Perl}}==
<lang perl># create array
<lang perl># create array
Line 886: Line 782:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>
<lang php>function cube($n)
function cube($n)
{
{
return($n * $n * $n);
return($n * $n * $n);
Line 894: Line 789:
$a = array(1, 2, 3, 4, 5);
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
$b = array_map("cube", $a);
print_r($b);
print_r($b);</lang>
</lang>


=={{header|PL/SQL}}==
=={{header|PL/SQL}}==
{{works with|Oracle}}
{{works with|Oracle}}
<lang plsql>
<lang plsql>set serveroutput on
set serveroutput on
declare
declare
type myarray is table of number index by binary_integer;
type myarray is table of number index by binary_integer;
Line 924: Line 817:


end;
end;
/</lang>
/
</lang>


=={{header|Pop11}}==
=={{header|Pop11}}==


<lang pop11>
<lang pop11>;;; Define a procedure
;;; Define a procedure
define proc(x);
define proc(x);
printf(x*x, '%p,');
printf(x*x, '%p,');
Line 939: Line 830:


;;; Apply procedure to array
;;; Apply procedure to array
appdata(ar, proc);
appdata(ar, proc);</lang>
</lang>


If one wants to create a new array consisting of transformed values then procedure mapdata may be more convenient.
If one wants to create a new array consisting of transformed values then procedure mapdata may be more convenient.
Line 953: Line 843:


=={{header|Python}}==
=={{header|Python}}==
<lang python>
<lang python>def square(n):
def square(n):
return n * n
return n * n
Line 971: Line 860:


import itertools
import itertools
isquares2 = itertools.imap(square, numbers) # iterator, lazy
isquares2 = itertools.imap(square, numbers) # iterator, lazy</lang>
</lang>
To print squares of integers in the range from 0 to 9, type:
To print squares of integers in the range from 0 to 9, type:
<lang python>print " ".join(str(n * n) for n in range(10))</lang>
<lang python>
print " ".join(str(n * n) for n in range(10))
</lang>
Or:
Or:
<lang python>print " ".join(map(str, map(square, range(10))))</lang>
<lang python>
print " ".join(map(str, map(square, range(10))))
</lang>
Result:
Result:
<lang python>
<lang python>0 1 4 9 16 25 36 49 64 81</lang>
0 1 4 9 16 25 36 49 64 81
</lang>


=={{header|R}}==
=={{header|R}}==
Many functions can take advantage of implicit vectorisation, e.g.
Many functions can take advantage of implicit vectorisation, e.g.
<lang R>
<lang R>cube <- function(x) x*x*x
cube <- function(x) x*x*x
elements <- 1:5
elements <- 1:5
cubes <- cube(elements)
cubes <- cube(elements)</lang>
</lang>
Explicit looping over array elements is also possible.
Explicit looping over array elements is also possible.
<lang R>
<lang R>cubes <- numeric(5)
cubes <- numeric(5)
for(i in seq_along(cubes))
for(i in seq_along(cubes))
{
{
cubes[i] <- cube(elements[i])
cubes[i] <- cube(elements[i])
}</lang>
}
</lang>
Loop syntax can often simplified using the [http://stat.ethz.ch/R-manual/R-patched/library/base/html/apply.html *array] family of functions.
Loop syntax can often simplified using the [http://stat.ethz.ch/R-manual/R-patched/library/base/html/apply.html *array] family of functions.
<lang R>
<lang R>elements2 <- list(1,2,3,4,5)
cubes <- sapply(elements2, cube)</lang>
elements2 <- list(1,2,3,4,5)
cubes <- sapply(elements2, cube)
</lang>
In each case above, the value of 'cubes' is
In each case above, the value of 'cubes' is
1 8 27 64 125
1 8 27 64 125


=={{header|Raven}}==
=={{header|Raven}}==
<lang raven>
<lang raven># To print the squared elements
[1 2 3 4 5] each dup * print</lang>
# To print the squared elements
[1 2 3 4 5] each dup * print
</lang>


<lang raven>
<lang raven># To obtain a new array
# To obtain a new array
group [1 2 3 4 5] each
group [1 2 3 4 5] each
dup *
dup *
list
list</lang>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
You could use a traditional "for i in arr" approach like below:
You could use a traditional "for i in arr" approach like below:
<lang ruby>
<lang ruby>for i in [1,2,3,4,5] do
for i in [1,2,3,4,5] do
puts i**2
puts i**2
end
end</lang>
</lang>


Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk)
Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk)
<lang ruby>
<lang ruby>[1,2,3,4,5].each{ |i| puts i**2 }</lang>
[1,2,3,4,5].each{ |i| puts i**2 }
</lang>


To create a new array of each value squared
To create a new array of each value squared
<lang ruby>
<lang ruby>[1,2,3,4,5].map{ |i| i**2 }</lang>
[1,2,3,4,5].map{ |i| i**2 }
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>
<lang scala>val l = List(1,2,3,4)
l.foreach {i => println(i)}</lang>
val l = List(1,2,3,4)
l.foreach {i => println(i)}
</lang>


When the argument appears only once -as here, i appears only one in println(i) - it may be shortened to
When the argument appears only once -as here, i appears only one in println(i) - it may be shortened to
<lang scala>
<lang scala>l.foreach(println(_))</lang>
l.foreach(println(_))
</lang>
Same for an array
Same for an array
<lang scala>
<lang scala>val a = Array(1,2,3,4)
val a = Array(1,2,3,4)
a.foreach {i => println(i)}
a.foreach {i => println(i)}
a.foreach(println(_)) '' // same as previous line''
a.foreach(println(_)) '' // same as previous line''</lang>
</lang>


Or for an externally defined function:
Or for an externally defined function:
<lang scala>def doSomething(in: int) = {println("Doing something with "+in)}
<lang scala>
l.foreach(doSomething)</lang>
def doSomething(in: int) = {println("Doing something with "+in)}
l.foreach(doSomething)
</lang>


There is also a ''for'' syntax, which is internally rewritten to call foreach. A foreach method must be defined on ''a''
There is also a ''for'' syntax, which is internally rewritten to call foreach. A foreach method must be defined on ''a''
<lang scala>
<lang scala>for(val i <- a) println(i)</lang>
for(val i <- a) println(i)
</lang>


It is also possible to apply a function on each item of an list to get a new list (same on array and most collections)
It is also possible to apply a function on each item of an list to get a new list (same on array and most collections)
<lang scala>val squares = l.map{i => i * i} ''//squares is'' List(1,4,9,16)</lang>
<lang scala>
val squares = l.map{i => i * i} ''//squares is'' List(1,4,9,16)
</lang>


Or the equivalent ''for'' syntax, with the additional keyword ''yield'', map is called instead of foreach
Or the equivalent ''for'' syntax, with the additional keyword ''yield'', map is called instead of foreach
<lang scala>val squares = for (val i <- l) yield i * i</lang>
<lang scala>
val squares = for (val i <- l) yield i * i
</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>
<lang scheme>(define (square n) (* n n))
(define (square n) (* n n))
(define x #(1 2 3 4 5))
(define x #(1 2 3 4 5))
(map square (vector->list x))
(map square (vector->list x))</lang>
</lang>


A single-line variation
A single-line variation
<lang scheme>
<lang scheme>(map (lambda (n) (* n n)) '(1 2 3 4 5))</lang>
(map (lambda (n) (* n n)) '(1 2 3 4 5))
</lang>


For completeness, the <tt>map</tt> function (which is R5RS standard) can be coded as follows:
For completeness, the <tt>map</tt> function (which is R5RS standard) can be coded as follows:
<lang scheme>
<lang scheme>(define (map f L)
(define (map f L)
(if (null? L)
(if (null? L)
L
L
(cons (f (car L)) (map f (cdr L)))))
(cons (f (car L)) (map f (cdr L)))))</lang>
</lang>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>
<lang slate>#( 1 2 3 4 5 ) collect: [| :n | n * n].</lang>
#( 1 2 3 4 5 ) collect: [| :n | n * n].
</lang>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>
<lang smalltalk>#( 1 2 3 4 5 ) collect: [:n | n * n].</lang>
#( 1 2 3 4 5 ) collect: [:n | n * n].
</lang>
=={{header|Tcl}}==
=={{header|Tcl}}==


Line 1,130: Line 972:
=={{header|TI-89 BASIC}}==
=={{header|TI-89 BASIC}}==


<pre style="font-family:'TI Uni'">© For no return value
<lang ti89b>© For no return value
Define foreach(fe_cname,fe_list) = Prgm
Define foreach(fe_cname,fe_list) = Prgm
Local fe_i
Local fe_i
Line 1,146: Line 988:


foreach("callback", {1,2,3,4,5})
foreach("callback", {1,2,3,4,5})
Disp map("√", {1,2,3,4,5})</pre>
Disp map("√", {1,2,3,4,5})</lang>


Output:
Output:
Line 1,159: Line 1,001:
=={{header|Toka}}==
=={{header|Toka}}==


<lang toka>
<lang toka>( array count function -- )
{
( array count function -- )
value| array fn |
{
value| array fn |
[ i array ] is I
[ to fn swap to array 0 swap [ I array.get :stack fn invoke I array.put ] countedLoop ]
[ i array ] is I
} is map-array
[ to fn swap to array 0 swap [ I array.get :stack fn invoke I array.put ] countedLoop ]

} is map-array
( Build an array )
( Build an array )
5 cells is-array a
5 cells is-array a
10 0 a array.put
10 0 a array.put
11 1 a array.put
11 1 a array.put
12 2 a array.put
12 2 a array.put
13 3 a array.put
13 3 a array.put
14 4 a array.put

14 4 a array.put
( Add 1 to each item in the array )
( Add 1 to each item in the array )
a 5 [ 1 + ] map-array</lang>
a 5 [ 1 + ] map-array
</lang>




Line 1,183: Line 1,023:
The * is a built-in map operator.
The * is a built-in map operator.
This example shows a map of the successor function over a list of natural numbers.
This example shows a map of the successor function over a list of natural numbers.
<lang Ursala>
<lang Ursala>#import nat
#import nat


#cast %nL
#cast %nL


demo = successor* <325,32,67,1,3,7,315>
demo = successor* <325,32,67,1,3,7,315></lang>
</lang>
output:
output:
<pre>
<pre>
Line 1,197: Line 1,035:
=={{header|V}}==
=={{header|V}}==
apply squaring (dup *) to each member of collection
apply squaring (dup *) to each member of collection
<lang v>
<lang v>[1 2 3 4] [dup *] map</lang>
[1 2 3 4] [dup *] map
</lang>


=={{header|Vorpal}}==
=={{header|Vorpal}}==
Given and array, A, and a function, F, mapping F over the elements of A is simple:
Given and array, A, and a function, F, mapping F over the elements of A is simple:
<lang vorpal>
<lang vorpal>A.map(F)</lang>
A.map(F)
</lang>
If F takes 2 arguments, x and , then simply pass them to map. They will be passed to F when as it is applied to each element of A.
If F takes 2 arguments, x and , then simply pass them to map. They will be passed to F when as it is applied to each element of A.
<lang vorpal>
<lang vorpal>A.map(F, x, y)</lang>
A.map(F, x, y)
</lang>


{{omit from|gnuplot}}
{{omit from|gnuplot}}