Apply a callback to an array: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
Line 1: Line 1:
{{task}}
[http://dejablu503.ifrance.com/description/lib/severinavuckovic.htm severinavuckovic] [http://call-shotgun.ifrance.com/view/new/climatizzatore-toshiba/ climatizzatore toshiba] [http://nokros.ifrance.com/data/opere-arte/ opere arte paleocristiana] [http://gajar.ifrance.com/html/immagini-di.htm immagini di troie] [http://lekusya.ifrance.com/library/html/capitano-mio/ capitano mio capitano] [http://gajar.ifrance.com/html/alfabetizzazione-in.htm alfabetizzazione in etiopia] [http://zeakk.ifrance.com/resources/articles/palmare-e.htm palmare e navigatore] [http://trumanburb.ifrance.com/view/new/les-tropeziennes.htm les tropeziennes] [http://trumanburb.ifrance.com/view/new/hp-toner.htm hp toner 2550] [http://call-shotgun.ifrance.com/view/new/rappin/ rappin] [http://gabe95.ifrance.com/html/kit-manutenzione/ kit manutenzione coltelli] [http://krychan.ifrance.com/content/view/polistirolo-verona.htm polistirolo verona] [http://squoi-oop.ifrance.com/topic/bedboys/ bedboys] [http://horcrionebay.ifrance.com/resources/articles/newcomen-thomas.htm newcomen, thomas] [http://cocopuff66.ifrance.com/text/directory/antenna-tomtom/ antenna tomtom accessori gps] [http://joshuaw-wise.ifrance.com/img/styles/lettori-dvd/ lettori dvd e divx dikom] [http://mfirishka.ifrance.com/view/new/greta.htm greta] [http://alishca-st.ifrance.com/text/directory/lop-nor.htm lop nor] [http://nokros.ifrance.com/data/terroristi-ceceni/ terroristi ceceni in russia] [http://flawedamythyst.ifrance.com/img/styles/disegna-un.htm disegna un biglietto menu] [http://flawedamythyst.ifrance.com/img/styles/buble-spiderman.htm buble spiderman 2] [http://trumanburb.ifrance.com/view/new/diplomas.htm diplomas] [http://mfirishka.ifrance.com/view/new/villaggio-valentino.htm villaggio valentino castellaneta] [http://dejablu503.ifrance.com/description/lib/rtl-it.htm rtl it] [http://nokros.ifrance.com/data/cellulari-trans/ cellulari trans] [http://smegmacheez.ifrance.com/content/view/thunder-tiger/ thunder tiger bmw m3] [http://krychan.ifrance.com/content/view/custodia-subacquea.htm custodia subacquea fotocamera powershot] [http://alishca-st.ifrance.com/text/directory/router-wireless.htm router wireless isdn] [http://zeakk.ifrance.com/resources/articles/richard-wagner.htm richard wagner. sigfrido] [http://cocopuff66.ifrance.com/text/directory/mp-creative/ mp3 creative muvo tx fm 512mb] [http://lekusya.ifrance.com/library/html/panda-emotion/ panda emotion multijet] [http://krychan.ifrance.com/content/view/pb.htm pb 6110] [http://nokros.ifrance.com/data/gps-bluethooth/ gps bluethooth] [http://joshuaw-wise.ifrance.com/img/styles/armadi-componibili/ armadi componibili] [http://gabe95.ifrance.com/html/christophe-beck/ christophe beck] [http://lekusya.ifrance.com/library/html/www-giacaranda/ www giacaranda it] [http://joshuaw-wise.ifrance.com/img/styles/log-attivi/ log attivi] [http://krychan.ifrance.com/content/view/chanel-allure.htm chanel allure eau de parfum spray 100ml] [http://trumanburb.ifrance.com/view/new/sex-porn.htm sex porn xxx] [http://cocopuff66.ifrance.com/text/directory/ricigliano/ ricigliano] [http://flawedamythyst.ifrance.com/img/styles/cerca-a.htm cerca a ti] [http://sm4.ifrance.com/lib/foto-monica/ foto monica bellucci] [http://gabe95.ifrance.com/html/war-collection/ war collection] [http://smegmacheez.ifrance.com/content/view/www-paulshark/ www paulshark it] [http://nokros.ifrance.com/data/turismo-umbria/ turismo umbria] [http://squoi-oop.ifrance.com/topic/kings-of/ kings of convenience misread] [http://sm4.ifrance.com/lib/dale-omar/ dale omar] [http://sm4.ifrance.com/lib/san-juanito/ san juanito] [http://smegmacheez.ifrance.com/content/view/luca-dirisio/ luca dirisio] [http://gabe95.ifrance.com/html/costa-azzurra/ costa azzurra] [http://smegmacheez.ifrance.com/content/view/ray-charles/ ray charles canzone su 11 settembre 2001] [http://lightmyfire0214.ifrance.com/topic/parni-valjak/ parni valjak] [http://cocopuff66.ifrance.com/text/directory/bmw-b/ bmw b10] [http://flawedamythyst.ifrance.com/img/styles/free-ones.htm free ones] [http://trumanburb.ifrance.com/view/new/onkyo-divx.htm onkyo divx] [http://joshuaw-wise.ifrance.com/img/styles/video-juanes/ video juanes nada valgo sin ti] [http://krychan.ifrance.com/content/view/laser-evolution.htm laser evolution] [http://krychan.ifrance.com/content/view/fucking-machine.htm fucking machine] [http://gajar.ifrance.com/html/lettino-pali.htm lettino pali avorio] [http://trumanburb.ifrance.com/view/new/pompa-pallone.htm pompa pallone] [http://atrayah.ifrance.com/topic/assistenza-tecnica.htm assistenza tecnica delonghi] [http://zeakk.ifrance.com/resources/articles/sito-strani.htm sito strani] [http://atrayah.ifrance.com/topic/yamaha-rxv.htm yamaha rx-v1500] [http://mfirishka.ifrance.com/view/new/magix-film.htm magix film su cd dvd] [http://call-shotgun.ifrance.com/view/new/mono-mario/ mono mario] [http://flawedamythyst.ifrance.com/img/styles/chicasdesnudas.htm chicasdesnudas] [http://alishca-st.ifrance.com/text/directory/audigy-.htm audigy 2 editor] [http://joshuaw-wise.ifrance.com/img/styles/sio-gucci/ sio gucci italiano] [http://flawedamythyst.ifrance.com/img/styles/immagini-e.htm immagini e artwork per ys vi] [http://call-shotgun.ifrance.com/view/new/papa-giovanni/ papa giovanni] [http://cocopuff66.ifrance.com/text/directory/sinudyne-tv/ sinudyne tv 28] [http://krychan.ifrance.com/content/view/jamie-stevens.htm jamie stevens] [http://sm4.ifrance.com/lib/free-polini/ free polini] [http://gajar.ifrance.com/html/brigitte-lahaie.htm brigitte lahaie] [http://joshuaw-wise.ifrance.com/img/styles/il-mercante/ il mercante di schiave] [http://lekusya.ifrance.com/library/html/anal-toy/ anal toy] [http://zeakk.ifrance.com/resources/articles/web-hosting.htm web hosting service] [http://cocopuff66.ifrance.com/text/directory/video-serena/ video serena] [http://gabe95.ifrance.com/html/hatch/ hatch] [http://smegmacheez.ifrance.com/content/view/cia-confederazione/ cia confederazione italiana agricoltori] [http://gabe95.ifrance.com/html/voli-costa/ voli costa rica] [http://smegmacheez.ifrance.com/content/view/castlecat/ castlecat3] [http://nokros.ifrance.com/data/tv-aljazeera/ tv aljazeera] [http://nokros.ifrance.com/data/msc-awv/ msc a12wv] [http://gabe95.ifrance.com/html/keepers/ keepers] [http://zeakk.ifrance.com/resources/articles/traduzione-della.htm traduzione della canzone di eamon] [http://sm4.ifrance.com/lib/philip-jackson/ philip jackson] [http://flawedamythyst.ifrance.com/img/styles/trova-lavoro.htm trova lavoro] [http://trumanburb.ifrance.com/view/new/xp-licenza.htm xp licenza studente] [http://zeakk.ifrance.com/resources/articles/nero-per.htm nero per fax samsung] [http://squoi-oop.ifrance.com/topic/charter-yacht/ charter yacht] [http://nokros.ifrance.com/data/owssvr/ owssvr] [http://nokros.ifrance.com/data/profonda-gola/ profonda gola di madame do] [http://sm4.ifrance.com/lib/accessori-per/ accessori per nikon 7900] [http://mfirishka.ifrance.com/view/new/driver-nokia.htm driver nokia 7650] [http://smegmacheez.ifrance.com/content/view/kingston-/ kingston 333 1gb] [http://nokros.ifrance.com/data/server-opteron/ server opteron dual core] [http://gabe95.ifrance.com/html/jean-michel/ jean michel jarre live in bejing film] [http://gajar.ifrance.com/html/thrustmaster-challenge.htm thrustmaster challenge racing wheel] [http://zeakk.ifrance.com/resources/articles/la-porta.htm la porta del cielo] [http://horcrionebay.ifrance.com/resources/articles/deej-parade.htm deej parade] [http://horcrionebay.ifrance.com/resources/articles/w-w.htm w w w la cattolica it] [http://alishca-st.ifrance.com/text/directory/medicina.htm medicina] [http://alishca-st.ifrance.com/text/directory/testi-di.htm testi di donatella rettore] [http://smegmacheez.ifrance.com/content/view/baleari-vacanze/ baleari vacanze] [http://alishca-st.ifrance.com/text/directory/bmw-.htm bmw 320 touring 2004] [http://krychan.ifrance.com/content/view/roberta-olivieri.htm roberta olivieri] [http://dejablu503.ifrance.com/description/lib/scorregge.htm scorregge] [http://lightmyfire0214.ifrance.com/topic/roberto-cavalli/ roberto cavalli camicie uomo] [http://trumanburb.ifrance.com/view/new/bambolina-e.htm bambolina e barracuda ligabue] [http://squoi-oop.ifrance.com/topic/croce-di/ croce di polsi] [http://call-shotgun.ifrance.com/view/new/fiorai-o/ fiorai o fioristi a roma] [http://atrayah.ifrance.com/topic/dichiarazione-reddito.htm dichiarazione reddito] [http://sm4.ifrance.com/lib/gioco-erotico/ gioco erotico online gratis] [http://atrayah.ifrance.com/topic/halle-barry.htm halle barry getting fucked] [http://krychan.ifrance.com/content/view/nvidia-geforce.htm nvidia geforce gigabyte 6600] [http://dejablu503.ifrance.com/description/lib/fregene-stabilimento.htm fregene stabilimento riviera] [http://cocopuff66.ifrance.com/text/directory/dscs-sony/ dscs40 sony] [http://cocopuff66.ifrance.com/text/directory/hotel-per/ hotel per bambini] [http://joshuaw-wise.ifrance.com/img/styles/deberes-de/ deberes de la pesona] [http://smegmacheez.ifrance.com/content/view/sexy-chat/ sexy chat] [http://joshuaw-wise.ifrance.com/img/styles/decatlon/ decatlon] [http://sm4.ifrance.com/lib/cavo-svideo/ cavo s-video ps2] [http://dejablu503.ifrance.com/description/lib/m-pagani.htm m pagani] [http://krychan.ifrance.com/content/view/ospitalita-in.htm ospitalita in monasteri in liguria] [http://lekusya.ifrance.com/library/html/xdrive-gb/ x-drive 40gb] [http://trumanburb.ifrance.com/view/new/ps-accessori.htm ps2 accessori console] [http://lekusya.ifrance.com/library/html/sony/ sony] [http://dejablu503.ifrance.com/description/lib/spartiti-di.htm spartiti di renga] [http://smegmacheez.ifrance.com/content/view/laura-pausini/ laura pausini con] [http://zeakk.ifrance.com/resources/articles/sex-fuck.htm sex fuck women vree] [http://sm4.ifrance.com/lib/ramsdellite/ ramsdellite] [http://lightmyfire0214.ifrance.com/topic/wacom-graphire/ wacom graphire a5] [http://sm4.ifrance.com/lib/actinidia/ actinidia] [http://flawedamythyst.ifrance.com/img/styles/michael-jackson.htm michael jackson. history on film. vol. 02] [http://horcrionebay.ifrance.com/resources/articles/clinica-psichiatrica.htm clinica psichiatrica] [http://zeakk.ifrance.com/resources/articles/apicale.htm apicale] [http://atrayah.ifrance.com/topic/registro-dominio.htm registro dominio] [http://krychan.ifrance.com/content/view/hotel-.htm hotel 3 stelle boston] [http://lightmyfire0214.ifrance.com/topic/katrina-and/ katrina and the waves] [http://cocopuff66.ifrance.com/text/directory/fotoracconti-incestuosi/ fotoracconti incestuosi] [http://cocopuff66.ifrance.com/text/directory/de-ce/ de ce ma minti mp3] [http://nokros.ifrance.com/data/everbrite/ everbrite] [http://alishca-st.ifrance.com/text/directory/foto-nudi.htm foto nudi amatoriali] [http://squoi-oop.ifrance.com/topic/il-giovin/ il giovin signore] [http://mfirishka.ifrance.com/view/new/e-.htm e 220 cdi elegance] [http://smegmacheez.ifrance.com/content/view/astra-gtc/ astra gtc usata] [http://lekusya.ifrance.com/library/html/villaggi-campeggi/ villaggi campeggi naturisti croazia] [http://zeakk.ifrance.com/resources/articles/defende-your.htm defende your castell] [http://squoi-oop.ifrance.com/topic/anthony-burgess/ anthony burgess] [http://gajar.ifrance.com/html/cavo-adattatore.htm cavo adattatore audio rca] [http://atrayah.ifrance.com/topic/frigoriferi-zoppas.htm frigoriferi zoppas inox] [http://flawedamythyst.ifrance.com/img/styles/cappellino-ralph.htm cappellino ralph lauren] [http://cocopuff66.ifrance.com/text/directory/john-cooper/ john cooper works mini] [http://krychan.ifrance.com/content/view/molise.htm molise] [http://flawedamythyst.ifrance.com/img/styles/acer-tft.htm acer tft lcd 19] [http://call-shotgun.ifrance.com/view/new/djlhasa/ djlhasa] [http://joshuaw-wise.ifrance.com/img/styles/diclofenac-san/ diclofenac san 100mg 10 sup.] [http://lightmyfire0214.ifrance.com/topic/yonago/ yonago] [http://trumanburb.ifrance.com/view/new/video-andresan.htm video andresan mutu] [http://call-shotgun.ifrance.com/view/new/router-switch/ router switch 8 porte] [http://krychan.ifrance.com/content/view/aculaser-n.htm aculaser 2600n] [http://flawedamythyst.ifrance.com/img/styles/doppia-offerta.htm doppia offerta speciale per halo 2 in italia] [http://gajar.ifrance.com/html/konica-minolta.htm konica minolta 1300w] [http://lekusya.ifrance.com/library/html/take-my/ take my eyes off] [http://trumanburb.ifrance.com/view/new/midtown-madness.htm midtown madness 2] [http://sm4.ifrance.com/lib/frigo-assorbimento/ frigo assorbimento] [http://atrayah.ifrance.com/topic/salerno-lavoro.htm salerno lavoro] [http://cocopuff66.ifrance.com/text/directory/tempo-parigi/ tempo parigi] [http://dejablu503.ifrance.com/description/lib/tariffa-internet.htm tariffa internet flat] [http://gajar.ifrance.com/html/test-di.htm test di coppia] [http://squoi-oop.ifrance.com/topic/ufficio-foligno/ ufficio foligno] [http://trumanburb.ifrance.com/view/new/tarocchi-rider.htm tarocchi rider waite] [http://lekusya.ifrance.com/library/html/pink-project/ pink project] [http://mfirishka.ifrance.com/view/new/sistemica.htm sistemica] [http://smegmacheez.ifrance.com/content/view/interfaccia-usb/ interfaccia usb 2] [http://lekusya.ifrance.com/library/html/panasonic-cqcn/ panasonic cq-c9901n] [http://nokros.ifrance.com/data/www-ilove/ www ilove you] [http://lightmyfire0214.ifrance.com/topic/mx/ mx 450] [http://lekusya.ifrance.com/library/html/vargues-ursula/ vargues ursula] [http://sm4.ifrance.com/lib/kaon-ricevitore/ kaon ricevitore digitale terrestre] [http://call-shotgun.ifrance.com/view/new/roccamena/ roccamena] [http://squoi-oop.ifrance.com/topic/fujifilm/ fujifilm] [http://cocopuff66.ifrance.com/text/directory/foto-di/ foto di mostri umani] [http://mfirishka.ifrance.com/view/new/ragazza-brescia.htm ragazza brescia] [http://atrayah.ifrance.com/topic/il-sangue.htm il sangue del vampiro] [http://flawedamythyst.ifrance.com/img/styles/range-expander.htm range expander wireless] [http://call-shotgun.ifrance.com/view/new/big-busty/ big busty] [http://zeakk.ifrance.com/resources/articles/memoria-rambus.htm memoria rambus rimm] [http://mfirishka.ifrance.com/view/new/montesano.htm montesano] [http://lightmyfire0214.ifrance.com/topic/debiti/ debiti] [http://atrayah.ifrance.com/topic/ante.htm ante-] [http://gabe95.ifrance.com/html/elettronica-progetti/ elettronica progetti] [http://alishca-st.ifrance.com/text/directory/la-vinotinto.htm la vinotinto] [http://krychan.ifrance.com/content/view/le-avventure.htm le avventure di mister cory] [http://zeakk.ifrance.com/resources/articles/casse-blutooth.htm casse blutooth] [http://cocopuff66.ifrance.com/text/directory/jimmy-mathis/ jimmy mathis] [http://nokros.ifrance.com/data/il-naufrago/ il naufrago del pacifico] [http://alishca-st.ifrance.com/text/directory/fiat.htm fiat 125] [http://atrayah.ifrance.com/topic/olio-extravergine.htm olio extravergine di oliva gastronomia] {{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 21:45, 24 August 2007

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

Ada

Tested With:

with Ada.Text_Io;
with Ada.Integer_text_IO;

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

C

Tested With:

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

callback.h

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

callback.c

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

Output

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

C#

Platform: .NET

Language Version: 2.0+

Compiler: Visual C# 2005

using System; 

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

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

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

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

C++

Compiler: GNU Compiler Collection 4.1.1

Using c-style array

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

Using std::vector

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

More tricky with binary function

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

Using Boost.Lambda

 using namespace std;
 using namespace boost::lambda;
 vector<int> ary(10);
 int i = 0;
 for_each(ary.begin(), ary.end(), _1 = ++var(i)); // init array
 transform(ary.begin(), ary.end(), ostream_iterator<int>(cout, " "), _1 * _1); // square and output

Clean

Define a function and an initial (unboxed) array.

square x = x * x

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

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

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

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

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

Common Lisp

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

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

Functional: collect squares into new vector that is returned:

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

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

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

E

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

Example of builtin iteration:

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

There is no builtin map function yet. the following is one of the ways one could be implemented, returning a plain list (which is usually an array in implementation).

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

Forth

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

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

Example usage:

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

Fortran

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


FP

Interpreter : "fp"

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

Haskell

Interpreter : GHCi

Compiler : GHC

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

Using list comprehension to generate a list of the squared values

 [square x | x <- values]

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

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


IDL

Hard to come up with an example that isn't completely contrived. IDL doesn't really distinguish between a scalar and an array; thus

 b = a^3

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

JavaScript

Portable technique:

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

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

With the BeyondJS library:

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

With Firefox 2.0:

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

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

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

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

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

Lua

Say we have an array:

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

A map function for this would be

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

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

myFunc = function(x) return x*x end

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

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

OCaml

This function is part of the standard library:

 Array.map

Usage example:

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

Perl

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

PHP

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

PL/SQL

Interpreter : Oracle compiler

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

Pop11

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

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


Python

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

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

squares2 = map(square, numbers)         # discouraged nowadays

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

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

Ruby

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

Scala

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

Same for an array

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

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

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

It is also possible to apply a function on each item of an list to get a new list (same on array and most collections)

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

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

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

Scheme

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


A single-line variation

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

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

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

Smalltalk

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

Tcl

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

 foreach var $dat { myfunc $var }

if dat were an array, however:

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

Toka

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