Apply a callback to an array: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
Line 1: Line 1:
[http://unremig.110mb.com/sfruttamento/ sfruttamento] [http://trene-von-anty.110mb.com/description/kingston-.htm kingston 512 mb] [http://blue-olusha.110mb.com/library/not-yet/ not yet] [http://stitchesnglue.110mb.com/box-.htm box 3 5 hd] [http://unremig.110mb.com/finanziamento-cuneo/ finanziamento cuneo] [http://forever-your.110mb.com/data/ormoni-androgeni.htm ormoni androgeni] [http://ultra-creator.110mb.com/articles/grande-fratello.htm grande fratello sito uffuciale] [http://nationavce.110mb.com/view/prestito-chieti.htm prestito chieti] [http://trouble166.110mb.com/mariagrazia.htm mariagrazia] [http://ultra-creator.110mb.com/articles/europe-travel.htm europe travel] [http://gekijuls.110mb.com/ot/ ot 525] [http://lazythoughts.110mb.com/lib/siemens-suoneria/ siemens suoneria cellulare] [http://ultra-creator.110mb.com/articles/dowload-midi.htm dowload midi] [http://dialed.110mb.com/small/chatta-con/ chatta con ragazze nude] [http://unremig.110mb.com/gabry-ponte/ gabry ponte figli pitagora] [http://funk-mastah-ion.110mb.com/data/sutra-diamante.htm sutra diamante] [http://book-wench.110mb.com/text/polar-si/ polar s810i] [http://ultra-creator.110mb.com/articles/mp-player.htm mp3 player wireless] [http://trouble166.110mb.com/torreciudad.htm torreciudad] [http://sneezingpops.110mb.com/rok-and/ rok and roll] [http://some-omeelse.110mb.com/data/ibi-srl.htm ibi srl] [http://some-omeelse.110mb.com/data/ia-riproduzione.htm ia riproduzione nell essere umano] [http://stitchesnglue.110mb.com/isola-di.htm isola di ischia] [http://gekijuls.110mb.com/coup-de/ coup de foudre] [http://some-omeelse.110mb.com/data/dispensatore-acqua.htm dispensatore acqua] [http://gekijuls.110mb.com/virgine/ virgine] [http://unremig.110mb.com/pavarotti-domingo/ pavarotti domingo carreras three tenors] [http://gekijuls.110mb.com/site-blog/ site blog deejay it] [http://gekijuls.110mb.com/incontro-single/ incontro single incontrare donna] [http://book-wench.110mb.com/text/translator-pro/ translator pro 9] [http://sneezingpops.110mb.com/van-aken/ van aken piet] [http://sneezingpops.110mb.com/la-principessa/ la principessa delle ostriche] [http://funk-mastah-ion.110mb.com/data/toy-story.htm toy story giocattoli] [http://sneezingpops.110mb.com/decespugliatori-alpina/ decespugliatori alpina elettrici] [http://funk-mastah-ion.110mb.com/data/www-milo.htm www milo ventimiglia it] [http://unremig.110mb.com/classifica-campionato/ classifica campionato serie b] [http://yeeden.110mb.com/data/mutande-sporche/ mutande sporche] [http://slavkamolot.110mb.com/library/olympus-ds/ olympus ds2] [http://yeeden.110mb.com/data/infonavit-gob/ infonavit gob mx] [http://forever-your.110mb.com/data/raymarine-st.htm raymarine st 40] [http://lazythoughts.110mb.com/lib/ragazzo-malta/ ragazzo malta] [http://ultra-creator.110mb.com/articles/danza-italiana.htm danza italiana] [http://trouble166.110mb.com/i-am.htm i am a woman in love mp3] [http://sneezingpops.110mb.com/sade-flow/ sade flow mp3] [http://gekijuls.110mb.com/xt/ xt 660] [http://sister-sunshine.110mb.com/html/wez-to/ wez to poczuj onar] [http://slavkamolot.110mb.com/library/legge/ legge 1933] [http://ultra-creator.110mb.com/articles/gruppi-musicali.htm gruppi musicali anni 70 opera] [http://blue-olusha.110mb.com/library/caso-moro/ caso moro] [http://stitchesnglue.110mb.com/ddr-mhz.htm ddr 400mhz pc3200] [http://blue-olusha.110mb.com/library/hatene/ hatene] [http://lazythoughts.110mb.com/lib/teac-h/ teac h500] [http://yeeden.110mb.com/data/polistirolo-brescia/ polistirolo brescia] [http://yeeden.110mb.com/data/ricchi/ ricchi] [http://stitchesnglue.110mb.com/monitor-plasma.htm monitor plasma 42] [http://sister-sunshine.110mb.com/html/dance-mat/ dance mat console accessori] [http://gekijuls.110mb.com/la-celestina/ la celestina] [http://funk-mastah-ion.110mb.com/data/recorder-disk.htm recorder disk] [http://olikka.110mb.com/library/lela-porno.htm lela porno] [http://slavkamolot.110mb.com/library/i-gangsters/ i gangsters del fuoco] [http://ultra-creator.110mb.com/articles/vendita-case.htm vendita case verona] [http://blue-olusha.110mb.com/library/esercito-difesa/ esercito difesa it] [http://slavkamolot.110mb.com/library/provveditorato-cosenza/ provveditorato cosenza] [http://olikka.110mb.com/library/quello-strano.htm quello strano sentimento] [http://nationavce.110mb.com/view/lazzo.htm lazzo] [http://funk-mastah-ion.110mb.com/data/home-theatre.htm home theatre con dvd recorder pioneer] [http://mouse-zae.110mb.com/dvd-recordervcr.htm dvd recordervcr] [http://blue-olusha.110mb.com/library/travelmate/ travelmate 200] [http://dialed.110mb.com/small/buona-vita/ buona vita gigi d] [http://funk-mastah-ion.110mb.com/data/da-godere.htm da godere] [http://mouse-zae.110mb.com/ericsson-antenne.htm ericsson antenne] [http://unremig.110mb.com/televisori-/ televisori 40 samsung] [http://unremig.110mb.com/acer-alw/ acer al2671w 26] [http://sister-sunshine.110mb.com/html/piccolo-uomo/ piccolo uomo mia martini] [http://unremig.110mb.com/stephanie-mc/ stephanie mc mahon] [http://mouse-zae.110mb.com/societa-post.htm societa post industriale] [http://dialed.110mb.com/small/maxtor-hd/ maxtor hd] [http://gekijuls.110mb.com/rjeka-croazia/ rjeka croazia] [http://sneezingpops.110mb.com/makadam/ makadam] [http://some-omeelse.110mb.com/data/cartier-rem.htm cartier rem] [http://lazythoughts.110mb.com/lib/fomalhaut/ fomalhaut] [http://forever-your.110mb.com/data/huge-boobs.htm huge boobs] [http://stitchesnglue.110mb.com/snow-on.htm snow on the sahara] [http://stitchesnglue.110mb.com/javel-quest.htm javel quest] [http://slavkamolot.110mb.com/library/nokia-telefonia/ nokia7260 telefonia] [http://unremig.110mb.com/lepidium/ lepidium] [http://lazythoughts.110mb.com/lib/mp-rds/ mp3 rds impianti hifi] [http://yeeden.110mb.com/data/canon-eos/ canon eos digital rebel xt slr] [http://gekijuls.110mb.com/har-disk/ har disk esterno lacie 250] [http://some-omeelse.110mb.com/data/viva-voce.htm viva voce auto bluetooth] [http://sister-sunshine.110mb.com/html/abigail-toyne/ abigail toyne] [http://sister-sunshine.110mb.com/html/yeti-sports/ yeti sports 9] [http://lazythoughts.110mb.com/lib/ricky-martin/ ricky martin livin la vida loca] [http://gekijuls.110mb.com/fotocopiatrice-konica/ fotocopiatrice konica] [http://gekijuls.110mb.com/plunkett-macleane/ plunkett macleane] [http://sneezingpops.110mb.com/acer-aspire/ acer aspire 17 bluetooth] [http://forever-your.110mb.com/data/vieht-video.htm vieht video] [http://ultra-creator.110mb.com/articles/pitesti.htm pitesti] [http://sneezingpops.110mb.com/annuncio-lavoro/ annuncio lavoro mantova] [http://nationavce.110mb.com/view/mahjong-towers.htm mahjong towers] [http://ultra-creator.110mb.com/articles/sava-vita.htm sava vita beghelli] [http://olikka.110mb.com/library/single-it.htm single it] [http://sister-sunshine.110mb.com/html/le-sensitive/ le sensitive] [http://forever-your.110mb.com/data/ati.htm ati 9550 256] [http://trouble166.110mb.com/testo-lo.htm testo lo stara] [http://some-omeelse.110mb.com/data/sora.htm sora] [http://dialed.110mb.com/small/adidas-/ adidas monaco] [http://mouse-zae.110mb.com/drown-in.htm drown in my own tears] [http://mouse-zae.110mb.com/sascha-del.htm sascha del bb] [http://trene-von-anty.110mb.com/description/veterinari-ravenna.htm veterinari ravenna] [http://trouble166.110mb.com/asics-tiger.htm asics tiger calzature] [http://slavkamolot.110mb.com/library/lg-condizionatori/ lg condizionatori dual] [http://sneezingpops.110mb.com/newberry/ newberry] [http://stitchesnglue.110mb.com/got-none.htm got none] [http://stitchesnglue.110mb.com/hard-disk.htm hard disk decoder] [http://slavkamolot.110mb.com/library/oddo/ oddo] [http://some-omeelse.110mb.com/data/provincia-italiane.htm provincia italiane] [http://sister-sunshine.110mb.com/html/asciugacapelli-parete/ asciugacapelli parete] [http://trene-von-anty.110mb.com/description/peccato.htm peccato] [http://lazythoughts.110mb.com/lib/giovanni-re/ giovanni (re di boemia)] [http://nationavce.110mb.com/view/prezzo-infisso.htm prezzo infisso] [http://unremig.110mb.com/code-sky/ code sky 11 2004] [http://funk-mastah-ion.110mb.com/data/calendario-brad.htm calendario brad pitt] [http://book-wench.110mb.com/text/seat-leon/ seat leon concessionario] [http://ultra-creator.110mb.com/articles/sblocco-tre.htm sblocco tre] [http://trouble166.110mb.com/leyendas-y.htm leyendas y mitos] [http://trene-von-anty.110mb.com/description/milano-santo.htm milano santo domingo (repubblica] [http://forever-your.110mb.com/data/telefonini-tim.htm telefonini tim] [http://nationavce.110mb.com/view/koc-daewoo.htm koc daewoo] [http://forever-your.110mb.com/data/singole-a.htm singole a roma] [http://lazythoughts.110mb.com/lib/fotos-da/ fotos da playboy internacional] [http://unremig.110mb.com/new-beetle/ new beetle tdi 101 cv] [http://unremig.110mb.com/motorola-v/ motorola v220 caricabatterie] [http://dialed.110mb.com/small/fiat-strada/ fiat strada] [http://sneezingpops.110mb.com/vitara/ vitara] [http://sister-sunshine.110mb.com/html/ded-my/ ded my] [http://trene-von-anty.110mb.com/description/a-family.htm a family] [http://olikka.110mb.com/library/indiana-line.htm indiana line 5 casse] [http://nationavce.110mb.com/view/hilton-sharm.htm hilton sharm] [http://olikka.110mb.com/library/lara-croft.htm lara croft non e in ritardo] [http://funk-mastah-ion.110mb.com/data/tisana-dimagranti.htm tisana dimagranti] [http://funk-mastah-ion.110mb.com/data/mpeg.htm mpeg4] [http://sneezingpops.110mb.com/videos-gratis/ videos gratis] [http://mouse-zae.110mb.com/gino-fontana.htm gino fontana srl] [http://blue-olusha.110mb.com/library/municipio-somma/ municipio somma lombardo] [http://book-wench.110mb.com/text/mi-vida/ mi vida] [http://book-wench.110mb.com/text/fiesta-de/ fiesta de la] [http://some-omeelse.110mb.com/data/longbow.htm longbow] [http://funk-mastah-ion.110mb.com/data/cryogenteam.htm cryogenteam] [http://gekijuls.110mb.com/tortura/ tortura] [http://unremig.110mb.com/lavatrici-philco/ lavatrici philco] [http://sneezingpops.110mb.com/susy-blady/ susy blady] [http://mouse-zae.110mb.com/dvd-di.htm dvd di phil collins] [http://unremig.110mb.com/piatti-arabi/ piatti arabi] [http://olikka.110mb.com/library/i-believe.htm i believe in miracle] [http://yeeden.110mb.com/data/foto-porno/ foto porno gratis] [http://blue-olusha.110mb.com/library/citta-torino/ citta torino] [http://nationavce.110mb.com/view/everibody-s.htm everibody s changing testo] [http://sister-sunshine.110mb.com/html/pacemaker/ pacemaker] [http://forever-your.110mb.com/data/rendsburg.htm rendsburg] [http://gekijuls.110mb.com/eleonora-rossi/ eleonora rossi drago] [http://sneezingpops.110mb.com/gioco-virtual/ gioco virtual inseminetor] [http://stitchesnglue.110mb.com/tu-sei.htm tu sei re] [http://nationavce.110mb.com/view/www-tecnogym.htm www tecnogym com] [http://yeeden.110mb.com/data/www-globe/ www globe janakantha com] [http://trene-von-anty.110mb.com/description/malattia-professionale.htm malattia professionale] [http://unremig.110mb.com/mini-brescia/ mini brescia] [http://olikka.110mb.com/library/nikon-binocolo.htm nikon binocolo] [http://stitchesnglue.110mb.com/vasto-case.htm vasto case] [http://dialed.110mb.com/small/mezza-notte/ mezza notte di fuoco] [http://gekijuls.110mb.com/r-kelly/ r kelly cassidy] [http://slavkamolot.110mb.com/library/por-que/ por que te amo] [http://stitchesnglue.110mb.com/my-inmortal.htm my inmortal evanescense] [http://funk-mastah-ion.110mb.com/data/kejo.htm kejo] [http://blue-olusha.110mb.com/library/hoover-frigo/ hoover frigo] [http://sneezingpops.110mb.com/la-cavalcata/ la cavalcata dei diavoli rossi] [http://nationavce.110mb.com/view/lettori-dvd.htm lettori dvd rw] [http://lazythoughts.110mb.com/lib/duje/ duje] [http://slavkamolot.110mb.com/library/francesco-sarsi/ francesco sarsi] [http://forever-your.110mb.com/data/mario-venuti.htm mario venuti crudele video] [http://stitchesnglue.110mb.com/chappaqua.htm chappaqua] [http://sneezingpops.110mb.com/organizzatore-di/ organizzatore di eventi] [http://gekijuls.110mb.com/lezione-di/ lezione di musica] [http://stitchesnglue.110mb.com/edoardo-vianello.htm edoardo vianello] [http://forever-your.110mb.com/data/bocs.htm bocs] [http://ultra-creator.110mb.com/articles/desktop-wallpaper.htm desktop wallpaper] [http://sneezingpops.110mb.com/stacey-s/ stacey s mom] [http://trene-von-anty.110mb.com/description/casseforti.htm casseforti] [http://gekijuls.110mb.com/e-c/ e c e una cosa che non] [http://stitchesnglue.110mb.com/dlaczzego.htm dlaczzego] [http://funk-mastah-ion.110mb.com/data/prefabricati.htm prefabricati] [http://slavkamolot.110mb.com/library/lino-banfi/ lino banfi bar dello sport] [http://slavkamolot.110mb.com/library/rom-platform/ rom platform super nintendo] [http://lazythoughts.110mb.com/lib/handycam-sony/ handycam sony hc42e] [http://lazythoughts.110mb.com/lib/magix-foto/ magix foto cd dvd] [http://dialed.110mb.com/small/s-/ s 4280 aspirapolvere] [http://some-omeelse.110mb.com/data/www-wachovia.htm www wachovia com] [http://trene-von-anty.110mb.com/description/fiat-punto.htm fiat punto 1100] [http://stitchesnglue.110mb.com/www-bolleblu.htm www bolleblu it] [http://some-omeelse.110mb.com/data/flakiss.htm flakiss] {{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 22:13, 25 August 2007

sfruttamento kingston 512 mb not yet box 3 5 hd finanziamento cuneo ormoni androgeni grande fratello sito uffuciale prestito chieti mariagrazia europe travel ot 525 siemens suoneria cellulare dowload midi chatta con ragazze nude gabry ponte figli pitagora sutra diamante polar s810i mp3 player wireless torreciudad rok and roll ibi srl ia riproduzione nell essere umano isola di ischia coup de foudre dispensatore acqua virgine pavarotti domingo carreras three tenors site blog deejay it incontro single incontrare donna translator pro 9 van aken piet la principessa delle ostriche toy story giocattoli decespugliatori alpina elettrici www milo ventimiglia it classifica campionato serie b mutande sporche olympus ds2 infonavit gob mx raymarine st 40 ragazzo malta danza italiana i am a woman in love mp3 sade flow mp3 xt 660 wez to poczuj onar legge 1933 gruppi musicali anni 70 opera caso moro ddr 400mhz pc3200 hatene teac h500 polistirolo brescia ricchi monitor plasma 42 dance mat console accessori la celestina recorder disk lela porno i gangsters del fuoco vendita case verona esercito difesa it provveditorato cosenza quello strano sentimento lazzo home theatre con dvd recorder pioneer dvd recordervcr travelmate 200 buona vita gigi d da godere ericsson antenne televisori 40 samsung acer al2671w 26 piccolo uomo mia martini stephanie mc mahon societa post industriale maxtor hd rjeka croazia makadam cartier rem fomalhaut huge boobs snow on the sahara javel quest nokia7260 telefonia lepidium mp3 rds impianti hifi canon eos digital rebel xt slr har disk esterno lacie 250 viva voce auto bluetooth abigail toyne yeti sports 9 ricky martin livin la vida loca fotocopiatrice konica plunkett macleane acer aspire 17 bluetooth vieht video pitesti annuncio lavoro mantova mahjong towers sava vita beghelli single it le sensitive ati 9550 256 testo lo stara sora adidas monaco drown in my own tears sascha del bb veterinari ravenna asics tiger calzature lg condizionatori dual newberry got none hard disk decoder oddo provincia italiane asciugacapelli parete peccato giovanni (re di boemia) prezzo infisso code sky 11 2004 calendario brad pitt seat leon concessionario sblocco tre leyendas y mitos milano santo domingo (repubblica telefonini tim koc daewoo singole a roma fotos da playboy internacional new beetle tdi 101 cv motorola v220 caricabatterie fiat strada vitara ded my a family indiana line 5 casse hilton sharm lara croft non e in ritardo tisana dimagranti mpeg4 videos gratis gino fontana srl municipio somma lombardo mi vida fiesta de la longbow cryogenteam tortura lavatrici philco susy blady dvd di phil collins piatti arabi i believe in miracle foto porno gratis citta torino everibody s changing testo pacemaker rendsburg eleonora rossi drago gioco virtual inseminetor tu sei re www tecnogym com www globe janakantha com malattia professionale mini brescia nikon binocolo vasto case mezza notte di fuoco r kelly cassidy por que te amo my inmortal evanescense kejo hoover frigo la cavalcata dei diavoli rossi lettori dvd rw duje francesco sarsi mario venuti crudele video chappaqua organizzatore di eventi lezione di musica edoardo vianello bocs desktop wallpaper stacey s mom casseforti e c e una cosa che non dlaczzego prefabricati lino banfi bar dello sport rom platform super nintendo handycam sony hc42e magix foto cd dvd s 4280 aspirapolvere www wachovia com fiat punto 1100 www bolleblu it flakiss

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