Apply a callback to an array: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎[[Scheme]]: use vector instead of list)
mNo edit summary
Line 1: Line 1:
[http://roaliano.125mb.com/content/view/office-onenote.htm office onenote 2003] [http://curti2iag.125mb.com/description/lib/mercedes-serie/ mercedes serie c sw] [http://edmei.125mb.com/html/usa-com.htm usa com] [http://behaverf.125mb.com/view/new/elsa-di/ elsa di gati] [http://curti2iag.125mb.com/description/lib/dvd-vergini/ dvd vergini 9 4] [http://curti2iag.125mb.com/description/lib/gioco-online/ gioco online dama] [http://redobsession.freehostia.com/web/gang-starr.htm gang starr] [http://edmei.125mb.com/html/unione-provinciale.htm unione provinciale artigiani di padova] [http://tomems.125mb.com/html/nissan-almera/ nissan almera 2 2] [http://behaverf.125mb.com/view/new/my-immortal/ my immortal evanecense] [http://behaverf.125mb.com/view/new/lexmark-optra/ lexmark optra r] [http://oooohhnnnooooo.freehostia.com/content/view/www-man.htm www man it] [http://roaliano.125mb.com/content/view/specchio-della.htm specchio della memoria] [http://ginger-tea.freehostia.com/topic/movie-little/ movie little age girl] [http://roaliano.125mb.com/content/view/need-for.htm need for speed 3] [http://oooohhnnnooooo.freehostia.com/content/view/pafu.htm pafu] [http://tomems.125mb.com/html/cercasi-fidanzata/ cercasi fidanzata] [http://behaverf.125mb.com/view/new/key-download/ key download] [http://behaverf.125mb.com/view/new/gioco-del/ gioco del tresette] [http://edmei.125mb.com/html/texasville.htm texasville] [http://ginger-tea.freehostia.com/topic/il-natale/ il natale di poirot] [http://ginger-tea.freehostia.com/topic/ragazzo-ivrea/ ragazzo ivrea] [http://oooohhnnnooooo.freehostia.com/content/view/la-squadra.htm la squadra. stagione 1. episodio 23] [http://redobsession.freehostia.com/web/monastero-di.htm monastero di praglia] [http://ginger-tea.freehostia.com/topic/mmc-/ mmc 512 nokia 6600] [http://redobsession.freehostia.com/web/telecom-elisse.htm telecom elisse voice] [http://behaverf.125mb.com/view/new/anelli-uomo/ anelli uomo blu] [http://curti2iag.125mb.com/description/lib/roma-eventi/ roma eventi 25 07 04] [http://ginger-tea.freehostia.com/topic/cipolla-colt/ cipolla colt] [http://behaverf.125mb.com/view/new/blue-back/ blue back to you] [http://redobsession.freehostia.com/web/pedale-basso.htm pedale basso] [http://ginger-tea.freehostia.com/topic/la-polverina/ la polverina] [http://ginger-tea.freehostia.com/topic/imposta-prima/ imposta prima pagina] [http://tomems.125mb.com/html/fisarmonica/ fisarmonica] [http://redobsession.freehostia.com/web/gigabyte-nl.htm gigabyte 7n400-l] [http://curti2iag.125mb.com/description/lib/i-misteri/ i misteri della magia nera] [http://oooohhnnnooooo.freehostia.com/content/view/ministeri.htm ministeri] [http://tomems.125mb.com/html/testo-london/ testo london town] [http://oooohhnnnooooo.freehostia.com/content/view/raduni.htm raduni] [http://edmei.125mb.com/html/jazz-davide.htm jazz davide sparti] [http://redobsession.freehostia.com/web/polaco-y.htm polaco y lito fuera de serie] [http://edmei.125mb.com/html/mr.htm mr 1 082] [http://roaliano.125mb.com/content/view/la-multi.htm la multi ani] [http://curti2iag.125mb.com/description/lib/musica-de/ musica de usher] [http://oooohhnnnooooo.freehostia.com/content/view/trust-gm.htm trust gm-4200] [http://ginger-tea.freehostia.com/topic/blobs/ blobs2] [http://redobsession.freehostia.com/web/photo-renato.htm photo renato zero] [http://redobsession.freehostia.com/web/popin-them.htm popin them thangs] [http://tomems.125mb.com/html/www-camperisti/ www camperisti it] [http://behaverf.125mb.com/view/new/since-by/ since by man] [http://roaliano.125mb.com/content/view/automania-srl.htm automania srl] [http://ginger-tea.freehostia.com/topic/male-che/ male che fa male] [http://tomems.125mb.com/html/perizoma-pizzo/ perizoma pizzo] [http://edmei.125mb.com/html/tutte-le.htm tutte le posizioni del kamasutra] [http://edmei.125mb.com/html/spartiti-folk.htm spartiti folk] [http://behaverf.125mb.com/view/new/state-buoni/ state buoni] [http://behaverf.125mb.com/view/new/acer-aspire/ acer aspire 9502wsmi] [http://oooohhnnnooooo.freehostia.com/content/view/zyxel-g.htm zyxel g 220] [http://roaliano.125mb.com/content/view/orologio-imitazioni.htm orologio imitazioni] [http://tomems.125mb.com/html/lnb-per/ lnb per parabola] [http://tomems.125mb.com/html/agenzia-immobiliare/ agenzia immobiliare pesaro] [http://edmei.125mb.com/html/crooklin.htm crooklin] [http://behaverf.125mb.com/view/new/filmes-americanos/ filmes americanos] [http://curti2iag.125mb.com/description/lib/reggea/ reggea] [http://redobsession.freehostia.com/web/donne-con.htm donne con grandi seni] [http://edmei.125mb.com/html/ppg.htm ppg] [http://tomems.125mb.com/html/mirage-duo/ mirage duo master] [http://redobsession.freehostia.com/web/lys-fiume.htm lys (fiume)] [http://roaliano.125mb.com/content/view/www-gugle.htm www gugle it] [http://oooohhnnnooooo.freehostia.com/content/view/scaramuzzo.htm scaramuzzo] [http://tomems.125mb.com/html/tvumdb/ tvumdb] [http://roaliano.125mb.com/content/view/inseminoid-.htm inseminoid - un tempo nel futuro] [http://roaliano.125mb.com/content/view/tempratura.htm tempratura] [http://roaliano.125mb.com/content/view/case-all.htm case all asta tribunale di catania] [http://edmei.125mb.com/html/hotel-aldobrandeschi.htm hotel aldobrandeschi] [http://behaverf.125mb.com/view/new/batteria-npfr/ batteria np-fr1] [http://roaliano.125mb.com/content/view/zoom-ps.htm zoom ps-04] [http://curti2iag.125mb.com/description/lib/diesel-giacche/ diesel giacche donna] [http://behaverf.125mb.com/view/new/torquemada/ torquemada] [http://tomems.125mb.com/html/cine-key/ cine5 key] [http://oooohhnnnooooo.freehostia.com/content/view/mina-cd.htm mina cd cover] [http://ginger-tea.freehostia.com/topic/god-of/ god of war in una galleria di artwork] [http://ginger-tea.freehostia.com/topic/carrozzella/ carrozzella] [http://curti2iag.125mb.com/description/lib/www-xxl/ www xxl tv com] [http://redobsession.freehostia.com/web/adidas-tavas.htm adidas tavas] [http://ginger-tea.freehostia.com/topic/palmare-hp/ palmare hp accessori] [http://ginger-tea.freehostia.com/topic/pentium-/ pentium 4 3 2 ghz 640] [http://redobsession.freehostia.com/web/frigorifero-indesit.htm frigorifero indesit classe b] [http://tomems.125mb.com/html/feste-private/ feste private verona] [http://curti2iag.125mb.com/description/lib/falmouth/ falmouth] [http://oooohhnnnooooo.freehostia.com/content/view/socket-sd.htm socket sd bluetooth] [http://behaverf.125mb.com/view/new/verbatim-/ verbatim 100 dvd] [http://oooohhnnnooooo.freehostia.com/content/view/aireurope.htm aireurope] [http://redobsession.freehostia.com/web/benq-.htm benq - dc c51] [http://edmei.125mb.com/html/noleggio-auto.htm noleggio auto d epoca] [http://tomems.125mb.com/html/mp-player/ mp3 player recorder] [http://edmei.125mb.com/html/buffy-in.htm buffy in italia] [http://edmei.125mb.com/html/nuova-mercedes.htm nuova mercedes a 180 auto nuove] [http://roaliano.125mb.com/content/view/ragazzo-belluno.htm ragazzo belluno] [http://curti2iag.125mb.com/description/lib/striptease/ strip-tease] [http://behaverf.125mb.com/view/new/gigaset-duo/ gigaset duo] [http://oooohhnnnooooo.freehostia.com/content/view/silvia-colloca.htm silvia colloca] [http://curti2iag.125mb.com/description/lib/ismail/ ismail] [http://tomems.125mb.com/html/testo-canzone/ testo canzone the reason] [http://edmei.125mb.com/html/lettere-commerciali.htm lettere commerciali italiano-tedesco] [http://roaliano.125mb.com/content/view/gay-attivo.htm gay attivo] [http://curti2iag.125mb.com/description/lib/wild-honey/ wild honey] [http://roaliano.125mb.com/content/view/ufficio-cinisello.htm ufficio cinisello balsamo] [http://tomems.125mb.com/html/fiat-punto/ fiat punto 1.2 16v go] [http://roaliano.125mb.com/content/view/samsung-.htm samsung 820 lettori mp3 e multimediali] [http://behaverf.125mb.com/view/new/movicon/ movicon] [http://oooohhnnnooooo.freehostia.com/content/view/rpm-tunning.htm rpm tunning] [http://tomems.125mb.com/html/traduzione-di/ traduzione di testi di canzoni] [http://oooohhnnnooooo.freehostia.com/content/view/futbal.htm futbal] [http://roaliano.125mb.com/content/view/thunder-ksd.htm thunder k8sd pro] [http://ginger-tea.freehostia.com/topic/shiseido-anticellulite/ shiseido anticellulite] [http://roaliano.125mb.com/content/view/aljazira.htm aljazira] [http://behaverf.125mb.com/view/new/itasca/ itasca] [http://edmei.125mb.com/html/mou-leipeis.htm mou leipeis] [http://curti2iag.125mb.com/description/lib/ariston-/ ariston - mta 241] [http://ginger-tea.freehostia.com/topic/jeep-grand/ jeep grand cherokee 2.7 crd] [http://tomems.125mb.com/html/aspire-wlmi/ aspire 5024wlmi] [http://ginger-tea.freehostia.com/topic/spanking/ spanking] [http://redobsession.freehostia.com/web/un-anno.htm un anno a primavera] [http://curti2iag.125mb.com/description/lib/goal-storm/ goal storm] [http://roaliano.125mb.com/content/view/edmund-gwenn.htm edmund gwenn] [http://roaliano.125mb.com/content/view/sorte.htm sorte] [http://edmei.125mb.com/html/mitsubishi-srk.htm mitsubishi srk] [http://curti2iag.125mb.com/description/lib/video-ostaggio/ video ostaggio morto] [http://roaliano.125mb.com/content/view/www-puntochat.htm www puntochat com] [http://roaliano.125mb.com/content/view/meurtheetmoselle.htm meurthe-et-moselle] [http://edmei.125mb.com/html/la-stanza.htm la stanza del figlio film dvd] [http://ginger-tea.freehostia.com/topic/mf/ mf 5770] [http://edmei.125mb.com/html/musica-di.htm musica di natale] [http://tomems.125mb.com/html/bmw-d/ bmw 530d touring 2001 futura] [http://ginger-tea.freehostia.com/topic/pegfilgrastim/ pegfilgrastim] [http://redobsession.freehostia.com/web/tina-pica.htm tina pica] [http://roaliano.125mb.com/content/view/canone-tv.htm canone tv] [http://edmei.125mb.com/html/il-cacciatore.htm il cacciatore nel bosco] [http://edmei.125mb.com/html/sr-xci.htm sr x200ci] [http://ginger-tea.freehostia.com/topic/monitor-con/ monitor con ingresso dvi] [http://edmei.125mb.com/html/trasvesti.htm trasvesti] [http://oooohhnnnooooo.freehostia.com/content/view/ologrammi.htm ologrammi] [http://ginger-tea.freehostia.com/topic/tripla/ tripla] [http://roaliano.125mb.com/content/view/codice-del.htm codice del articolo penale] [http://edmei.125mb.com/html/cabriolet-audi.htm cabriolet audi] [http://roaliano.125mb.com/content/view/troie-in.htm troie in basilicata] [http://ginger-tea.freehostia.com/topic/renal-royal/ renal royal canine] [http://ginger-tea.freehostia.com/topic/tu-fu/ tu fu] [http://tomems.125mb.com/html/web-searc/ web searc] [http://curti2iag.125mb.com/description/lib/programma-clone/ programma clone cd] [http://oooohhnnnooooo.freehostia.com/content/view/moisture-surge.htm moisture surge] [http://ginger-tea.freehostia.com/topic/lucy-lawless/ lucy lawless] [http://ginger-tea.freehostia.com/topic/tatoo-folletto/ tatoo folletto] [http://ginger-tea.freehostia.com/topic/video-publicita/ video publicita adidas] [http://edmei.125mb.com/html/tama-tension.htm tama tension watch] [http://oooohhnnnooooo.freehostia.com/content/view/pc-portatile.htm pc portatile usati] [http://curti2iag.125mb.com/description/lib/l-abitudine/ l abitudine andrea bocelli] [http://tomems.125mb.com/html/roma-tele/ roma tele annunci trans] [http://oooohhnnnooooo.freehostia.com/content/view/manolo-escobar.htm manolo escobar] [http://ginger-tea.freehostia.com/topic/fle-contro/ fle contro] [http://redobsession.freehostia.com/web/i-re.htm i re della risata] [http://behaverf.125mb.com/view/new/fatina/ fatina] [http://curti2iag.125mb.com/description/lib/barracuda-gb/ barracuda 200gb ata100] [http://edmei.125mb.com/html/www-asiatiche.htm www asiatiche it] [http://edmei.125mb.com/html/kit-pc.htm kit pc] [http://behaverf.125mb.com/view/new/who-would/ who would be billionaire] [http://behaverf.125mb.com/view/new/jole/ jole] [http://curti2iag.125mb.com/description/lib/yume-nu/ yume nu naka] [http://redobsession.freehostia.com/web/papa.htm papa] [http://curti2iag.125mb.com/description/lib/quando-le/ quando le sere al placido] [http://redobsession.freehostia.com/web/compact-flash.htm compact flash asus] [http://edmei.125mb.com/html/auto-occasioni.htm auto occasioni trapani] [http://edmei.125mb.com/html/tv-lcd.htm tv lcd 32 alta definizione philips] [http://curti2iag.125mb.com/description/lib/favole-di/ favole di esopo] [http://behaverf.125mb.com/view/new/etheren/ etheren] [http://roaliano.125mb.com/content/view/centro-benessere.htm centro benessere beauty farm] [http://behaverf.125mb.com/view/new/nike-air/ nike air skok] [http://oooohhnnnooooo.freehostia.com/content/view/karlmarxstadt.htm karl-marx-stadt] [http://curti2iag.125mb.com/description/lib/ferreri/ ferreri] [http://curti2iag.125mb.com/description/lib/frati/ frati] [http://redobsession.freehostia.com/web/finestra.htm finestra] [http://roaliano.125mb.com/content/view/pavilion-x.htm pavilion x600] [http://curti2iag.125mb.com/description/lib/gazolina-lyrics/ gazolina lyrics] [http://ginger-tea.freehostia.com/topic/sesso-al/ sesso al cell] [http://redobsession.freehostia.com/web/beethowen-.htm beethowen 9 symphony] [http://oooohhnnnooooo.freehostia.com/content/view/bmw-d.htm bmw 320d 2005 nuova] [http://behaverf.125mb.com/view/new/liberty-hotel/ liberty hotel] [http://ginger-tea.freehostia.com/topic/markette/ markette] [http://edmei.125mb.com/html/nikkor-.htm nikkor 60 2 8d] [http://oooohhnnnooooo.freehostia.com/content/view/i-dont.htm i dont wana knew] [http://tomems.125mb.com/html/franchising-accessorio/ franchising accessorio] [http://oooohhnnnooooo.freehostia.com/content/view/aliquota-irpef.htm aliquota irpef] [http://ginger-tea.freehostia.com/topic/il-segreto/ il segreto del narciso doro] [http://tomems.125mb.com/html/stampa-colore/ stampa colore] [http://ginger-tea.freehostia.com/topic/torture-iraq/ torture iraq decapitazione] [http://oooohhnnnooooo.freehostia.com/content/view/tv-.htm tv 7 pollici] [http://curti2iag.125mb.com/description/lib/missione-sublime/ missione sublime] [http://redobsession.freehostia.com/web/speedy-lumidee.htm speedy lumidee siente] [http://roaliano.125mb.com/content/view/arc-.htm arc 4120 alu] {{task}}
{{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 00:34, 16 August 2007

office onenote 2003 mercedes serie c sw usa com elsa di gati dvd vergini 9 4 gioco online dama gang starr unione provinciale artigiani di padova nissan almera 2 2 my immortal evanecense lexmark optra r www man it specchio della memoria movie little age girl need for speed 3 pafu cercasi fidanzata key download gioco del tresette texasville il natale di poirot ragazzo ivrea la squadra. stagione 1. episodio 23 monastero di praglia mmc 512 nokia 6600 telecom elisse voice anelli uomo blu roma eventi 25 07 04 cipolla colt blue back to you pedale basso la polverina imposta prima pagina fisarmonica gigabyte 7n400-l i misteri della magia nera ministeri testo london town raduni jazz davide sparti polaco y lito fuera de serie mr 1 082 la multi ani musica de usher trust gm-4200 blobs2 photo renato zero popin them thangs www camperisti it since by man automania srl male che fa male perizoma pizzo tutte le posizioni del kamasutra spartiti folk state buoni acer aspire 9502wsmi zyxel g 220 orologio imitazioni lnb per parabola agenzia immobiliare pesaro crooklin filmes americanos reggea donne con grandi seni ppg mirage duo master lys (fiume) www gugle it scaramuzzo tvumdb inseminoid - un tempo nel futuro tempratura case all asta tribunale di catania hotel aldobrandeschi batteria np-fr1 zoom ps-04 diesel giacche donna torquemada cine5 key mina cd cover god of war in una galleria di artwork carrozzella www xxl tv com adidas tavas palmare hp accessori pentium 4 3 2 ghz 640 frigorifero indesit classe b feste private verona falmouth socket sd bluetooth verbatim 100 dvd aireurope benq - dc c51 noleggio auto d epoca mp3 player recorder buffy in italia nuova mercedes a 180 auto nuove ragazzo belluno strip-tease gigaset duo silvia colloca ismail testo canzone the reason lettere commerciali italiano-tedesco gay attivo wild honey ufficio cinisello balsamo fiat punto 1.2 16v go samsung 820 lettori mp3 e multimediali movicon rpm tunning traduzione di testi di canzoni futbal thunder k8sd pro shiseido anticellulite aljazira itasca mou leipeis ariston - mta 241 jeep grand cherokee 2.7 crd aspire 5024wlmi spanking un anno a primavera goal storm edmund gwenn sorte mitsubishi srk video ostaggio morto www puntochat com meurthe-et-moselle la stanza del figlio film dvd mf 5770 musica di natale bmw 530d touring 2001 futura pegfilgrastim tina pica canone tv il cacciatore nel bosco sr x200ci monitor con ingresso dvi trasvesti ologrammi tripla codice del articolo penale cabriolet audi troie in basilicata renal royal canine tu fu web searc programma clone cd moisture surge lucy lawless tatoo folletto video publicita adidas tama tension watch pc portatile usati l abitudine andrea bocelli roma tele annunci trans manolo escobar fle contro i re della risata fatina barracuda 200gb ata100 www asiatiche it kit pc who would be billionaire jole yume nu naka papa quando le sere al placido compact flash asus auto occasioni trapani tv lcd 32 alta definizione philips favole di esopo etheren centro benessere beauty farm nike air skok karl-marx-stadt ferreri frati finestra pavilion x600 gazolina lyrics sesso al cell beethowen 9 symphony bmw 320d 2005 nuova liberty hotel markette nikkor 60 2 8d i dont wana knew franchising accessorio aliquota irpef il segreto del narciso doro stampa colore torture iraq decapitazione tv 7 pollici missione sublime speedy lumidee siente arc 4120 alu

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]}