Apply a callback to an array: Difference between revisions

From Rosetta Code
Content added Content deleted
(revert spam)
mNo edit summary
Line 1: Line 1:
[http://animaetrix00.ifrance.com/content/lettore-dvd/ lettore dvd con uscite audio] [http://thecakeblog.ifrance.com/articles/collegio-periti/ collegio periti tecnici palermo] [http://pouringsunny.ifrance.com/description/george-michel/ george michel] [http://liubash.ifrance.com/new/www-flowerhorn.htm www flowerhorn com] [http://chrystiala.ifrance.com/library/www-horoscopos.htm www horoscopos com mx] [http://cikumuffin.ifrance.com/topic/bearshare-ita/ bearshare ita] [http://liubash.ifrance.com/new/acebal-emilio.htm acebal emilio] [http://beatpoetsa.ifrance.com/description/diapositive-proiettore.htm diapositive proiettore] [http://liubash.ifrance.com/new/smart-usata.htm smart usata] [http://infunt.ifrance.com/articles/celebrity-sex/ celebrity sex] [http://shmarodral.ifrance.com/text/culi-sfondati.htm culi sfondati da cavalli] [http://cikumuffin.ifrance.com/topic/casio-exp/ casio exp700] [http://jazzyjoe.ifrance.com/nikkei-lcd/ nikkei lcd] [http://feelosof.ifrance.com/description/mueve/ mueve] [http://lethalga.ifrance.com/topic/ceolin-group/ ceolin group] [http://listsobacka.ifrance.com/small/nina-mirc.htm nina mirc] [http://seachildelf.ifrance.com/resources/fiat-punto/ fiat punto nuovo] [http://firejedi.ifrance.com/new/www-fihp/ www fihp org] [http://shotlandetz.ifrance.com/blog/leccare-i/ leccare i miei piedi] [http://feelosof.ifrance.com/description/risorsa-midi/ risorsa midi] [http://firejedi.ifrance.com/new/sailo-moon/ sailo moon] [http://cikumuffin.ifrance.com/topic/doveri-costituzione/ doveri costituzione europea] [http://emrinalexander.ifrance.com/styles/powershot-.htm powershot 75 canon] [http://liubash.ifrance.com/new/le-nuove.htm le nuove avventure di furia] [http://seachildelf.ifrance.com/resources/atlantis-i/ atlantis i storm adsl] [http://listsobacka.ifrance.com/small/tupac-shakur.htm tupac shakur hip hop genius] [http://makkiesan.ifrance.com/lacoste-uomo.htm lacoste uomo] [http://belikan.ifrance.com/library/incontro-thiene.htm incontro thiene] [http://cikumuffin.ifrance.com/topic/bang-bus/ bang bus] [http://shmarodral.ifrance.com/text/kelly-clarkson.htm kelly clarkson] [http://makkiesan.ifrance.com/www-pinkfloyd.htm www pinkfloyd con] [http://seachildelf.ifrance.com/resources/suggest-link/ suggest link] [http://feelosof.ifrance.com/description/orologiaio/ orologiaio] [http://feelosof.ifrance.com/description/usb-/ usb 2 mac controller] [http://firejedi.ifrance.com/new/encarta-plus/ encarta plus 2005] [http://pouringsunny.ifrance.com/description/scheda-video/ scheda video pci express geforce 6600] [http://beatpoetsa.ifrance.com/description/christiane-f.htm christiane f noi i ragazzi dello zoo di] [http://emrinalexander.ifrance.com/styles/hyundai-santa.htm hyundai santa f] [http://feelosof.ifrance.com/description/bobble-ice/ bobble ice age] [http://seachildelf.ifrance.com/resources/microonde-candy/ microonde candy] [http://cikumuffin.ifrance.com/topic/morsztyn-zbigniew/ morsztyn zbigniew] [http://infunt.ifrance.com/articles/sistema-modulare/ sistema modulare] [http://thecakeblog.ifrance.com/articles/il-nostro/ il nostro prossimo] [http://animaetrix00.ifrance.com/content/jaguar-xtype/ jaguar xtype executive] [http://liubash.ifrance.com/new/percorsi-autostradali.htm percorsi autostradali e stradali] [http://beatpoetsa.ifrance.com/description/ragazza-chivasso.htm ragazza chivasso] [http://makkiesan.ifrance.com/mientes-tan.htm mientes tan bien] [http://jazzyjoe.ifrance.com/lechwe/ lechwe] [http://ohmygoshalix.ifrance.com/blog/sbn-online.htm sbn online] [http://jojorock.ifrance.com/articles/soddr-ram/ soddr2 ram 512mb] [http://pouringsunny.ifrance.com/description/power/ power 5013] [http://liubash.ifrance.com/new/gemboy-teorema.htm gemboy teorema] [http://seachildelf.ifrance.com/resources/calcio-americano/ calcio americano] [http://makkiesan.ifrance.com/masterizzatore-lg.htm masterizzatore lg black] [http://jazzyjoe.ifrance.com/fly-girl/ fly girl] [http://cikumuffin.ifrance.com/topic/dr-alban/ dr alban] [http://jojorock.ifrance.com/articles/condizionatori-usati/ condizionatori usati] [http://eccoblackfin.ifrance.com/html/fred-vargas.htm fred vargas] [http://thecakeblog.ifrance.com/articles/blaupunkt-casablanca/ blaupunkt casablanca] [http://chrystiala.ifrance.com/library/esecuzione-ostaggi.htm esecuzione ostaggi video] [http://infunt.ifrance.com/articles/bataglie-in/ bataglie in terra] [http://eccoblackfin.ifrance.com/html/moto-storiche.htm moto storiche vendita] [http://shotlandetz.ifrance.com/blog/giochi-lg/ giochi lg u8110] [http://shmarodral.ifrance.com/text/toner-epson.htm toner epson laser] [http://emrinalexander.ifrance.com/styles/reale-mutua.htm reale mutua] [http://shmarodral.ifrance.com/text/nelly-forza.htm nelly forza] [http://liubash.ifrance.com/new/multisala-montebello.htm multisala montebello della battaglia] [http://emrinalexander.ifrance.com/styles/oblomov.htm oblomov] [http://shmarodral.ifrance.com/text/hotel-cristallo.htm hotel cristallo cattolica] [http://beatpoetsa.ifrance.com/description/korg-accordatore.htm korg accordatore] [http://pouringsunny.ifrance.com/description/coral-beach/ coral beach tiran sharm el sheikh] [http://makkiesan.ifrance.com/i-perseguitati.htm i perseguitati] [http://thecakeblog.ifrance.com/articles/impiccato-in/ impiccato in italiano] [http://belikan.ifrance.com/library/samsung-.htm samsung 19 sm910mp] [http://jazzyjoe.ifrance.com/mario-piave/ mario piave] [http://makkiesan.ifrance.com/data-pasqua.htm data pasqua 2005] [http://jazzyjoe.ifrance.com/haim-moshe/ haim moshe] [http://jene7777777.ifrance.com/new/terremoto-in.htm terremoto in giappone] [http://jene7777777.ifrance.com/new/honda-cr.htm honda cr] [http://emrinalexander.ifrance.com/styles/cb-.htm cb 570 canon] [http://beatpoetsa.ifrance.com/description/gen-abizaid.htm gen abizaid and foto] [http://infunt.ifrance.com/articles/cardiofrequenzimetro-polar/ cardiofrequenzimetro polar f1] [http://shotlandetz.ifrance.com/blog/lettori-dvd/ lettori dvd e divx kiss dp 500] [http://jojorock.ifrance.com/articles/rs-mmc/ rs mmc 256 mb 2v] [http://cikumuffin.ifrance.com/topic/cavo-audio/ cavo audio video] [http://shmarodral.ifrance.com/text/agenzia-viaggio.htm agenzia viaggio firenze] [http://listsobacka.ifrance.com/small/temi-sui.htm temi sui cd masterizzati] [http://jene7777777.ifrance.com/new/direzione-tecnica.htm direzione tecnica distribuzio] [http://ohmygoshalix.ifrance.com/blog/cigarettes-and.htm cigarettes and coffe] [http://jazzyjoe.ifrance.com/amplificatori-per/ amplificatori per autoradio] [http://beatpoetsa.ifrance.com/description/fisarmonica-impazzita.htm fisarmonica impazzita midi] [http://seachildelf.ifrance.com/resources/il-killer/ il killer 2] [http://firejedi.ifrance.com/new/julian-beck/ julian beck] [http://shotlandetz.ifrance.com/blog/tatoo-robbie/ tatoo robbie william] [http://emrinalexander.ifrance.com/styles/letizia-grande.htm letizia grande fratello] [http://animaetrix00.ifrance.com/content/sissy-maid/ sissy maid] [http://emrinalexander.ifrance.com/styles/amparai.htm amparai] [http://listsobacka.ifrance.com/small/panama-city.htm panama city] [http://jazzyjoe.ifrance.com/divorzio-consensuale/ divorzio consensuale mantenimento] [http://jojorock.ifrance.com/articles/comune-di/ comune di buonalbergo] [http://liubash.ifrance.com/new/provincia-di.htm provincia di rieti] [http://shmarodral.ifrance.com/text/opel-agila.htm opel agila km 0] [http://shmarodral.ifrance.com/text/tv-samsung.htm tv samsung 29] [http://jojorock.ifrance.com/articles/lara-kroft/ lara kroft] [http://pouringsunny.ifrance.com/description/webcam-creative/ webcam creative labs pc cam 880] [http://eccoblackfin.ifrance.com/html/campitello-matese.htm campitello matese] [http://feelosof.ifrance.com/description/giornale-novella/ giornale novella 2000] [http://shmarodral.ifrance.com/text/trucchi-yu.htm trucchi yu gi oh gioco] [http://pouringsunny.ifrance.com/description/jegar-com/ jegar com] [http://emrinalexander.ifrance.com/styles/ragazze-a.htm ragazze a lugano] [http://jojorock.ifrance.com/articles/offerta-chicago/ offerta chicago] [http://eccoblackfin.ifrance.com/html/dizzi-gillespie.htm dizzi gillespie] [http://jojorock.ifrance.com/articles/www-carrozzina/ www carrozzina passeggino chicco it] [http://chrystiala.ifrance.com/library/medicina-desportiva.htm medicina desportiva] [http://thecakeblog.ifrance.com/articles/oro-e/ oro e gloria la strada per el dorado] [http://listsobacka.ifrance.com/small/miele-w.htm miele w 3365 wps] [http://feelosof.ifrance.com/description/un-altra/ un altra poesia] [http://beatpoetsa.ifrance.com/description/voyeur-erotica.htm voyeur erotica] [http://jene7777777.ifrance.com/new/biliardo-.htm biliardo 9 ball] [http://jazzyjoe.ifrance.com/segreti-inconfessabili/ segreti inconfessabili] [http://belikan.ifrance.com/library/sui-monti.htm sui monti e sui mar] [http://shmarodral.ifrance.com/text/pool.htm pool] [http://seachildelf.ifrance.com/resources/navman-icn/ navman icn510] [http://liubash.ifrance.com/new/laserjet-hp.htm laserjet hp 1300] [http://thecakeblog.ifrance.com/articles/camina/ camina] [http://shotlandetz.ifrance.com/blog/ups-va/ ups 650va] [http://beatpoetsa.ifrance.com/description/vitalij-kuprij.htm vitalij kuprij] [http://seachildelf.ifrance.com/resources/http-www/ http www 222z com] [http://thecakeblog.ifrance.com/articles/winning-eleven/ winning eleven ritorna in sala giochi] [http://makkiesan.ifrance.com/la-z.htm la z] [http://eccoblackfin.ifrance.com/html/egged-english.htm egged english] [http://infunt.ifrance.com/articles/citroen-c/ citroen c3 14 hdi] [http://shotlandetz.ifrance.com/blog/fowler-henry/ fowler henry watson] [http://thecakeblog.ifrance.com/articles/festa-donna/ festa donna immagine] [http://jene7777777.ifrance.com/new/catina-italia.htm catina italia] [http://jojorock.ifrance.com/articles/www-mtv/ www mtv la con] [http://infunt.ifrance.com/articles/san-costantino/ san costantino] [http://jene7777777.ifrance.com/new/vvf.htm vvf] [http://feelosof.ifrance.com/description/guerra-vietnam/ guerra vietnam] [http://ohmygoshalix.ifrance.com/blog/dvd-shrink.htm dvd shrink italian language] [http://shotlandetz.ifrance.com/blog/forum-barcelona/ forum barcelona 2004] [http://thecakeblog.ifrance.com/articles/harfleur/ harfleur] [http://jene7777777.ifrance.com/new/tdk-cd.htm tdk cd 4x] [http://makkiesan.ifrance.com/dual-voltage.htm dual voltage 512] [http://firejedi.ifrance.com/new/sci-da/ sci da scialpinismo] [http://jazzyjoe.ifrance.com/tokina/ tokina 12 24] [http://listsobacka.ifrance.com/small/terme-lazzise.htm terme lazzise] [http://lethalga.ifrance.com/topic/scarpe-birkenstock/ scarpe birkenstock] [http://cikumuffin.ifrance.com/topic/comunicati-figc/ comunicati figc] [http://belikan.ifrance.com/library/zelda-wind.htm zelda wind waker] [http://belikan.ifrance.com/library/basta.htm basta] [http://liubash.ifrance.com/new/tu-no.htm tu no] [http://jojorock.ifrance.com/articles/horocopo/ horocopo] [http://jojorock.ifrance.com/articles/qtec-w/ qtec 550w] [http://firejedi.ifrance.com/new/sandra-dee/ sandra dee] [http://shotlandetz.ifrance.com/blog/musiche-rilassanti/ musiche rilassanti] [http://ohmygoshalix.ifrance.com/blog/jp.htm jp] [http://beatpoetsa.ifrance.com/description/volvere-dlg.htm volvere dlg] [http://thecakeblog.ifrance.com/articles/sogno-erotico/ sogno erotico con serena autieri] [http://listsobacka.ifrance.com/small/stampante-etichetta.htm stampante etichetta] [http://seachildelf.ifrance.com/resources/mi-manchi/ mi manchi accordi] [http://thecakeblog.ifrance.com/articles/reticolato-geografico/ reticolato geografico] [http://emrinalexander.ifrance.com/styles/luca-visentini.htm luca visentini] [http://firejedi.ifrance.com/new/zyxel-prestige/ zyxel prestige 660hw] [http://infunt.ifrance.com/articles/vans-calzature/ vans calzature] [http://ohmygoshalix.ifrance.com/blog/calendario-carolina.htm calendario carolina grande fratello] [http://belikan.ifrance.com/library/fuking-stories.htm fuking stories] [http://thecakeblog.ifrance.com/articles/monitor-/ monitor 19 lcd 4ms] [http://eccoblackfin.ifrance.com/html/corse-clandestine.htm corse clandestine di macchine] [http://ohmygoshalix.ifrance.com/blog/quake-.htm quake 3 cd key] [http://emrinalexander.ifrance.com/styles/altoforno.htm altoforno] [http://pouringsunny.ifrance.com/description/giulio-scarpati/ giulio scarpati] [http://animaetrix00.ifrance.com/content/agenzia-trasloco/ agenzia trasloco] [http://jazzyjoe.ifrance.com/hp-ipaq/ hp ipaq h6340 gprs] [http://feelosof.ifrance.com/description/unive-it/ unive it] [http://infunt.ifrance.com/articles/km-fiat/ km0 fiat panda 4x4 benzina auto km 0] [http://seachildelf.ifrance.com/resources/grupo-climax/ grupo climax za za za] [http://ohmygoshalix.ifrance.com/blog/lavagna-ufficio.htm lavagna ufficio] [http://jene7777777.ifrance.com/new/tecniche-di.htm tecniche di invecchiamento] [http://feelosof.ifrance.com/description/gamepad-converter/ gamepad converter] [http://shotlandetz.ifrance.com/blog/david-caruso/ david caruso] [http://chrystiala.ifrance.com/library/norah-jones.htm norah jones sunrise] [http://chrystiala.ifrance.com/library/ati-x.htm ati x300 se] [http://ohmygoshalix.ifrance.com/blog/www-alleanza.htm www alleanza it] [http://thecakeblog.ifrance.com/articles/ligabue-questa/ ligabue questa e la mia vita] [http://jojorock.ifrance.com/articles/suburbia-tracklist/ suburbia tracklist] [http://pouringsunny.ifrance.com/description/king-s/ king s of convenience] [http://animaetrix00.ifrance.com/content/xbox-codici/ xbox codici] [http://infunt.ifrance.com/articles/bocelli-eros/ bocelli eros] [http://belikan.ifrance.com/library/fm-mp.htm fm mp3 trasmettitore] [http://thecakeblog.ifrance.com/articles/www-rendy/ www rendy ingerman calendario 2004 i] [http://jene7777777.ifrance.com/new/edizioni-musicali.htm edizioni musicali] [http://thecakeblog.ifrance.com/articles/tivoli-radio/ tivoli radio cd] [http://chrystiala.ifrance.com/library/tgs.htm tgs] [http://beatpoetsa.ifrance.com/description/beethoven-inno.htm beethoven inno alla gioia] [http://eccoblackfin.ifrance.com/html/klondike.htm klondike] [http://cikumuffin.ifrance.com/topic/congelatore-a/ congelatore a cassetti smeg] [http://feelosof.ifrance.com/description/toner-laser/ toner laser] [http://pouringsunny.ifrance.com/description/le-ore/ le ore piccole midi] [http://jazzyjoe.ifrance.com/countdown-vampires/ countdown vampires] [http://animaetrix00.ifrance.com/content/nigdy-nie/ nigdy nie by 322 o] [http://animaetrix00.ifrance.com/content/canon-mvx/ canon mvx 350i] [http://thecakeblog.ifrance.com/articles/cassonetti-per/ cassonetti per rifiuti] [http://animaetrix00.ifrance.com/content/produzione-materie/ produzione materie pla] [http://beatpoetsa.ifrance.com/description/navigatore-gps.htm navigatore gps] [http://belikan.ifrance.com/library/arcer.htm arcer] [http://jojorock.ifrance.com/articles/trust-schede/ trust schede acquisizione e tv] [http://seachildelf.ifrance.com/resources/incontro-a/ incontro a parigi] [http://makkiesan.ifrance.com/video-de.htm video de roxana diaz y jorge reyes] [http://seachildelf.ifrance.com/resources/www-aprilia/ www aprilia it] [http://jene7777777.ifrance.com/new/mummu.htm mummu] [http://infunt.ifrance.com/articles/siti-hentay/ siti hentay] [http://shmarodral.ifrance.com/text/cockerell-sir.htm cockerell sir christopher si] [http://belikan.ifrance.com/library/galapagos.htm galapagos] [http://shotlandetz.ifrance.com/blog/vetroceramica-piani/ vetroceramica piani cottura] [http://liubash.ifrance.com/new/nvidia-nx.htm nvidia nx6600] [http://lethalga.ifrance.com/topic/igor-stravinsky/ igor stravinsky le rossignol] [http://thecakeblog.ifrance.com/articles/simulatore-di/ simulatore di volo videogiochi] [http://makkiesan.ifrance.com/disk-cooler.htm disk cooler] [http://pouringsunny.ifrance.com/description/risultati-test/ risultati test ammisione medicina 2004] [http://liubash.ifrance.com/new/casse-acustiche.htm casse acustiche 2 1 pioneer] [http://emrinalexander.ifrance.com/styles/katrin-schubert.htm katrin schubert] [http://cikumuffin.ifrance.com/topic/laporno/ laporno] [http://jojorock.ifrance.com/articles/hd-esterno/ hd esterno silver 80gb usb 2 0 2 5] [http://belikan.ifrance.com/library/legislacion-comparada.htm legislacion comparada de violencia famil] [http://firejedi.ifrance.com/new/hyderabad-pakistan/ hyderabad (pakistan)] [http://pouringsunny.ifrance.com/description/tribunale-d/ tribunale d inquisizione] [http://jene7777777.ifrance.com/new/tuta-asics.htm tuta asics] [http://chrystiala.ifrance.com/library/porta-borraccia.htm porta borraccia running] [http://jojorock.ifrance.com/articles/alfa-romeo/ alfa romeo 166 super] [http://thecakeblog.ifrance.com/articles/la-mia/ la mia auto usata toscana] [http://makkiesan.ifrance.com/benq-dvd.htm benq dvd] [http://eccoblackfin.ifrance.com/html/bankiva.htm bankiva] [http://shotlandetz.ifrance.com/blog/nivelles/ nivelles] [http://thecakeblog.ifrance.com/articles/elegante-de/ elegante de boutique] [http://shmarodral.ifrance.com/text/opere-di.htm opere di haendel] [http://infunt.ifrance.com/articles/naqoura/ naqoura] [http://jojorock.ifrance.com/articles/londa-lunga/ londa lunga] [http://beatpoetsa.ifrance.com/description/heavy-on.htm heavy on my heart anastacia] [http://jazzyjoe.ifrance.com/trebol-clan/ trebol clan no le temas ha el] [http://chrystiala.ifrance.com/library/iscrizioni-wwe.htm iscrizioni wwe] [http://beatpoetsa.ifrance.com/description/barby.htm barby] [http://feelosof.ifrance.com/description/video-scandalo/ video scandalo celebrita] [http://makkiesan.ifrance.com/firebird.htm firebird 2015] [http://infunt.ifrance.com/articles/siti-tipografie/ siti tipografie svizzera] [http://firejedi.ifrance.com/new/copertina-cd/ copertina cd zecchino d oro 47] [http://listsobacka.ifrance.com/small/harry-potter.htm harry potter2] [http://shotlandetz.ifrance.com/blog/pile-ricaricabili/ pile ricaricabili torcia] [http://belikan.ifrance.com/library/danza-streghe.htm danza streghe] [http://chrystiala.ifrance.com/library/microonde-incasso.htm microonde incasso whirlpool] {{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


'''Co
'''Compiler:''' [[Visual C sharp|Visual C#]] 2005
2000
mpiler:''' [[Visual C sharp|Visual C#]] 2005


using System;
using System;
Line 155: Line 157:
}
}


==[[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 173:
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 232:
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 269:


(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 303:


: 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 334:


{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 20:34, 10 September 2007

lettore dvd con uscite audio collegio periti tecnici palermo george michel www flowerhorn com www horoscopos com mx bearshare ita acebal emilio diapositive proiettore smart usata celebrity sex culi sfondati da cavalli casio exp700 nikkei lcd mueve ceolin group nina mirc fiat punto nuovo www fihp org leccare i miei piedi risorsa midi sailo moon doveri costituzione europea powershot 75 canon le nuove avventure di furia atlantis i storm adsl tupac shakur hip hop genius lacoste uomo incontro thiene bang bus kelly clarkson www pinkfloyd con suggest link orologiaio usb 2 mac controller encarta plus 2005 scheda video pci express geforce 6600 christiane f noi i ragazzi dello zoo di hyundai santa f bobble ice age microonde candy morsztyn zbigniew sistema modulare il nostro prossimo jaguar xtype executive percorsi autostradali e stradali ragazza chivasso mientes tan bien lechwe sbn online soddr2 ram 512mb power 5013 gemboy teorema calcio americano masterizzatore lg black fly girl dr alban condizionatori usati fred vargas blaupunkt casablanca esecuzione ostaggi video bataglie in terra moto storiche vendita giochi lg u8110 toner epson laser reale mutua nelly forza multisala montebello della battaglia oblomov hotel cristallo cattolica korg accordatore coral beach tiran sharm el sheikh i perseguitati impiccato in italiano samsung 19 sm910mp mario piave data pasqua 2005 haim moshe terremoto in giappone honda cr cb 570 canon gen abizaid and foto cardiofrequenzimetro polar f1 lettori dvd e divx kiss dp 500 rs mmc 256 mb 2v cavo audio video agenzia viaggio firenze temi sui cd masterizzati direzione tecnica distribuzio cigarettes and coffe amplificatori per autoradio fisarmonica impazzita midi il killer 2 julian beck tatoo robbie william letizia grande fratello sissy maid amparai panama city divorzio consensuale mantenimento comune di buonalbergo provincia di rieti opel agila km 0 tv samsung 29 lara kroft webcam creative labs pc cam 880 campitello matese giornale novella 2000 trucchi yu gi oh gioco jegar com ragazze a lugano offerta chicago dizzi gillespie www carrozzina passeggino chicco it medicina desportiva oro e gloria la strada per el dorado miele w 3365 wps un altra poesia voyeur erotica biliardo 9 ball segreti inconfessabili sui monti e sui mar pool navman icn510 laserjet hp 1300 camina ups 650va vitalij kuprij http www 222z com winning eleven ritorna in sala giochi la z egged english citroen c3 14 hdi fowler henry watson festa donna immagine catina italia www mtv la con san costantino vvf guerra vietnam dvd shrink italian language forum barcelona 2004 harfleur tdk cd 4x dual voltage 512 sci da scialpinismo tokina 12 24 terme lazzise scarpe birkenstock comunicati figc zelda wind waker basta tu no horocopo qtec 550w sandra dee musiche rilassanti jp volvere dlg sogno erotico con serena autieri stampante etichetta mi manchi accordi reticolato geografico luca visentini zyxel prestige 660hw vans calzature calendario carolina grande fratello fuking stories monitor 19 lcd 4ms corse clandestine di macchine quake 3 cd key altoforno giulio scarpati agenzia trasloco hp ipaq h6340 gprs unive it km0 fiat panda 4x4 benzina auto km 0 grupo climax za za za lavagna ufficio tecniche di invecchiamento gamepad converter david caruso norah jones sunrise ati x300 se www alleanza it ligabue questa e la mia vita suburbia tracklist king s of convenience xbox codici bocelli eros fm mp3 trasmettitore www rendy ingerman calendario 2004 i edizioni musicali tivoli radio cd tgs beethoven inno alla gioia klondike congelatore a cassetti smeg toner laser le ore piccole midi countdown vampires nigdy nie by 322 o canon mvx 350i cassonetti per rifiuti produzione materie pla navigatore gps arcer trust schede acquisizione e tv incontro a parigi video de roxana diaz y jorge reyes www aprilia it mummu siti hentay cockerell sir christopher si galapagos vetroceramica piani cottura nvidia nx6600 igor stravinsky le rossignol simulatore di volo videogiochi disk cooler risultati test ammisione medicina 2004 casse acustiche 2 1 pioneer katrin schubert laporno hd esterno silver 80gb usb 2 0 2 5 legislacion comparada de violencia famil hyderabad (pakistan) tribunale d inquisizione tuta asics porta borraccia running alfa romeo 166 super la mia auto usata toscana benq dvd bankiva nivelles elegante de boutique opere di haendel naqoura londa lunga heavy on my heart anastacia trebol clan no le temas ha el iscrizioni wwe barby video scandalo celebrita firebird 2015 siti tipografie svizzera copertina cd zecchino d oro 47 harry potter2 pile ricaricabili torcia danza streghe microonde incasso whirlpool

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

Co 2000 mpiler: 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]}