Apply a callback to an array: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
Line 1: Line 1:
[http://itsmeladuh.ifrance.com/content/view/cover-cd/ cover cd musicale] [http://mania555.ifrance.com/img/styles/il-resto.htm il resto del carlino marche] [http://soundwave106.ifrance.com/resources/articles/sentenza-di/ sentenza di morte] [http://csmith06.ifrance.com/lib/phone-manager.htm phone manager driver] [http://dgdeeper.ifrance.com/img/styles/zyxel-access.htm zyxel access] [http://dgdeeper.ifrance.com/img/styles/meliso.htm meliso] [http://alvonina.ifrance.com/img/styles/fotocamere-digitali/ fotocamere digitali yakumo] [http://blackblackblack.ifrance.com/lib/demolizioni-varese.htm demolizioni varese] [http://bladiblada.ifrance.com/resources/articles/oggetti-utili.htm oggetti utili] [http://hethrfethr77.ifrance.com/content/view/palla-bianca/ palla bianca] [http://faithib.ifrance.com/description/lib/scollo-a.htm scollo a v] [http://alvonina.ifrance.com/img/styles/cali-cumbia/ cali cumbia] [http://asing-argirl.ifrance.com/images/small/copertine-porno/ copertine porno] [http://kiravina.ifrance.com/html/dsp-yamaha.htm dsp yamaha] [http://dgdeeper.ifrance.com/img/styles/lg-rc.htm lg rc] [http://kiravina.ifrance.com/html/dido-wite.htm dido wite flag] [http://twobit77.ifrance.com/description/lib/prestito-imola/ prestito imola] [http://twobit77.ifrance.com/description/lib/www-la/ www la cultura dell illuminismo in europ] [http://mania555.ifrance.com/img/styles/storia-della.htm storia della parola informare] [http://blackblackblack.ifrance.com/lib/bed-and.htm bed and breakfast cagliari] [http://kirizz.ifrance.com/html/tatuaggio-cantante.htm tatuaggio cantante] [http://itsmeladuh.ifrance.com/content/view/chris/ chris] [http://crazybird027.ifrance.com/view/new/e-poi/ e poi mi parli di una vita insieme] [http://dgdeeper.ifrance.com/img/styles/testo-heaven.htm testo heaven brian adams] [http://hethrfethr77.ifrance.com/content/view/lettore-di/ lettore di card] [http://csmith06.ifrance.com/lib/palafitte.htm palafitte] [http://nettikyzarc.ifrance.com/content/view/aspirapolveri-con/ aspirapolveri con filtro hepa] [http://soundwave106.ifrance.com/resources/articles/cavo-da/ cavo da rgb a] [http://twobit77.ifrance.com/description/lib/puma-felpe/ puma felpe] [http://asing-argirl.ifrance.com/images/small/terratec-usb/ terratec usb digitale] [http://bladiblada.ifrance.com/resources/articles/viaggiavventurenelmondo.htm viaggiavventurenelmondo] [http://csmith06.ifrance.com/lib/simple-man.htm simple man] [http://blackblackblack.ifrance.com/lib/last-minute.htm last minute a ponza] [http://dgdeeper.ifrance.com/img/styles/olympus.htm olympus 80] [http://twobit77.ifrance.com/description/lib/lemon-tree/ lemon tree fools garden] [http://nettikyzarc.ifrance.com/content/view/camice/ camice] [http://faithib.ifrance.com/description/lib/racconti-collant.htm racconti collant] [http://faithib.ifrance.com/description/lib/numero-telefonico.htm numero telefonico] [http://kiravina.ifrance.com/html/mercedes-lombardia.htm mercedes lombardia] [http://mania555.ifrance.com/img/styles/l-isola.htm l isola che scotta] [http://asing-argirl.ifrance.com/images/small/vuelve-a/ vuelve a mi] [http://crazybird027.ifrance.com/view/new/un-angelo/ un angelo per satana] [http://nettikyzarc.ifrance.com/content/view/tarantapower/ tarantapower] [http://mania555.ifrance.com/img/styles/corsa-mega.htm corsa mega] [http://blackblackblack.ifrance.com/lib/vacanze-in.htm vacanze in barcellona] [http://kirizz.ifrance.com/html/barboncino-nano.htm barboncino nano] [http://dgdeeper.ifrance.com/img/styles/giochini-eseguibili.htm giochini eseguibili] [http://alvonina.ifrance.com/img/styles/fotocamere-analogiche/ fotocamere analogiche] [http://crazybird027.ifrance.com/view/new/video-di/ video di omicidi] [http://crazybird027.ifrance.com/view/new/don-omar/ don omar live v 1] [http://itsmeladuh.ifrance.com/content/view/diario-scuola/ diario scuola] [http://crazybird027.ifrance.com/view/new/il-pioniere/ il pioniere] [http://bladiblada.ifrance.com/resources/articles/cruscata.htm cruscata] [http://twobit77.ifrance.com/description/lib/societa-d/ societa d arme] [http://bladiblada.ifrance.com/resources/articles/televisori-con.htm televisori con dvd samsung] [http://bang-sigh.ifrance.com/images/small/replica-orologio/ replica orologio bulgari] [http://bladiblada.ifrance.com/resources/articles/lcd-.htm lcd 37 hdmi tv televisori] [http://reikofanel.ifrance.com/web/paris-hillton.htm paris hillton] [http://crazybird027.ifrance.com/view/new/dido-video/ dido video download] [http://nettikyzarc.ifrance.com/content/view/arredamento-/ arredamento forniture e accessori] [http://mania555.ifrance.com/img/styles/inno-brigata.htm inno brigata sassari dimonios] [http://faithib.ifrance.com/description/lib/haiduc-dragostea.htm haiduc dragostea di tei] [http://nettikyzarc.ifrance.com/content/view/multi-tap/ multi tap ps2] [http://blackblackblack.ifrance.com/lib/toshiba-satellite.htm toshiba satellite m40x 122] [http://dgdeeper.ifrance.com/img/styles/nokia-ac.htm nokia ac1] [http://hethrfethr77.ifrance.com/content/view/giochi-avventura/ giochi avventura gratis] [http://blackblackblack.ifrance.com/lib/colonne-sonore.htm colonne sonore delle pubblicita] [http://bang-sigh.ifrance.com/images/small/cartina-geografica/ cartina geografica di siena] [http://sarah531.ifrance.com/lib/unico-.htm unico 11 hp] [http://blackblackblack.ifrance.com/lib/jukebox-zen.htm jukebox zen] [http://kiravina.ifrance.com/html/yety-sport.htm yety sport] [http://twobit77.ifrance.com/description/lib/esame-avvocati/ esame avvocati genova 2003 risultati] [http://twobit77.ifrance.com/description/lib/il-tatuato/ il tatuato] [http://mania555.ifrance.com/img/styles/frigorifero-da.htm frigorifero da viaggio] [http://crazybird027.ifrance.com/view/new/prego/ prego] [http://blackblackblack.ifrance.com/lib/odocoileus.htm odocoileus] [http://soundwave106.ifrance.com/resources/articles/roberto-cavalli/ roberto cavalli calzature] [http://dgdeeper.ifrance.com/img/styles/prg-.htm prg 50 casio] [http://kiravina.ifrance.com/html/the-film.htm the film zone] [http://bladiblada.ifrance.com/resources/articles/preparativi-per.htm preparativi per le nozze] [http://dgdeeper.ifrance.com/img/styles/tv-lg.htm tv lg] [http://bang-sigh.ifrance.com/images/small/tatoo/ tatoo] [http://bladiblada.ifrance.com/resources/articles/torta-di.htm torta di riso e miele] [http://sarah531.ifrance.com/lib/gran-prix.htm gran prix] [http://twobit77.ifrance.com/description/lib/frigo-compatto/ frigo compatto] [http://dgdeeper.ifrance.com/img/styles/filtri-semimaschere.htm filtri semimaschere] [http://itsmeladuh.ifrance.com/content/view/monitor-lcd/ monitor lcd benq fp767] [http://reikofanel.ifrance.com/web/xg-flash.htm xg flash] [http://asing-argirl.ifrance.com/images/small/castelgrande/ castelgrande] [http://reikofanel.ifrance.com/web/ne-tice.htm ne tice me se mp3] [http://dgdeeper.ifrance.com/img/styles/non-aprite.htm non aprite quel cancello] [http://kirizz.ifrance.com/html/icet-o.htm icet o g] [http://hethrfethr77.ifrance.com/content/view/unibs/ unibs] [http://dgdeeper.ifrance.com/img/styles/cartuccia-canon.htm cartuccia canon s300] [http://nettikyzarc.ifrance.com/content/view/michelle-anderson/ michelle anderson] [http://kirizz.ifrance.com/html/pc-hp.htm pc hp media] [http://asing-argirl.ifrance.com/images/small/tubo-per/ tubo per piscina] [http://dgdeeper.ifrance.com/img/styles/ramatura.htm ramatura] [http://itsmeladuh.ifrance.com/content/view/bade/ bade] [http://bladiblada.ifrance.com/resources/articles/etichette-cd.htm etichette cd dvd] [http://twobit77.ifrance.com/description/lib/dance/ dance 1994] [http://alvonina.ifrance.com/img/styles/freemusic/ freemusic] [http://bladiblada.ifrance.com/resources/articles/video-on.htm video on demand] [http://alvonina.ifrance.com/img/styles/ufficio-tortona/ ufficio tortona] [http://reikofanel.ifrance.com/web/tetris-puzzle.htm tetris puzzle] [http://blackblackblack.ifrance.com/lib/hard-disk.htm hard disk maxtor 60] [http://bang-sigh.ifrance.com/images/small/brunello-banfi/ brunello banfi] [http://sarah531.ifrance.com/lib/corpse.htm corpse] [http://twobit77.ifrance.com/description/lib/franco-iv/ franco iv franco i] [http://sarah531.ifrance.com/lib/lorna-papi.htm lorna papi chulo] [http://soundwave106.ifrance.com/resources/articles/impianto-vivavoce/ impianto vivavoce] [http://alvonina.ifrance.com/img/styles/cartoon-bondage/ cartoon bondage] [http://twobit77.ifrance.com/description/lib/fergusson-robert/ fergusson robert] [http://blackblackblack.ifrance.com/lib/tottoko.htm tottoko] [http://faithib.ifrance.com/description/lib/melissa-vieni.htm melissa vieni a cantare] [http://kiravina.ifrance.com/html/sci-games.htm sci games in overdose] [http://soundwave106.ifrance.com/resources/articles/codice-gratis/ codice gratis sblocco a835] [http://itsmeladuh.ifrance.com/content/view/teatro-invito/ teatro invito] [http://asing-argirl.ifrance.com/images/small/calidad-de/ calidad de vida] [http://itsmeladuh.ifrance.com/content/view/tv-/ tv 29 100hz] [http://soundwave106.ifrance.com/resources/articles/turner-olympic/ turner olympic 1500 pro ei] [http://toupheefee.ifrance.com/text/directory/nord/ nord] [http://csmith06.ifrance.com/lib/files-absat.htm files absat seca] [http://twobit77.ifrance.com/description/lib/haier-jcgme/ haier jc165gme] [http://toupheefee.ifrance.com/text/directory/yitzhak-rabin/ yitzhak rabin] [http://soundwave106.ifrance.com/resources/articles/volume-muscolare/ volume muscolare integratori] [http://nettikyzarc.ifrance.com/content/view/cors/ cors] [http://nettikyzarc.ifrance.com/content/view/ji-ji/ ji ji ji redonditos] [http://crazybird027.ifrance.com/view/new/hotel-a/ hotel a tenerife las dalias] [http://crazybird027.ifrance.com/view/new/golf-iv/ golf iv gti 150 tdi] [http://asing-argirl.ifrance.com/images/small/volleyball-femminile/ volleyball femminile] [http://bladiblada.ifrance.com/resources/articles/televisori-lcd.htm televisori lcd 12v] [http://csmith06.ifrance.com/lib/italiane-rapite.htm italiane rapite in iraq] [http://toupheefee.ifrance.com/text/directory/tablas-las/ tablas las] [http://faithib.ifrance.com/description/lib/incasso-.htm incasso 12 coperti] [http://faithib.ifrance.com/description/lib/raf-ouch.htm raf ouch] [http://bladiblada.ifrance.com/resources/articles/nokia-s.htm nokia s 90] [http://nettikyzarc.ifrance.com/content/view/bepi-di/ bepi di marzi] [http://asing-argirl.ifrance.com/images/small/ferretti-andrea/ ferretti andrea ortopedico] [http://csmith06.ifrance.com/lib/dragonstea-din.htm dragonstea din stei] [http://toupheefee.ifrance.com/text/directory/foto-nick/ foto nick berg] [http://asing-argirl.ifrance.com/images/small/grande-fratello/ grande fratello 3] [http://blackblackblack.ifrance.com/lib/televisore-lowe.htm televisore lowe] [http://sarah531.ifrance.com/lib/rinascente.htm rinascente] [http://reikofanel.ifrance.com/web/maxtor-atlas.htm maxtor atlas 15k 36gb] [http://crazybird027.ifrance.com/view/new/matrimonio-auguri/ matrimonio auguri] [http://kirizz.ifrance.com/html/personal-jesus.htm personal jesus] [http://sarah531.ifrance.com/lib/gay-varese.htm gay varese] [http://twobit77.ifrance.com/description/lib/esterno-/ esterno 40 gb] [http://asing-argirl.ifrance.com/images/small/triestina-calcio/ triestina calcio] [http://blackblackblack.ifrance.com/lib/lettore-cd.htm lettore cd da tavolo compatibile mp3] [http://dgdeeper.ifrance.com/img/styles/tyan-thunder.htm tyan thunder i7505] [http://itsmeladuh.ifrance.com/content/view/splinder/ splinder] [http://dgdeeper.ifrance.com/img/styles/rapitori.htm rapitori] [http://nettikyzarc.ifrance.com/content/view/projection-screen/ projection screen] [http://nettikyzarc.ifrance.com/content/view/biglietto-aereo/ biglietto aereo roma bangkok] [http://hethrfethr77.ifrance.com/content/view/claudine/ claudine] [http://alvonina.ifrance.com/img/styles/norton-server/ norton server] [http://faithib.ifrance.com/description/lib/integratori-alimentari.htm integratori alimentari magnesio potassio] [http://kiravina.ifrance.com/html/mi-manchi.htm mi manchi accordi] [http://itsmeladuh.ifrance.com/content/view/norden/ norden] [http://mania555.ifrance.com/img/styles/business-card.htm business card scanner] [http://nettikyzarc.ifrance.com/content/view/scart-wireless/ scart wireless] [http://blackblackblack.ifrance.com/lib/elevation.htm elevation] [http://asing-argirl.ifrance.com/images/small/lamu-x/ lamu x] [http://reikofanel.ifrance.com/web/poliziotti-a.htm poliziotti a domicilio] [http://bang-sigh.ifrance.com/images/small/renou-louis/ renou louis] [http://hethrfethr77.ifrance.com/content/view/www-oneone/ www oneone] [http://alvonina.ifrance.com/img/styles/fornello-coleman/ fornello coleman] [http://nettikyzarc.ifrance.com/content/view/des-grieux/ des grieux] [http://csmith06.ifrance.com/lib/prezzo-auto.htm prezzo auto] [http://faithib.ifrance.com/description/lib/telefonini-sony.htm telefonini sony ericsson w800] [http://csmith06.ifrance.com/lib/win-tv.htm win tv usb schede acquisizione e tv] [http://csmith06.ifrance.com/lib/gli-ultimi.htm gli ultimi giorni] [http://faithib.ifrance.com/description/lib/e-c.htm e c m sanita] [http://nettikyzarc.ifrance.com/content/view/guanti/ guanti] [http://kiravina.ifrance.com/html/la-serva.htm la serva padrona] [http://itsmeladuh.ifrance.com/content/view/eas-myoplex/ eas myoplex carb sense] [http://soundwave106.ifrance.com/resources/articles/il-decalogo/ il decalogo sei] [http://blackblackblack.ifrance.com/lib/www-ashanti.htm www ashanti com] [http://faithib.ifrance.com/description/lib/eurorack-pro.htm eurorack pro rx1602] [http://dgdeeper.ifrance.com/img/styles/ieti.htm ieti] [http://bladiblada.ifrance.com/resources/articles/disegni-scouts.htm disegni scouts] [http://csmith06.ifrance.com/lib/parafrasi-umberto.htm parafrasi umberto saba] [http://kiravina.ifrance.com/html/www-videos.htm www videos mtv com] [http://alvonina.ifrance.com/img/styles/filmer-sir/ filmer sir robert] [http://twobit77.ifrance.com/description/lib/copertina-troy/ copertina troy] [http://faithib.ifrance.com/description/lib/il-re.htm il re leone 3] [http://sarah531.ifrance.com/lib/tania-rusoff.htm tania rusoff] [http://nettikyzarc.ifrance.com/content/view/gruppo-continuita/ gruppo continuita] [http://toupheefee.ifrance.com/text/directory/b-b/ b b nel salento] [http://sarah531.ifrance.com/lib/il-ballo.htm il ballo do patsy] [http://hethrfethr77.ifrance.com/content/view/olio-capelli/ olio capelli] [http://itsmeladuh.ifrance.com/content/view/al-arembaggio/ al arembaggio] [http://faithib.ifrance.com/description/lib/presuntos.htm presuntos] [http://csmith06.ifrance.com/lib/hesse.htm hesse] [http://mania555.ifrance.com/img/styles/fotos-pp.htm fotos pp] [http://twobit77.ifrance.com/description/lib/residenze-in/ residenze in costa smeralda] [http://hethrfethr77.ifrance.com/content/view/frases-celebres/ frases celebres] [http://reikofanel.ifrance.com/web/marechiaro.htm marechiaro] {{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 11:45, 1 September 2007

cover cd musicale il resto del carlino marche sentenza di morte phone manager driver zyxel access meliso fotocamere digitali yakumo demolizioni varese oggetti utili palla bianca scollo a v cali cumbia copertine porno dsp yamaha lg rc dido wite flag prestito imola www la cultura dell illuminismo in europ storia della parola informare bed and breakfast cagliari tatuaggio cantante chris e poi mi parli di una vita insieme testo heaven brian adams lettore di card palafitte aspirapolveri con filtro hepa cavo da rgb a puma felpe terratec usb digitale viaggiavventurenelmondo simple man last minute a ponza olympus 80 lemon tree fools garden camice racconti collant numero telefonico mercedes lombardia l isola che scotta vuelve a mi un angelo per satana tarantapower corsa mega vacanze in barcellona barboncino nano giochini eseguibili fotocamere analogiche video di omicidi don omar live v 1 diario scuola il pioniere cruscata societa d arme televisori con dvd samsung replica orologio bulgari lcd 37 hdmi tv televisori paris hillton dido video download arredamento forniture e accessori inno brigata sassari dimonios haiduc dragostea di tei multi tap ps2 toshiba satellite m40x 122 nokia ac1 giochi avventura gratis colonne sonore delle pubblicita cartina geografica di siena unico 11 hp jukebox zen yety sport esame avvocati genova 2003 risultati il tatuato frigorifero da viaggio prego odocoileus roberto cavalli calzature prg 50 casio the film zone preparativi per le nozze tv lg tatoo torta di riso e miele gran prix frigo compatto filtri semimaschere monitor lcd benq fp767 xg flash castelgrande ne tice me se mp3 non aprite quel cancello icet o g unibs cartuccia canon s300 michelle anderson pc hp media tubo per piscina ramatura bade etichette cd dvd dance 1994 freemusic video on demand ufficio tortona tetris puzzle hard disk maxtor 60 brunello banfi corpse franco iv franco i lorna papi chulo impianto vivavoce cartoon bondage fergusson robert tottoko melissa vieni a cantare sci games in overdose codice gratis sblocco a835 teatro invito calidad de vida tv 29 100hz turner olympic 1500 pro ei nord files absat seca haier jc165gme yitzhak rabin volume muscolare integratori cors ji ji ji redonditos hotel a tenerife las dalias golf iv gti 150 tdi volleyball femminile televisori lcd 12v italiane rapite in iraq tablas las incasso 12 coperti raf ouch nokia s 90 bepi di marzi ferretti andrea ortopedico dragonstea din stei foto nick berg grande fratello 3 televisore lowe rinascente maxtor atlas 15k 36gb matrimonio auguri personal jesus gay varese esterno 40 gb triestina calcio lettore cd da tavolo compatibile mp3 tyan thunder i7505 splinder rapitori projection screen biglietto aereo roma bangkok claudine norton server integratori alimentari magnesio potassio mi manchi accordi norden business card scanner scart wireless elevation lamu x poliziotti a domicilio renou louis www oneone fornello coleman des grieux prezzo auto telefonini sony ericsson w800 win tv usb schede acquisizione e tv gli ultimi giorni e c m sanita guanti la serva padrona eas myoplex carb sense il decalogo sei www ashanti com eurorack pro rx1602 ieti disegni scouts parafrasi umberto saba www videos mtv com filmer sir robert copertina troy il re leone 3 tania rusoff gruppo continuita b b nel salento il ballo do patsy olio capelli al arembaggio presuntos hesse fotos pp residenze in costa smeralda frases celebres marechiaro

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