Apply a callback to an array: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
(revert spam)
Line 1: Line 1:
{{task}}
[http://zodip.info/description/pellizzari-achille.htm pellizzari, achille] [http://puli.org.cn/web/siti-cover/ siti cover cd] [http://zodip.info/description/matteo-e.htm matteo e sonia] [http://hangzhau.cn/html/san-costantino/ san costantino] [http://italnet.net.cn/img/www-batistuta/ www batistuta it] [http://zodip.info/description/tiraera.htm tiraera] [http://puli.org.cn/web/bari-reggio/ bari reggio calabria] [http://italnet.net.cn/img/leggi-e/ leggi e mandati] [http://hangzhau.cn/html/i-lupi/ i lupi attaccano in branco] [http://nibko.info/data/www-proposal.htm www proposal com] [http://hangzhau.cn/html/torta-alla/ torta alla frutta] [http://italnet.net.cn/img/ozu-chat/ ozu chat] [http://zodip.info/description/assicurazione-immobiliare.htm assicurazione immobiliare] [http://puli.org.cn/web/barracuda-/ barracuda 200 gb] [http://puli.org.cn/web/fuochi-ultimi/ fuochi ultimi] [http://puli.org.cn/web/poeti-durante/ poeti durante la guerra fredda] [http://hangzhau.cn/html/www-google/ www google com br] [http://puli.org.cn/web/shadows-ashlee/ shadows ashlee simpson] [http://puli.org.cn/web/chacalon-sus/ chacalon sus videos] [http://italnet.net.cn/img/elettronica-musica/ elettronica musica] [http://nibko.info/data/www-informagiovani.htm www informagiovani] [http://puli.org.cn/web/viacreme-in/ viacreme in italia] [http://hangzhau.cn/html/gioco-pc/ gioco pc scarica gratis] [http://zodip.info/description/putas-borrachas.htm putas borrachas] [http://puli.org.cn/web/trucchi-pc/ trucchi pc need for speed underground] [http://puli.org.cn/web/cavo-optical/ cavo optical] [http://nibko.info/data/adult-web.htm adult web cams] [http://zodip.info/description/classifica-libri.htm classifica libri] [http://zodip.info/description/scarlet-keegan.htm scarlet keegan] [http://zodip.info/description/epson-aculaser.htm epson aculaser c 8600] [http://zodip.info/description/e-.htm e 300 td avantgarde] [http://zodip.info/description/delma-calabria.htm delma calabria] [http://italnet.net.cn/img/movimento-socialista/ movimento socialista] [http://hangzhau.cn/html/ciclo-mestruale/ ciclo mestruale] [http://puli.org.cn/web/prisma/ prisma] [http://nibko.info/data/il-segno.htm il segno] [http://nibko.info/data/beyonce-video.htm beyonce video] [http://zodip.info/description/mk-c.htm mk c12] [http://italnet.net.cn/img/astro-boy/ astro boy] [http://puli.org.cn/web/cunni/ cunni] [http://hangzhau.cn/html/kia-sorento/ kia sorento lombardia] [http://italnet.net.cn/img/la-polizia/ la polizia incrimina, la legge assolve] [http://nibko.info/data/e-sulo.htm e sulo niente] [http://italnet.net.cn/img/manifesti-pubblicita/ manifesti pubblicita germania playboy] [http://puli.org.cn/web/brid/ brid] [http://nibko.info/data/lexmark-z.htm lexmark z515] [http://hangzhau.cn/html/vecchio-frac/ vecchio frac] [http://puli.org.cn/web/fotos-de/ fotos de marina mora] [http://zodip.info/description/jose-luis.htm jose luis peralez] [http://zodip.info/description/honda.htm honda 600] [http://zodip.info/description/kit-wireless.htm kit wireless netgear] [http://nibko.info/data/universita-degli.htm universita degli studi del molise] [http://hangzhau.cn/html/maxtor-fw/ maxtor fw800] [http://zodip.info/description/escape-from.htm escape from house] [http://zodip.info/description/le-piu.htm le piu belle delle olimpiadi] [http://hangzhau.cn/html/golden-miners/ golden miners] [http://nibko.info/data/zaino-kensington.htm zaino kensington] [http://puli.org.cn/web/hyundai-santamo/ hyundai santamo] [http://hangzhau.cn/html/c-dion/ c dion] [http://puli.org.cn/web/kirchsteigfeld-potsdam/ kirchsteigfeld potsdam] [http://italnet.net.cn/img/binocoli-bushnell/ binocoli bushnell] [http://nibko.info/data/colejialas-com.htm colejialas com] [http://italnet.net.cn/img/mauro-goia/ mauro goia] [http://zodip.info/description/triumph-motor.htm triumph motor co.] [http://puli.org.cn/web/original-sing/ original sing] [http://italnet.net.cn/img/la-scola/ la scola della musica] [http://puli.org.cn/web/clp-n/ clp 550n] [http://italnet.net.cn/img/cartuccia-originali/ cartuccia originali hp] [http://hangzhau.cn/html/hino-nacional/ hino nacional do indonesia] [http://puli.org.cn/web/cartina-geografica/ cartina geografica] [http://puli.org.cn/web/titoli-telefilm/ titoli telefilm anni 70] [http://hangzhau.cn/html/driver-mpu/ driver mpu 401] [http://zodip.info/description/una-diciassettenne.htm una diciassettenne] [http://hangzhau.cn/html/modelos-argentinas/ modelos argentinas] [http://puli.org.cn/web/prodotto-alimentare/ prodotto alimentare tipico] [http://nibko.info/data/ati-radeon.htm ati radeon all in wonder 9800] [http://hangzhau.cn/html/debussy-infinito/ debussy infinito] [http://puli.org.cn/web/whit-or/ whit or whithout yu] [http://hangzhau.cn/html/sexy-pussy/ sexy pussy] [http://puli.org.cn/web/spedizionieri-treviso/ spedizionieri treviso] [http://puli.org.cn/web/kelly-madison/ kelly madison] [http://zodip.info/description/decoder-humax.htm decoder humax dtt] [http://puli.org.cn/web/incontro-reale/ incontro reale] [http://italnet.net.cn/img/foto-personaggi/ foto personaggi di un posto al sole] [http://nibko.info/data/obiettivi-nikon.htm obiettivi nikon 24-120mm] [http://zodip.info/description/hp-g.htm hp 39g] [http://puli.org.cn/web/animaticon-gratis/ animaticon gratis] [http://nibko.info/data/ere-mi.htm ere mi respirar] [http://italnet.net.cn/img/cyruss/ cyruss] [http://zodip.info/description/puttane-si.htm puttane si] [http://zodip.info/description/indesit-wil.htm indesit wil 86] [http://nibko.info/data/litio-stilo.htm litio stilo aa] [http://nibko.info/data/bruno-coulais.htm bruno coulais] [http://puli.org.cn/web/free-font/ free font download] [http://nibko.info/data/armi-da.htm armi da collezionare] [http://italnet.net.cn/img/ospedale-santoro/ ospedale santoro] [http://italnet.net.cn/img/il-cavaliere/ il cavaliere della stella doro] [http://hangzhau.cn/html/cat-a/ cat a pulta] [http://italnet.net.cn/img/buon-giorno/ buon giorno principessa] [http://hangzhau.cn/html/cartoonetwork-cl/ cartoonetwork cl] [http://nibko.info/data/spartito-flauto.htm spartito flauto] [http://italnet.net.cn/img/loce-hina/ loce hina] [http://puli.org.cn/web/i-love/ i love this sex] [http://zodip.info/description/april.htm april] [http://hangzhau.cn/html/toner-c/ toner c9500] [http://italnet.net.cn/img/fiore-delle/ fiore delle hawaii] [http://puli.org.cn/web/windows-xp/ windows xp home edition sp2] [http://nibko.info/data/lisa-gastoni.htm lisa gastoni] [http://zodip.info/description/dakar-roma.htm dakar roma] [http://italnet.net.cn/img/frigorifero-/ frigorifero 120 litri] [http://italnet.net.cn/img/trea-spa/ trea spa] [http://puli.org.cn/web/tapis-roulant/ tapis roulant phoenix high power] [http://hangzhau.cn/html/wayne-rooney/ wayne rooney] [http://zodip.info/description/detrazione-ici.htm detrazione ici] [http://zodip.info/description/katie-jordan.htm katie jordan] [http://hangzhau.cn/html/adulterio/ adulterio] [http://nibko.info/data/nokiia.htm nokiia] [http://zodip.info/description/lost-highway.htm lost highway] [http://nibko.info/data/google-image.htm google image] [http://nibko.info/data/sexo-prohibidos.htm sexo prohibidos] [http://puli.org.cn/web/tabla-de/ tabla de ascii] [http://hangzhau.cn/html/pagefocus/ pagefocus] [http://nibko.info/data/rovera-ab.htm rovera ab fast] [http://nibko.info/data/emanuele-spagnuolo.htm emanuele spagnuolo] [http://puli.org.cn/web/running-nike/ running nike] [http://hangzhau.cn/html/vienna-offerta/ vienna offerta] [http://puli.org.cn/web/acer-t/ acer t120] [http://hangzhau.cn/html/video-games/ video games sim] [http://puli.org.cn/web/lose-your/ lose your self eminem] [http://puli.org.cn/web/argo-climatizzatore/ argo climatizzatore] [http://nibko.info/data/copertine-cd.htm copertine cd] [http://nibko.info/data/lovell-sir.htm lovell, sir bernard alfred ch...] [http://nibko.info/data/tastiera-labtec.htm tastiera labtec] [http://italnet.net.cn/img/anle/ anle] [http://hangzhau.cn/html/il-vento/ il vento dell est midi] [http://nibko.info/data/cortocorto.htm cortocorto] [http://zodip.info/description/un-ora.htm un ora sola ti vorrei giorgia] [http://hangzhau.cn/html/ortisei-val/ ortisei val gardena] [http://italnet.net.cn/img/topetta/ topetta] [http://zodip.info/description/allessandra-schiavo.htm allessandra schiavo] [http://nibko.info/data/obsesion-midi.htm obsesion midi file] [http://puli.org.cn/web/norton-italia/ norton italia] [http://puli.org.cn/web/film-di/ film di bud spencer] [http://italnet.net.cn/img/quotazioni-ford/ quotazioni ford] [http://italnet.net.cn/img/foto-camera/ foto camera digitale casio] [http://zodip.info/description/la-bionda.htm la bionda graffia] [http://puli.org.cn/web/asus-/ asus 620 gps] [http://nibko.info/data/kids-wb.htm kids wb] [http://puli.org.cn/web/speedy-gonzales/ speedy gonzales] [http://puli.org.cn/web/bilale/ bilale] [http://puli.org.cn/web/lettore-dvd/ lettore dvd dvx vcr] [http://italnet.net.cn/img/luka-rijeka/ luka rijeka] [http://puli.org.cn/web/imola-singole/ imola singole] [http://hangzhau.cn/html/brainwaves/ brainwaves] [http://zodip.info/description/torn.htm torn] [http://zodip.info/description/ebony-fuck.htm ebony fuck] [http://nibko.info/data/hotel-a.htm hotel a verona] [http://puli.org.cn/web/red-tatoo/ red tatoo] [http://puli.org.cn/web/san-andreas/ san andreas] [http://zodip.info/description/tetta-grossa.htm tetta grossa] [http://hangzhau.cn/html/cristano-ronaldo/ cristano ronaldo] [http://puli.org.cn/web/albergo-economico/ albergo economico barcellona] [http://italnet.net.cn/img/fotocamere-con/ fotocamere con grandangolo] [http://zodip.info/description/firmware-philips.htm firmware philips] [http://nibko.info/data/olimpus-mju.htm olimpus mju mini] [http://hangzhau.cn/html/voci-berlusconi/ voci berlusconi] [http://italnet.net.cn/img/noleggio-porsche/ noleggio porsche cayenne] [http://zodip.info/description/olo.htm olo] [http://hangzhau.cn/html/cause-di/ cause di artrosi] [http://nibko.info/data/cavo-autoradio.htm cavo autoradio] [http://italnet.net.cn/img/mini-amplificatore/ mini amplificatore] [http://zodip.info/description/ditalini-giovanili.htm ditalini giovanili] [http://puli.org.cn/web/tastiere-mouse/ tastiere mouse microsoft] [http://nibko.info/data/canon-g.htm canon g] [http://zodip.info/description/hotel-san.htm hotel san pietroburgo] [http://zodip.info/description/povera-voce.htm povera voce] [http://nibko.info/data/cinema-of.htm cinema of ro ma] [http://nibko.info/data/casa-vacanza.htm casa vacanza trentino] [http://italnet.net.cn/img/daniele-cicarelli/ daniele cicarelli] [http://puli.org.cn/web/www-gamespot/ www gamespot it] [http://zodip.info/description/maggiori-dettagli.htm maggiori dettagli] [http://puli.org.cn/web/neked/ neked] [http://italnet.net.cn/img/www-cr/ www cr decorazioni com] [http://zodip.info/description/mirco-visconti.htm mirco visconti srl] [http://zodip.info/description/falk.htm falk] [http://hangzhau.cn/html/italia-piemonte/ italia piemonte 2002] [http://zodip.info/description/scarpone.htm scarpone] [http://hangzhau.cn/html/sxx/ sxx] [http://puli.org.cn/web/passione/ passione] [http://zodip.info/description/windows-mobile.htm windows mobile 5] [http://italnet.net.cn/img/bct/ bct 1530] [http://nibko.info/data/ministero-dell.htm ministero dell istruzione dell universit] [http://hangzhau.cn/html/ray-ban/ ray ban wayfarer 2038] [http://hangzhau.cn/html/sancamaleon/ sancamaleon] [http://puli.org.cn/web/vagina-manuela/ vagina manuela arcuri] [http://hangzhau.cn/html/rossellabrescia/ rossellabrescia] [http://zodip.info/description/tvc-.htm tvc 20 lcd sharp] [http://italnet.net.cn/img/es-s/ es 4033s] [http://zodip.info/description/nomi-reali.htm nomi reali] [http://puli.org.cn/web/che-fantastica/ che fantastica] {{task}}
== [[Ada]] ==
== [[Ada]] ==
[[Category:Ada]]
[[Category:Ada]]
'''Tested With:'''
'''Tested With:'''
* [[Gnat GPL 2005]]
* [[Gnat GPL 2005]]
** Amd-64bit-3500 -WinXP
** Amd-64bit-3500+-WinXP


with Ada.Text_Io;
with Ada.Text_Io;
Line 93: Line 93:
{
{
int i;
int i;
for(i = 0; i < len; i )
for(i = 0; i < len; i++)
{
{
callback(i, array[i]);
callback(i, array[i]);
Line 116: Line 116:
'''Platform:''' [[.NET]]
'''Platform:''' [[.NET]]


'''Language Version:''' 2.0
'''Language Version:''' 2.0+


'''Compiler:''' [[Visual C sharp|Visual C#]] 2005
'''Compiler:''' [[Visual C sharp|Visual C#]] 2005
Line 155: Line 155:
}
}


==[[C plus plus|C ]]==
==[[C plus plus|C++]]==
[[Category:C plus plus]]
[[Category:C plus plus]]
'''Compiler:''' [[GNU Compiler Collection]] 4.1.1
'''Compiler:''' [[GNU Compiler Collection]] 4.1.1
Line 171: Line 171:
int ary[]={1,2,3,4,5};
int ary[]={1,2,3,4,5};
//stl for_each
//stl for_each
std::for_each(ary,ary 5,print_square);
std::for_each(ary,ary+5,print_square);
return 0;
return 0;
}
}
Line 230: Line 230:
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


Line 267: Line 267:


(defvar *a* (vector 1 2 3))
(defvar *a* (vector 1 2 3))
(map-into *a* #'1 *a*)
(map-into *a* #'1+ *a*)


==[[E]]==
==[[E]]==
Line 301: Line 301:


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


Example usage:
Example usage:


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
data 5 ' 1+ map \ adds one to each element of data


==[[Fortran]]==
==[[Fortran]]==
Line 332: Line 332:


{square * . [id, id]}
{square * . [id, id]}
& square: <1,2,3,4,5>

== [[Haskell]] ==
[[Category:Haskell]]
'''Interpreter''' : [[GHC | GHCi]]

'''Compiler''' : [[GHC]]

let square x = x*x
let values = [1..10]
map square values

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

Using function composition to create a function that will print the squares of a list
let printSquares = putStr.unlines.map (show.square)
printSquares values


== [[IDL]] ==
[[Category:IDL]]

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

will yield a scalar if a is scalar or a vector if a is a vector or an n-dimensional array is a is an n-dimensional array

== [[JavaScript]] ==
[[Category:JavaScript]]

Portable technique:

function map(a, func) {
for (var i in a)
a[i] = func(a[i]);
}
var a = [1, 2, 3, 4, 5];
map(a, function(v) { return v * v; });

With the [http://w3future.com/html/beyondJS/ BeyondJS] library:

var a = (1).to(10).collect(Math.pow.curry(undefined,2));

With Firefox 2.0:

function cube(num) {
return Math.pow(num, 3);
}
var numbers = [1, 2, 3, 4, 5];
//get results of calling cube on every element
var cubes1 = numbers.map(cube);
//display each result in a separate dialog
cubes1.forEach(alert);
//array comprehension
var cubes2 = [cube(n) for each (n in numbers)];
var cubes3 = [n * n * n for each (n in numbers)];

==[[Lua]]==
[[Category:Lua]]

Say we have an array:
myArray = {1, 2, 3, 4, 5}
A map function for this would be
map = function(f, data)
local result = {}
for k,v in ipairs(data) do
result[k] = f(v)
end
return result
end
Together with our array and and a square function this yields:
myFunc = function(x) return x*x end
print(unpack( map(myFunc, myArray) ))
--> 1 4 9 16 25
If you used pairs() instead of ipairs(), this would even work on a hash table in general.

== [[OCaml]] ==
[[Category:OCaml]]
This function is part of the standard library:

Array.map

Usage example:

let square x = x * x;;
let values = Array.init 10 ((+) 1);;
Array.map square values;;

==[[Perl]]==
[[Category:Perl]]

# create array
my @a = (1, 2, 3, 4, 5);

# create callback function
sub mycallback {
return 2 * shift;
}

# use array indexing
my $i;
for ($i = 0; $i < scalar @a; $i++) {
print "mycallback($a[$i]) = ", mycallback($a[$i]), "\n";
}

# using foreach
foreach my $x (@a) {
print "mycallback($x) = ", mycallback($x), "\n";
}

# using map (useful for transforming an array)
my @b = map mycallback($_), @a; # @b is now (2, 4, 6, 8, 10)

# and the same using an anonymous function
my @c = map { $_ * 2 } @a; # @c is now (2, 4, 6, 8, 10)

# use a callback stored in a variable
my $func = \&mycallback;
my @d = map &{$func}($_), @a; # @d is now (2, 4, 6, 8, 10)

==[[PHP]]==
[[Category:PHP]]

function cube($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);

== [[PL/SQL]] ==
[[Category:PL/SQL]]
'''Interpreter''' : Oracle compiler

set serveroutput on
declare
type myarray is table of number index by binary_integer;
x myarray;
i pls_integer;
begin
-- populate array
for i in 1..5 loop
x(i) := i;
end loop;
i :=0;
-- square array
loop
i := i + 1;
begin
x(i) := x(i)*x(i);
dbms_output.put_line(x(i));
exception
when no_data_found then exit;
end;
end loop;
end;
/

==[[Pop11]]==
[[Category:Pop11]]

;;; Define a procedure
define proc(x);
printf(x*x, '%p,');
enddefine;

;;; Create array
lvars ar = { 1 2 3 4 5};

;;; Apply procedure to array
appdata(ar, proc);

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


== [[Python]] ==
[[Category:Python]]
<pre>
def square(n):
return n * n
numbers = [1, 3, 5, 7]

squares1 = [square(n) for n in numbers] # list comprehension

squares2 = map(square, numbers) # discouraged nowadays

squares3 = [n * n for n in numbers] # no need for a function,
# anonymous or otherwise

isquares = (n * n for n in numbers) # iterator, lazy
</pre>

==[[Ruby]]==
[[Category:Ruby]]
# You could use a traditional "for i in arr" approach like below:
for i in [1,2,3,4,5] do
puts i**2
end

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

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

==[[Scala]]==
[[Category:Scala]]
val l = List(1,2,3,4)
l.foreach {i => Console.println(i)}

Same for an array
val a = Array(1,2,3,4)
a.foreach {i => Console.println(i)}

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

There is also a ''for'' syntax, which is internally rewritten to call foreach. A foreach method must be define on ''a''
for(val i <- a) Console.println(i)

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)
val squares = l.map{i => i * i} //returns List(1,4,9,16)

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

== [[Scheme]] ==
[[Category:Scheme]]
(define (square n) (* n n))
(define x #(1 2 3 4 5))
(map square (vector->list x))


A single-line variation
(map (lambda (n) (* n n)) '(1 2 3 4 5))

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

== [[Smalltalk]] ==
[[Category:Smalltalk]]
| anArray |
anArray = #( 1 2 3 4 5 )
anArray do: [ :x | Transcript nextPut: x * x ]

== [[Tcl]] ==
[[Category:Tcl]]

If I wanted to call "<tt>myfunc</tt>" on each element of <tt>dat</tt> and <tt>dat</tt> were a list:

foreach var $dat { myfunc $var }

if <tt>dat</tt> were an array, however:

foreach var [array names dat] { myfunc $dat($var) }

== [[Toka]] ==
[[Category:Toka]]

( array count function -- )
{
variable| array fn |
[ i 1- array @ ] is I
[ fn ! swap array ! [ I get-element fn @ invoke I put-element ] +iterate ]
} is map-array
( Build an array )
5 cells is-array a
10 0 a put-element
11 1 a put-element
12 2 a put-element
13 3 a put-element
14 4 a put-element
( Add 1 to each item in the array )
a 5 ` 1+ map-array

Revision as of 12:11, 2 September 2007

Task
Apply a callback to an array
You are encouraged to solve this task according to the task description, using any language you may know.

Ada

Tested With:

with Ada.Text_Io;
with Ada.Integer_text_IO;

procedure Call_Back_Example is
   -- Purpose: Apply a callback to an array
   -- Output: Prints the squares of an integer array to the console
  
   -- Define the callback procedure
   procedure Display(Location : Positive; Value : Integer) is
   begin
      Ada.Text_Io.Put("array(");
      Ada.Integer_Text_Io.Put(Item => Location, Width => 1);
      Ada.Text_Io.Put(") = ");
      Ada.Integer_Text_Io.Put(Item => Value * Value, Width => 1);
      Ada.Text_Io.New_Line;
   end Display;
  
   -- Define an access type matching the signature of the callback procedure
   type Call_Back_Access is access procedure(L : Positive; V : Integer);
  
   -- Define an unconstrained array type
   type Value_Array is array(Positive range <>) of Integer;
  
   -- Define the procedure performing the callback
   procedure Map(Values : Value_Array; Worker : Call_Back_Access) is
   begin
      for I in Values'range loop
         Worker(I, Values(I));
      end loop;
   end Map;
  
   -- Define and initialize the actual array
   Sample : Value_Array := (5,4,3,2,1);
  
begin
   Map(Sample, Display'access);   
end Call_Back_Example;

C

Tested With:

  • GCC 3.3.6
    • i686-pc-linux-gnu
  • GCC 3.4.6
    • i686-pc-linux-gnu
  • GCC 4.0.3
    • i686-pc-linux-gnu
  • GCC 4.1.1
    • i686-pc-linux-gnu
    • powerpc-unknown-linux-gnu
  • TCC 0.9.23
    • i686-pc-linux-gnu
  • ICC 9.1
    • i686-pc-linux-gnu

callback.h

 #ifndef __CALLBACK_H
 #define __CALLBACK_H
 /*
  * By declaring the function in a separate file, we allow
  * it to be used by other source files.
  *
  * It also stops ICC from complaining.
  *
  * If you don't want to use it outside of callback.c, this
  * file can be removed, provided the static keyword is prepended
  * to the definition.
  */
 void map(int* array, int len, void(*callback)(int,int));
 #endif

callback.c

 #include <stdio.h>
 #include "callback.h"
 /*
  * We don't need this function outside of this file, so
  * we declare it static.
  */
 static void callbackFunction(int location, int value)
 {
   printf("array[%d] = %d\n", location, value);
 } 
 void map(int* array, int len, void(*callback)(int,int))
 {
   int i;
   for(i = 0; i < len; i++)
   {
      callback(i, array[i]);
   }
 } 
 int main()
 {
   int array[] = { 1, 2, 3, 4 };
   map(array, 4, callbackFunction);
   return 0;
 }

Output

 array[0] = 1
 array[1] = 2
 array[2] = 3
 array[3] = 4

C#

Platform: .NET

Language Version: 2.0+

Compiler: Visual C# 2005

using System; 

static class Program
{
  // Purpose: Apply a callback (or anonymous method) to an Array
  // Output: Prints the squares of an int array to the console.
  // Compiler: Visual Studio 2005
  // Framework: .net 2
   
  [STAThread]
  public static void Main() 
  {
    int[] intArray = { 1, 2, 3, 4, 5 };

    // Using a callback,
    Console.WriteLine("Printing squares using a callback:");
    Array.ForEach<int>(intArray, PrintSquare);

    // or using an anonymous method:
    Console.WriteLine("Printing squares using an anonymous method:");
    Array.ForEach<int>
    (
      intArray,
      delegate(int value) 
      {
        Console.WriteLine(value * value);    
      });
  }

  public static void PrintSquare(int value) 
  { 
    Console.WriteLine(value * value);
  }
}

C++

Compiler: GNU Compiler Collection 4.1.1

Using c-style array

#include <iostream> //cout for printing
#include <algorithm> //for_each defined here
//create the function (print the square)
void print_square(int i) {
  std::cout << i*i << " ";
}
int main() {
  //create the array
  int ary[]={1,2,3,4,5};
  //stl for_each
  std::for_each(ary,ary+5,print_square);
  return 0;
}
//prints 1 4 9 16 25

Using std::vector

#include <iostream> //cout for printing
#include <algorithm> //for_each defined here
#include <vector> //stl vector class
//create the function (print the square)
void print_square(int i) {
  std::cout << i*i << " ";
}
int main() {
  //create the array
  std::vector<int> ary;
  ary.push_back(1);
  ary.push_back(2);
  ary.push_back(3);
  ary.push_back(4);
  ary.push_back(5);
  //stl for_each
  std::for_each(ary.begin(),ary.end(),print_square);
  return 0;
}
//prints 1 4 9 16 25

More tricky with binary function

#include <iostream> //cout for printing
#include <algorithm> //for_each defined here
#include <vector> //stl vector class
#include <functional> //bind and ptr_fun
//create a binary function (print any two arguments together)
template<class type1,class type2>
void print_juxtaposed(type1 x, type2 y) {
  std::cout << x << y;
}
int main() {
  //create the array
  std::vector<int> ary;
  ary.push_back(1);
  ary.push_back(2);
  ary.push_back(3);
  ary.push_back(4);
  ary.push_back(5);
  //stl for_each, using binder and adaptable unary function
  std::for_each(ary.begin(),ary.end(),std::bind2nd(std::ptr_fun(print_juxtaposed<int,std::string>),"x "));
  return 0;
}
//prints 1x 2x 3x 4x 5x

Using Boost.Lambda

 using namespace std;
 using namespace boost::lambda;
 vector<int> ary(10);
 int i = 0;
 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

Clean

Define a function and an initial (unboxed) array.

square x = x * x

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

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

mapArray f array = {f x \\ x <-: array}

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

Start :: {#Int}
Start = mapArray square values

Common Lisp

Imperative: print 1, 2, 3, 4 and 5:

 (map nil #'print #(1 2 3 4 5))

Functional: collect squares into new vector that is returned:

 (defun square (x) (* x x))
 (map 'vector #'square #(1 2 3 4 5))

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

 (defvar *a* (vector 1 2 3))
 (map-into *a* #'1+ *a*)

E

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

Example of builtin iteration:

def callback(index, value) { 
    println(`Item $index is $value.`)
}
array.iterate(callback)

There is no builtin 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).

def map(func, collection) {
    def output := [].diverge()
    for item in collection {
        output.push(func(item))
    }
    return output.snapshot()
}
println(map(square, array))

Forth

This is a word that will call a given function on each cell in an array.

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

Example usage:

create data 1 , 2 , 3 , 4 , 5 ,
data 5 ' 1+ map  \ adds one to each element of data

Fortran

      program test
C
C--   Declare array:
      integer a(5)
C
C--   Fill it with Data
      data a /45,22,67,87,98/
C
C--   Do something with all elements (in this case: print their squares)
      do i=1,5
        print *,a(i)*a(i)
      end do
C
      end


FP

Interpreter : "fp"

 {square * . [id, id]}
 & square: <1,2,3,4,5>

Haskell

Interpreter : GHCi

Compiler : GHC

 let square x = x*x
 let values = [1..10]
 map square values

Using list comprehension to generate a list of the squared values

 [square x | x <- values]

Using function composition to create a function that will print the squares of a list

 let printSquares = putStr.unlines.map (show.square)
 printSquares values


IDL

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

will yield a scalar if a is scalar or a vector if a is a vector or an n-dimensional array is a is an n-dimensional array

JavaScript

Portable technique:

function map(a, func) {
  for (var i in a)
    a[i] = func(a[i]);
}

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

With the BeyondJS library:

var a = (1).to(10).collect(Math.pow.curry(undefined,2));

With Firefox 2.0:

function cube(num) {
  return Math.pow(num, 3);
}

var numbers = [1, 2, 3, 4, 5];

//get results of calling cube on every element
var cubes1 = numbers.map(cube);

//display each result in a separate dialog
cubes1.forEach(alert);

//array comprehension
var cubes2 = [cube(n) for each (n in numbers)];
var cubes3 = [n * n * n for each (n in numbers)];

Lua

Say we have an array:

myArray = {1, 2, 3, 4, 5}

A map function for this would be

map = function(f, data)
   local result = {}
   for k,v in ipairs(data) do
      result[k] = f(v)
   end
   return result
end

Together with our array and and a square function this yields:

myFunc = function(x) return x*x end

print(unpack( map(myFunc, myArray) ))
--> 1   4   9   16  25

If you used pairs() instead of ipairs(), this would even work on a hash table in general.

OCaml

This function is part of the standard library:

 Array.map

Usage example:

 let square x = x * x;;
 let values = Array.init 10 ((+) 1);;
 Array.map square values;;

Perl

 # create array
 my @a = (1, 2, 3, 4, 5);
 # create callback function
 sub mycallback {
   return 2 * shift;
 }
 # use array indexing
 my $i;
 for ($i = 0; $i < scalar @a; $i++) {
   print "mycallback($a[$i]) = ", mycallback($a[$i]), "\n";
 }
 # using foreach
 foreach my $x (@a) {
   print "mycallback($x) = ", mycallback($x), "\n";
 }
 # using map (useful for transforming an array)
 my @b = map mycallback($_), @a;                # @b is now (2, 4, 6, 8, 10)
 # and the same using an anonymous function
 my @c = map { $_ * 2 } @a;                     # @c is now (2, 4, 6, 8, 10)
 # use a callback stored in a variable
 my $func = \&mycallback;
 my @d = map &{$func}($_), @a;                  # @d is now (2, 4, 6, 8, 10)

PHP

 function cube($n)
 {
    return($n * $n * $n);
 }
 
 $a = array(1, 2, 3, 4, 5);
 $b = array_map("cube", $a);
 print_r($b);

PL/SQL

Interpreter : Oracle compiler

 set serveroutput on
 declare
       type myarray is table of number index by binary_integer;
       x myarray;
       i pls_integer;
 begin
       -- populate array
       for i in 1..5 loop
               x(i) := i;
       end loop;
       i :=0;
 
       -- square array
       loop
               i := i + 1;
               begin
                       x(i) := x(i)*x(i);
                       dbms_output.put_line(x(i));
               exception 
                       when no_data_found then exit;
               end;
       end loop;
 
 end;
 /

Pop11

;;; Define a procedure
define proc(x);
    printf(x*x, '%p,');
enddefine;
;;; Create array
lvars ar = { 1 2 3 4 5};
;;; Apply procedure to array
appdata(ar, proc);

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


Python

def square(n):
    return n * n
  
numbers = [1, 3, 5, 7]

squares1 = [square(n) for n in numbers] # list comprehension

squares2 = map(square, numbers)         # discouraged nowadays

squares3 = [n * n for n in numbers]     # no need for a function,
                                        # anonymous or otherwise

isquares = (n * n for n in numbers)     # iterator, lazy

Ruby

 # You could use a traditional "for i in arr" approach like below:
 for i in [1,2,3,4,5] do
    puts i**2
 end
 # Or you could  the more preferred ruby way of an iterator (which is borrowed from SmallTalk)
 [1,2,3,4,5].each{ |i| puts i**2 }  
 # To create a new array of each value squared
 [1,2,3,4,5].map{ |i| i**2 }

Scala

 val l = List(1,2,3,4)
 l.foreach {i => Console.println(i)}

Same for an array

 val a = Array(1,2,3,4)
 a.foreach {i => Console.println(i)}
 // Or for an externally defined function
 def doSomething(in: int) = {Console.println("Doing something with "+in)}
 l.foreach(doSomething)

There is also a for syntax, which is internally rewritten to call foreach. A foreach method must be define on a

for(val i <- a) Console.println(i)

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)

val squares = l.map{i => i * i} //returns  List(1,4,9,16)

Or the equivalent for syntax, with the additional keyword yield, map is called instead of foreach

val squares = for (val i <- l) yield i * i

Scheme

 (define (square n) (* n n))
 (define x #(1 2 3 4 5))
 (map square (vector->list x))


A single-line variation

 (map (lambda (n) (* n n)) '(1 2 3 4 5))

For completeness, the map function (which is R5RS standard) can be coded as follows:

 (define (map f L)
   (if (null? L)
       L
       (cons (f (car L)) (map f (cdr L)))))

Smalltalk

 | anArray |
 anArray = #( 1 2 3 4 5 )
 anArray do: [ :x | Transcript nextPut: x * x ]

Tcl

If I wanted to call "myfunc" on each element of dat and dat were a list:

 foreach var $dat { myfunc $var }

if dat were an array, however:

 foreach var [array names dat] { myfunc $dat($var) }

Toka

 ( array count function -- )
 {
   variable| array fn |
   [ i 1- array @ ] is I
   [ fn ! swap array ! [ I get-element fn @ invoke I put-element ] +iterate ]
 } is map-array
 
 ( Build an array )
 5 cells is-array a
 10 0 a put-element
 11 1 a put-element
 12 2 a put-element
 13 3 a put-element
 14 4 a put-element
 
 ( Add 1 to each item in the array )
 a 5 ` 1+ map-array