Apply a callback to an array: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
Line 1: Line 1:
{{task}}
[http://betheresa.t35.com/text/directory/yashica-fx/ yashica fx 3 super] [http://dabeutle.t35.com/content/view/pacioli.htm pacioli] [http://fergus-mac.somee.com/description/lib/obbsesion/ obbsesion] [http://quotes-girl.somee.com/content/view/massaggio-anticellulite/ massaggio anticellulite] [http://jututor.125mb.com/lib/inchieste-commerciali/ inchieste commerciali e industriali] [http://nationavce.somee.com/library/html/videos-fotos/ videos fotos dibujos] [http://coarmago.freeweb7.com/library/html/blond-record.htm blond record] [http://nationavce.somee.com/library/html/guida-di/ guida di maya] [http://fergus-mac.somee.com/description/lib/bisex-milano/ bisex milano] [http://kiboukni.125mb.com/web/estratti-di/ estratti di radice] [http://lamcgie.t35.com/web/direttiva-.htm direttiva 91 689 cee] [http://nationavce.somee.com/library/html/suore/ suore] [http://nairoz.somee.com/img/styles/pisa-teatro/ pisa teatro terapia] [http://thegoogly.somee.com/view/new/scheda-madre.htm scheda madre asus scsi] [http://itgurney.t35.com/view/new/rio-/ rio - carbon 5gb] [http://peter-land.somee.com/images/small/test-di.htm test di mutagenesi] [http://flheddina.t35.com/web/birch-society/ birch society] [http://viemalin.freeweb7.com/resources/articles/www-giles.htm www giles it] [http://nationavce.somee.com/library/html/kelly-chen/ kelly chen] [http://rimarsh.t35.com/images/small/treviso-singole.htm treviso singole] [http://jututor.125mb.com/lib/yu-gi/ yu gi oh disegni da colorare] [http://brrezab.freeweb7.com/img/styles/sandy-pelada.htm sandy pelada] [http://yourorus.somee.com/data/multifunzione-laser.htm multifunzione laser colori scanner] [http://nairoz.somee.com/img/styles/fibro/ fibro-] [http://flheddina.t35.com/web/sodimm-ddr/ sodimm ddr pc2100 non-ecc] [http://viemalin.freeweb7.com/resources/articles/troie-lecce.htm troie lecce] [http://flheddina.t35.com/web/vittoria-in/ vittoria in provincia di ragusa] [http://jututor.125mb.com/lib/jvc-dr/ jvc dr mh 50 se] [http://lensman.somee.com/html/free-foto/ free foto sex] [http://quotes-girl.somee.com/content/view/innovazione-gov/ innovazione gov it] [http://am-i-bird.somee.com/img/styles/adsl-modem.htm adsl modem internet gateway router] [http://brrezab.freeweb7.com/img/styles/sharp-aquos.htm sharp aquos 37] [http://nationavce.somee.com/library/html/fabrizio/ fabrizio] [http://davelovesyou.somee.com/library/html/gps-tom/ gps tom tom per nokia 6630] [http://quotes-girl.somee.com/content/view/registratore-cassette/ registratore cassette] [http://betheresa.t35.com/text/directory/lampadine-risparmio/ lampadine risparmio energetico] [http://itgurney.t35.com/view/new/codici-carte/ codici carte servizi omnitel] [http://de-der.somee.com/library/html/blue-car.htm blue car wash] [http://nationavce.somee.com/library/html/il-cavaliere/ il cavaliere della valle solitaria] [http://kiboukni.125mb.com/web/vasco-rssi/ vasco rssi] [http://trocterli.t35.com/img/styles/www-pesca/ www pesca it] [http://coarmago.freeweb7.com/library/html/auto-noleggio.htm auto noleggio arles] [http://betheresa.t35.com/text/directory/grego/ grego] [http://dj-deus.somee.com/lib/megama.htm megama] [http://thegoogly.somee.com/view/new/pietramelara.htm pietramelara] [http://itgurney.t35.com/view/new/googlre/ googlre] [http://fergus-mac.somee.com/description/lib/trucchi-crusader/ trucchi crusader italiano] [http://itgurney.t35.com/view/new/elena-rosenkova/ elena rosenkova] [http://luallard.t35.com/html/tv-color/ tv color lcd 17] [http://lamcgie.125mb.com/html/amstrad-lcd.htm amstrad lcd 42] [http://lamcgie.125mb.com/html/fotocopiatrici-e.htm fotocopiatrici e fax] [http://fergus-mac.somee.com/description/lib/fd-usb/ fd usb] [http://thegoogly.somee.com/view/new/mercedes-e.htm mercedes e 230 avantgarde] [http://betheresa.t35.com/text/directory/elisa-foto/ elisa foto] [http://flheddina.t35.com/web/shitt/ shitt] [http://itgurney.t35.com/view/new/caleffi/ caleffi] [http://de-der.somee.com/library/html/minestra-di.htm minestra di pisello e carciofo] [http://lamcgie.t35.com/web/spartito-gianna.htm spartito gianna nannini sei anima] [http://dabeutle.t35.com/content/view/togni-luna.htm togni luna] [http://madavid.t35.com/html/exilim-ex/ exilim ex s 3 casio] [http://lakitsmi.freeweb7.com/web/dubayy/ dubayy] [http://fergus-mac.somee.com/description/lib/space-truckers/ space truckers] [http://davelovesyou.somee.com/library/html/www-buongusto/ www buongusto com] [http://trocterli.t35.com/img/styles/salome/ salome] [http://jututor.125mb.com/lib/pietra-ollare/ pietra ollare] [http://jututor.125mb.com/lib/gioiello-perla/ gioiello perla] [http://itgurney.t35.com/view/new/modelli-navali/ modelli navali in legno] [http://itgurney.t35.com/view/new/mitsubishi-pajero/ mitsubishi pajero sport] [http://flheddina.t35.com/web/carrello-acciaio/ carrello acciaio] [http://am-i-bird.somee.com/img/styles/la-madonnina.htm la madonnina dai riccioli d oro] [http://jedillar.125mb.com/resources/articles/fasi-di/ fasi di venere] [http://itgurney.t35.com/view/new/gabbia-per/ gabbia per uccelli] [http://lamcgie.125mb.com/html/chaise-longue.htm chaise longue le corbusier] [http://dj-deus.somee.com/lib/tv-acer.htm tv acer 20] [http://fawarfo.freeweb7.com/topic/nissan-micra.htm nissan micra km 0] [http://peter-land.somee.com/images/small/volvo-.htm volvo 240 super polar] [http://itgurney.t35.com/view/new/spartiti-masini/ spartiti masini] [http://de-der.somee.com/library/html/giampiero-galeazzi.htm giampiero galeazzi] [http://quotes-girl.somee.com/content/view/quello-che/ quello che volevi] [http://fergus-mac.somee.com/description/lib/lultimo-mercenario/ lultimo mercenario] [http://rihelm.125mb.com/img/styles/concorsi-universita/ concorsi universita rimini] [http://davelovesyou.somee.com/library/html/una-volta/ una volta il west] [http://flheddina.t35.com/web/nona-sinfonie/ nona sinfonie] [http://flheddina.t35.com/web/lupo-auto/ lupo auto] [http://viemalin.freeweb7.com/resources/articles/foto-trans.htm foto trans bisex] [http://lensman.somee.com/html/drago-stea/ drago stea] [http://trocterli.t35.com/img/styles/freek-a/ freek a leek] [http://thegoogly.somee.com/view/new/palermo-new.htm palermo new york biglietti aerei] [http://betheresa.t35.com/text/directory/ballad-pour/ ballad pour adeline] [http://trocterli.t35.com/img/styles/gioco-porno/ gioco porno] [http://lakitsmi.freeweb7.com/web/i-proibiti/ i proibiti amori di tokyo] [http://luallard.t35.com/html/sagarmatha/ sagarmatha] [http://viemalin.freeweb7.com/resources/articles/un-pugno.htm un pugno di polvere] [http://viemalin.freeweb7.com/resources/articles/let-s.htm let s get it started b e p] [http://jututor.125mb.com/lib/ospedale-valduce/ ospedale valduce] [http://lamcgie.t35.com/web/orecchino-piercing.htm orecchino piercing] [http://nairoz.somee.com/img/styles/tetta-enormi/ tetta enormi] [http://jututor.125mb.com/lib/notizie-sulle/ notizie sulle foto] [http://madavid.t35.com/html/radeon-/ radeon 9600 xt 256] [http://rihelm.125mb.com/img/styles/tancredi-rossini/ tancredi rossini] [http://luallard.t35.com/html/ntsc-video/ ntsc video] [http://madavid.t35.com/html/ef-mm/ ef 70-200mm] [http://kiboukni.125mb.com/web/professional-care/ professional care 7500] [http://itgurney.t35.com/view/new/sfondi-citta/ sfondi citta] [http://luallard.t35.com/html/cuffia-dj/ cuffia dj stanton] [http://madavid.t35.com/html/suonerie-polifoniche/ suonerie polifoniche da comporre] [http://rihelm.125mb.com/img/styles/teatro-degli/ teatro degli arcimboldi] [http://ouquaite.freeweb7.com/img/styles/gigi-e/ gigi e andrea] [http://luallard.t35.com/html/gif-animate/ gif animate hentai] [http://ouquaite.freeweb7.com/img/styles/lunanera/ lunanera] [http://lensman.somee.com/html/google-i/ google i] [http://itgurney.t35.com/view/new/videos-porno/ videos porno de michell vieth] [http://peter-land.somee.com/images/small/disegni-da.htm disegni da colorare sulla befana] [http://viemalin.freeweb7.com/resources/articles/er-cavaliere.htm er cavaliere nero proietti] [http://quotes-girl.somee.com/content/view/dual-processor/ dual processor workstation] [http://madavid.t35.com/html/decoder-wireless/ decoder wireless] [http://nairoz.somee.com/img/styles/programmatore-as/ programmatore as 400 (regione lombardia - bergamo provincia)] [http://lensman.somee.com/html/premier-ds/ premier ds-5330] [http://dabeutle.t35.com/content/view/christian-dior.htm christian dior fahrenheit] [http://trocterli.t35.com/img/styles/dieta-/ dieta 1200 caloria] [http://madavid.t35.com/html/tania-cagnotto/ tania cagnotto nuda] [http://madavid.t35.com/html/canon-ip/ canon ip1600 cartuccia nero] [http://am-i-bird.somee.com/img/styles/vedere-fica.htm vedere fica] [http://ouquaite.freeweb7.com/img/styles/wwwauto/ wwwauto] [http://lakitsmi.freeweb7.com/web/nvidia-geforce/ nvidia geforce 6800] [http://lakitsmi.freeweb7.com/web/batmam/ batmam] [http://jututor.125mb.com/lib/laura-pausini/ laura pausini strani amori] [http://dj-deus.somee.com/lib/come-fare.htm come fare allungare il pene] [http://ouquaite.freeweb7.com/img/styles/gina-ryder/ gina ryder] [http://yourorus.somee.com/data/assistenza-inno.htm assistenza inno hit arezzo] [http://ouquaite.freeweb7.com/img/styles/la-notte/ la notte della taranta] [http://lamcgie.125mb.com/html/bouwling.htm bouwling] [http://lensman.somee.com/html/www-posiciones/ www posiciones com co] [http://rihelm.125mb.com/img/styles/decespugliatore-/ decespugliatore 4 tempi] [http://rimarsh.t35.com/images/small/agatha-christie.htm agatha christie collection. vol. 3] [http://de-der.somee.com/library/html/strategia-marketing.htm strategia marketing] [http://madavid.t35.com/html/tha-reason/ tha reason hoobastank] [http://fawarfo.freeweb7.com/topic/toyota-.htm toyota corolla 1.4 16v 3p. sol] [http://brrezab.freeweb7.com/img/styles/la-nasa.htm la nasa] [http://lakitsmi.freeweb7.com/web/jesse/ jesse] [http://am-i-bird.somee.com/img/styles/imovane.htm imovane] [http://de-der.somee.com/library/html/kennedy-et.htm kennedy et moi] [http://dj-deus.somee.com/lib/vasco-rossi.htm vasco rossi buoni e cattivi] [http://quotes-girl.somee.com/content/view/dustin-hoffman/ dustin hoffman] [http://madavid.t35.com/html/gig-d/ gig d agostino] [http://lensman.somee.com/html/liz-hurley/ liz hurley] [http://fawarfo.freeweb7.com/topic/dante-alighieri.htm dante alighieri] [http://dj-deus.somee.com/lib/a-spasso.htm a spasso con la morte] [http://yourorus.somee.com/data/dama-su.htm dama su scacchiera] [http://kiboukni.125mb.com/web/gai-mattiolo/ gai mattiolo - thats amore lui] [http://yourorus.somee.com/data/vorbei-christina.htm vorbei christina] [http://thegoogly.somee.com/view/new/dsc-v.htm dsc v1 sony] [http://coarmago.freeweb7.com/library/html/steimberg-cubase.htm steimberg cubase vst] [http://fawarfo.freeweb7.com/topic/codici-sbloco.htm codici sbloco nec e228] [http://viemalin.freeweb7.com/resources/articles/polize-assicurative.htm polize assicurative] [http://fawarfo.freeweb7.com/topic/william-basinski.htm william basinski] [http://flheddina.t35.com/web/verona-lumache/ verona lumache] [http://fawarfo.freeweb7.com/topic/la-figlia.htm la figlia del reggimento] [http://thegoogly.somee.com/view/new/giurisprudenza-appunti.htm giurisprudenza appunti] [http://rimarsh.t35.com/images/small/camera-housing.htm camera housing] [http://rihelm.125mb.com/img/styles/windows-/ windows 2003 srv std] [http://quotes-girl.somee.com/content/view/climatizzatore-portatile/ climatizzatore portatile split] [http://lensman.somee.com/html/km-renault/ km0 renault auto km 0] [http://trocterli.t35.com/img/styles/riduttore-seggiolino/ riduttore seggiolino bimbo] [http://de-der.somee.com/library/html/lola-la.htm lola la fattoria] [http://coarmago.freeweb7.com/library/html/voli-aerei.htm voli aerei new york] [http://rimarsh.t35.com/images/small/stranded.htm stranded] [http://dabeutle.t35.com/content/view/philips-voice.htm philips voice tracer 7880] [http://am-i-bird.somee.com/img/styles/musicanova.htm musicanova] [http://nationavce.somee.com/library/html/la-vita/ la vita segreta di ian fleming] [http://fergus-mac.somee.com/description/lib/traduzione-testo/ traduzione testo she will be loved] [http://lakitsmi.freeweb7.com/web/il-box/ il box di jack ryan] [http://itgurney.t35.com/view/new/da-vinci/ da vinci leonardo] [http://kiboukni.125mb.com/web/lacie-gb/ lacie 160gb esterno] [http://itgurney.t35.com/view/new/miracolo-a/ miracolo a milano] [http://betheresa.t35.com/text/directory/topless-vacanza/ topless vacanza mare] [http://coarmago.freeweb7.com/library/html/delonghi.htm delonghi 46] [http://nationavce.somee.com/library/html/oregon-scientific/ oregon scientific basic] [http://yourorus.somee.com/data/googl.htm googl] [http://am-i-bird.somee.com/img/styles/luly-bosa.htm luly bosa] [http://ouquaite.freeweb7.com/img/styles/exilim-pro/ exilim pro casio] [http://dabeutle.t35.com/content/view/turismo-sardegna.htm turismo sardegna] [http://lamcgie.t35.com/web/luesi.htm luesi] [http://thegoogly.somee.com/view/new/immigrationexpert-com.htm immigrationexpert com] [http://am-i-bird.somee.com/img/styles/big-monei.htm big monei] [http://yourorus.somee.com/data/la-signora.htm la signora di montecarlo] [http://flheddina.t35.com/web/designjet/ designjet 70] [http://madavid.t35.com/html/virtua-striker/ virtua striker 2] [http://lakitsmi.freeweb7.com/web/ritornerai-bruno/ ritornerai bruno lauzi] [http://jututor.125mb.com/lib/ochii-tai/ ochii tai] [http://peter-land.somee.com/images/small/www-angela.htm www angela melillo it] [http://rihelm.125mb.com/img/styles/microsoft-office/ microsoft office professional edition] [http://trocterli.t35.com/img/styles/diras-que/ diras que estoy loco] [http://quotes-girl.somee.com/content/view/daniella-rush/ daniella rush] [http://itgurney.t35.com/view/new/caratteristiche-tecniche/ caratteristiche tecniche di telecamere] [http://thegoogly.somee.com/view/new/veronica-maya.htm veronica maya] [http://lamcgie.t35.com/web/pda-compact.htm pda compact flash] [http://luallard.t35.com/html/konica-/ konica 1216 toner] [http://dabeutle.t35.com/content/view/batteria-elettronica.htm batteria elettronica con pad] [http://madavid.t35.com/html/corvi/ corvi] {{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 22:53, 22 August 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