Apply a callback to an array: Difference between revisions
mNo edit summary |
(Undo revision 6972 by Special:Contributions/TucRup (User talk:TucRup)) |
||
Line 1: | Line 1: | ||
{{task}} |
|||
[http://tizolaa.ifrance.com/web/italy-hotel/ italy hotel reservation] [http://igaros.ifrance.com/lib/audi-a/ audi a6 2.5 tdi] [http://toofarfrommaybe.ifrance.com/view/new/compact-flash/ compact flash sandisk] [http://tizolaa.ifrance.com/web/carrier-condizionatori/ carrier condizionatori e ventilatori] [http://lovereceier.ifrance.com/lib/winmorph.htm winmorph] [http://toofarfrommaybe.ifrance.com/view/new/pigro-kar/ pigro kar] [http://yeeden.ifrance.com/img/styles/caccia-burgas/ caccia burgas] [http://demurediablo.ifrance.com/library/html/scarica-libro/ scarica libro harry potter e il prigioni] [http://demurediablo.ifrance.com/library/html/la-compagna/ la compagna di banco] [http://lovereceier.ifrance.com/lib/fuck-you.htm fuck you right back di kf tree] [http://lordsander.ifrance.com/topic/sreca-songkillers.htm sreca songkillers] [http://voltia.ifrance.com/content/view/noleggio-auto.htm noleggio auto torino] [http://singaporepets.ifrance.com/library/html/fotografia-aerea.htm fotografia aerea] [http://voltia.ifrance.com/content/view/letz-en.htm letz en go1] [http://yeeden.ifrance.com/img/styles/jvc/ jvc 26] [http://noxuhax.ifrance.com/content/view/associazione.htm associazione] [http://tizolaa.ifrance.com/web/ilaria-d/ ilaria d amico] [http://kalian42.ifrance.com/text/directory/tefal-kaleo/ tefal kaleo 2] [http://igaros.ifrance.com/lib/cappa-company/ cappa company] [http://jdawsona.ifrance.com/data/cachando/ cachando] [http://lovereceier.ifrance.com/lib/panda-.htm panda 750 young] [http://oiyaoi.ifrance.com/images/small/gay-dating/ gay dating] [http://demurediablo.ifrance.com/library/html/radeon-xpro/ radeon x800pro] [http://tat-ooin.ifrance.com/resources/articles/hornet-.htm hornet 600 honda] [http://igaros.ifrance.com/lib/bocelli-eros/ bocelli eros] [http://oiyaoi.ifrance.com/images/small/stabilizzatore-ottico/ stabilizzatore ottico] [http://tat-ooin.ifrance.com/resources/articles/fujifilm-finepix.htm fujifilm finepix a345] [http://toofarfrommaybe.ifrance.com/view/new/foppapedretti-technology/ foppapedretti technology passeggino] [http://toofarfrommaybe.ifrance.com/view/new/carolina-e/ carolina e tommy] [http://tizolaa.ifrance.com/web/sistema-ortogonale/ sistema ortogonale lotto] [http://lordsander.ifrance.com/topic/cop-dvd.htm cop dvd] [http://yeeden.ifrance.com/img/styles/polistirolo-da/ polistirolo da isolamento] [http://singaporepets.ifrance.com/library/html/claudius-matthias.htm claudius, matthias] [http://kalian42.ifrance.com/text/directory/consegna-il/ consegna il gelato] [http://lordsander.ifrance.com/topic/la-casa.htm la casa en el aire] [http://jdawsona.ifrance.com/data/ferrari-enzo/ ferrari enzo] [http://deviantrus.ifrance.com/topic/camere-ancona/ camere ancona] [http://lordsander.ifrance.com/topic/reggaeton-descargar.htm reggaeton descargar] [http://demurediablo.ifrance.com/library/html/canon-digital/ canon digital ixus 40] [http://lovereceier.ifrance.com/lib/wa.htm wa] [http://lordsander.ifrance.com/topic/musica-arezzo.htm musica arezzo] [http://tat-ooin.ifrance.com/resources/articles/haiduci-dragosta.htm haiduci dragosta din tei] [http://lordsander.ifrance.com/topic/liam-gallagher.htm liam gallagher] [http://igaros.ifrance.com/lib/cavo-scart/ cavo scart rca] [http://tat-ooin.ifrance.com/resources/articles/decoder-terrestre.htm decoder terrestre pc] [http://oiyaoi.ifrance.com/images/small/formulauno-gp/ formulauno gp] [http://tat-ooin.ifrance.com/resources/articles/nubilato-party.htm nubilato party] [http://kalian42.ifrance.com/text/directory/futu/ futu] [http://broadwaylili.ifrance.com/content/view/tania-rusoff.htm tania rusoff] [http://lordsander.ifrance.com/topic/salta.htm salta] [http://noxuhax.ifrance.com/content/view/il-foglio.htm il foglio di giuliano ferrara] [http://lovereceier.ifrance.com/lib/cartier-essence.htm cartier essence declaration] [http://highbulp.ifrance.com/images/small/flli-romano/ flli romano] [http://noxuhax.ifrance.com/content/view/annunci-girls.htm annunci girls milano] [http://igaros.ifrance.com/lib/nany/ nany] [http://lordsander.ifrance.com/topic/informatica-consulenza.htm informatica consulenza (to)] [http://toofarfrommaybe.ifrance.com/view/new/www-casevacanze/ www casevacanze org it] [http://broadwaylili.ifrance.com/content/view/vendita-film.htm vendita film] [http://girlwho-is.ifrance.com/img/styles/hote-tea.htm hote tea gabicce] [http://demurediablo.ifrance.com/library/html/www-plyrics/ www plyrics com] [http://lordsander.ifrance.com/topic/batterie-cellulare.htm batterie cellulare samsung a800] [http://highbulp.ifrance.com/images/small/compressori-subacquei/ compressori subacquei] [http://demurediablo.ifrance.com/library/html/tecnologia-e/ tecnologia e cultura] [http://tat-ooin.ifrance.com/resources/articles/kate-capshaw.htm kate capshaw nata il] [http://kalian42.ifrance.com/text/directory/giochi-soluzioni/ giochi soluzioni] [http://toofarfrommaybe.ifrance.com/view/new/renault-clio/ renault clio 1 4 s] [http://tat-ooin.ifrance.com/resources/articles/inculare.htm inculare] [http://tizolaa.ifrance.com/web/mangiare-per/ mangiare per cani] [http://toofarfrommaybe.ifrance.com/view/new/free-sex/ free sex movies] [http://voltia.ifrance.com/content/view/www-lavoixdunord.htm www lavoixdunord fr] [http://lordsander.ifrance.com/topic/microscopia.htm microscopia] [http://girlwho-is.ifrance.com/img/styles/gioco-bowling.htm gioco bowling] [http://highbulp.ifrance.com/images/small/technosat-/ technosat 9000 ultra satellite receiver] [http://demurediablo.ifrance.com/library/html/www-honda/ www honda crx com] [http://tizolaa.ifrance.com/web/foto-donne/ foto donne sex] [http://akmokanzen.ifrance.com/images/small/trama-di.htm trama di e stato cosi] [http://tat-ooin.ifrance.com/resources/articles/il-mio.htm il mio concerto per te] [http://highbulp.ifrance.com/images/small/il-piccolo/ il piccolo principe] [http://deviantrus.ifrance.com/topic/uomini-depravati/ uomini depravati] [http://oiyaoi.ifrance.com/images/small/le-preposizioni/ le preposizioni italiane libri] [http://broadwaylili.ifrance.com/content/view/originale.htm originale] [http://girlwho-is.ifrance.com/img/styles/ragazzo-collegno.htm ragazzo collegno] [http://lordsander.ifrance.com/topic/lettore-mp.htm lettore mp3 auricolare] [http://highbulp.ifrance.com/images/small/googlke/ googlke] [http://akmokanzen.ifrance.com/images/small/con-radio.htm con radio mp3 teac lettori] [http://noxuhax.ifrance.com/content/view/suez.htm suez] [http://speedofsoun.ifrance.com/text/directory/mitsubishi-l.htm mitsubishi l200 2003] [http://singaporepets.ifrance.com/library/html/jules.htm jules] [http://demurediablo.ifrance.com/library/html/mobil-cremona/ mobil cremona] [http://toofarfrommaybe.ifrance.com/view/new/analisi-poesia/ analisi poesia pascoli] [http://highbulp.ifrance.com/images/small/dahn-felix/ dahn, felix] [http://lordsander.ifrance.com/topic/www-ischia.htm www ischia] [http://jdawsona.ifrance.com/data/iguana-mauro/ iguana mauro picotto] [http://akmokanzen.ifrance.com/images/small/solletico-bisex.htm solletico bisex] [http://broadwaylili.ifrance.com/content/view/terrorismo-e.htm terrorismo e informazione] [http://demurediablo.ifrance.com/library/html/cybershot-dsch/ cybershot dsc-h1] [http://jdawsona.ifrance.com/data/lcd-b/ lcd b o 32] [http://demurediablo.ifrance.com/library/html/brother-bluetooth/ brother bluetooth] [http://girlwho-is.ifrance.com/img/styles/acer-pd.htm acer pd 723] [http://toofarfrommaybe.ifrance.com/view/new/http-webmail/ http webmail cox net] [http://toofarfrommaybe.ifrance.com/view/new/ati-/ ati - sapphire radeon x800pro 256mb ddr] [http://yeeden.ifrance.com/img/styles/lg/ lg 217] [http://tizolaa.ifrance.com/web/buche/ buche] [http://tizolaa.ifrance.com/web/penise/ penise] [http://speedofsoun.ifrance.com/text/directory/penisole.htm penisole] [http://yeeden.ifrance.com/img/styles/brit/ brit] [http://lovereceier.ifrance.com/lib/de-doors.htm de doors] [http://deviantrus.ifrance.com/topic/samsung-fax/ samsung fax] [http://oiyaoi.ifrance.com/images/small/navigatore-tom/ navigatore tom tom 5] [http://demurediablo.ifrance.com/library/html/epson-stylus/ epson stylus photo 830u] [http://speedofsoun.ifrance.com/text/directory/pick-up.htm pick up benzina] [http://broadwaylili.ifrance.com/content/view/ariston-mba.htm ariston mba 45 d2 nfe] [http://jdawsona.ifrance.com/data/la-maschera/ la maschera di vetro. la serie completa] [http://kalian42.ifrance.com/text/directory/bomba-nucleare/ bomba nucleare] [http://lordsander.ifrance.com/topic/olympus-camedia.htm olympus camedia c-480] [http://kalian42.ifrance.com/text/directory/casse-home/ casse home teatre] [http://igaros.ifrance.com/lib/stefan-banica/ stefan banica jr] [http://deviantrus.ifrance.com/topic/le-ragazze/ le ragazze americane] [http://lordsander.ifrance.com/topic/hoover-lavatrici.htm hoover lavatrici] [http://toofarfrommaybe.ifrance.com/view/new/video-trombate/ video trombate gratis] [http://speedofsoun.ifrance.com/text/directory/indossa.htm indossa] [http://yeeden.ifrance.com/img/styles/copertina-blue/ copertina blue a chi mi dice] [http://tat-ooin.ifrance.com/resources/articles/ex-ragazza.htm ex ragazza] [http://tizolaa.ifrance.com/web/stampanti-epson/ stampanti epson c1100] [http://lovereceier.ifrance.com/lib/ocean-cf.htm ocean cf 3411] [http://lovereceier.ifrance.com/lib/divano-in.htm divano in fibra sintetica] [http://kalian42.ifrance.com/text/directory/bicocca-ateneo/ bicocca ateneo] [http://highbulp.ifrance.com/images/small/biggest-boobs/ biggest boobs] [http://jdawsona.ifrance.com/data/pausa-pranzo/ pausa pranzo animale] [http://broadwaylili.ifrance.com/content/view/hero-quest.htm hero quest] [http://tat-ooin.ifrance.com/resources/articles/bellissimi-calendari.htm bellissimi calendari] [http://tat-ooin.ifrance.com/resources/articles/dm.htm dm 124] [http://akmokanzen.ifrance.com/images/small/gsm-pcmcia.htm gsm pcmcia] [http://oiyaoi.ifrance.com/images/small/inno/ inno 33] [http://deviantrus.ifrance.com/topic/killzone/ killzone] [http://demurediablo.ifrance.com/library/html/diffusione-orologi/ diffusione orologi] [http://noxuhax.ifrance.com/content/view/cucine-lecce.htm cucine lecce] [http://voltia.ifrance.com/content/view/leather-belt.htm leather belt case] [http://voltia.ifrance.com/content/view/recorder-dvd.htm recorder dvd lettori e divx] [http://tizolaa.ifrance.com/web/il-romanzo/ il romanzo di una vita] [http://akmokanzen.ifrance.com/images/small/televisore-.htm televisore 32 lcd sharp] [http://deviantrus.ifrance.com/topic/promotional-pen/ promotional pen] [http://tat-ooin.ifrance.com/resources/articles/b-atman.htm b atman] [http://igaros.ifrance.com/lib/sydney-bechet/ sydney bechet] [http://kalian42.ifrance.com/text/directory/muvo-micro/ muvo micro n200] [http://singaporepets.ifrance.com/library/html/carabinieri-prima.htm carabinieri. prima serie. vol. 2] [http://demurediablo.ifrance.com/library/html/modellismo-r/ modellismo r c] [http://broadwaylili.ifrance.com/content/view/motorola-a.htm motorola a1010] [http://voltia.ifrance.com/content/view/eamon-testo.htm eamon testo] [http://tizolaa.ifrance.com/web/istituti-di/ istituti di ricerca di mercato] [http://lordsander.ifrance.com/topic/roper-router.htm roper router] [http://yeeden.ifrance.com/img/styles/lettore-dvd/ lettore dvd da 12v] [http://deviantrus.ifrance.com/topic/lcd-/ lcd 28 monitor] [http://lovereceier.ifrance.com/lib/indice-borsa.htm indice borsa] [http://deviantrus.ifrance.com/topic/come-va/ come va] [http://tat-ooin.ifrance.com/resources/articles/ragazza-pozzuoli.htm ragazza pozzuoli] [http://girlwho-is.ifrance.com/img/styles/ktcp.htm ktc-p2800 256] [http://girlwho-is.ifrance.com/img/styles/dj-sammy.htm dj sammy california dreaming] [http://akmokanzen.ifrance.com/images/small/spedizioni-moto.htm spedizioni moto] [http://broadwaylili.ifrance.com/content/view/mr-bean.htm mr. bean] [http://lovereceier.ifrance.com/lib/film-gay.htm film gay gratis] [http://lordsander.ifrance.com/topic/driver-s.htm driver s3 trio 3d 4 mb gratis] [http://jdawsona.ifrance.com/data/gigaset-siemens/ gigaset siemens s440] [http://noxuhax.ifrance.com/content/view/rapporto-anali.htm rapporto anali] [http://kalian42.ifrance.com/text/directory/distributori-lexicon/ distributori lexicon] [http://oiyaoi.ifrance.com/images/small/epson-stampanti/ epson stampanti aghi] [http://speedofsoun.ifrance.com/text/directory/editar.htm editar] [http://yeeden.ifrance.com/img/styles/kampot-provincia/ kampot (provincia)] [http://oiyaoi.ifrance.com/images/small/le-arene/ le arene a catania] [http://oiyaoi.ifrance.com/images/small/toyota-corolla/ toyota corolla sw 1999] [http://demurediablo.ifrance.com/library/html/racchette-da/ racchette da ping pong] [http://highbulp.ifrance.com/images/small/nick-berg/ nick berg s] [http://igaros.ifrance.com/lib/hack-quarantine/ hack quarantine] [http://tizolaa.ifrance.com/web/batteria-siemens/ batteria siemens c-35] [http://kalian42.ifrance.com/text/directory/powershot-/ powershot 1 pro] [http://igaros.ifrance.com/lib/mature-big/ mature big tits] [http://tat-ooin.ifrance.com/resources/articles/shaza.htm shaza] [http://tat-ooin.ifrance.com/resources/articles/feel-feel.htm feel feel] [http://yeeden.ifrance.com/img/styles/alomar-villalonga/ alomar villalonga, gabriel] [http://yeeden.ifrance.com/img/styles/connessione-internet/ connessione internet flat] [http://oiyaoi.ifrance.com/images/small/spose/ spose] [http://voltia.ifrance.com/content/view/condizionatore-inverter.htm condizionatore inverter] [http://lovereceier.ifrance.com/lib/snowdon.htm snowdon] [http://singaporepets.ifrance.com/library/html/svhs-videoregistratore.htm s-vhs videoregistratore dvd] [http://voltia.ifrance.com/content/view/gigi-d.htm gigi d alessio copertina] [http://kalian42.ifrance.com/text/directory/bigorre/ bigorre] [http://akmokanzen.ifrance.com/images/small/tv-.htm tv 20 catodico] [http://noxuhax.ifrance.com/content/view/mobili-e.htm mobili e scaffalature per ufficio] [http://speedofsoun.ifrance.com/text/directory/creare-biglietto.htm creare biglietto augurio] [http://igaros.ifrance.com/lib/gamecube-come/ gamecube come il super nintendo] [http://jdawsona.ifrance.com/data/libri-italiani/ libri italiani] [http://yeeden.ifrance.com/img/styles/trans-suzanna/ trans suzanna holmes] [http://noxuhax.ifrance.com/content/view/rasmus-guilty.htm rasmus guilty] [http://akmokanzen.ifrance.com/images/small/driver-motorola.htm driver motorola v150] [http://jdawsona.ifrance.com/data/worldsex-com/ worldsex com] [http://demurediablo.ifrance.com/library/html/radio-con/ radio con sveglia] [http://deviantrus.ifrance.com/topic/chicco/ chicco] [http://oiyaoi.ifrance.com/images/small/home-teathre/ home teathre 6 1] [http://oiyaoi.ifrance.com/images/small/bessa-luis/ bessa luis, agustina] [http://yeeden.ifrance.com/img/styles/cartoline-pensionati/ cartoline pensionati] {{task}} |
|||
== [[Ada]] == |
== [[Ada]] == |
||
[[Category:Ada]] |
[[Category:Ada]] |
||
'''Tested With:''' |
'''Tested With:''' |
||
* [[Gnat GPL 2005]] |
* [[Gnat GPL 2005]] |
||
** Amd-64bit-3500 |
** 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 |
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 = |
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 |
(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 |
-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 |
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 01:43, 20 August 2007
You are encouraged to solve this task according to the task description, using any language you may know.
Ada
Tested With:
- Gnat GPL 2005
- Amd-64bit-3500+-WinXP
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
#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