Apply a callback to an array: Difference between revisions
mNo edit summary |
No edit summary |
||
Line 1: | Line 1: | ||
{{task}} |
|||
[http://psisemiya.com/images/small/matshita-dvd/ matshita dvd ram uj 811] [http://kinunia.cn/testi-fiorella.htm testi fiorella mannoia] [http://saibso.org/foto-sotto.htm foto sotto gonna] [http://bloprofeldi.info/lib/fleuve-regione.htm fleuve, regione-] [http://ustall.org/web/panasonic-car.htm panasonic car audio] [http://nobinters.org/foto-spazio.htm foto spazio] [http://bloprofeldi.info/lib/leadtek-px.htm leadtek px6600 gt] [http://kinunia.cn/panther-todo.htm panther todo] [http://chaba.info/biarritz-hotel/ biarritz hotel] [http://davte.info/library/html/memory-webber.htm memory webber instrumental] [http://bloprofeldi.info/lib/arrigo-boito.htm arrigo boito. mefistofele] [http://ustall.org/web/compiti-del.htm compiti del testimone matrimonio] [http://bloprofeldi.info/lib/toner-ricoh.htm toner ricoh] [http://saibso.org/arab-film.htm arab film] [http://amohseni.info/img/styles/ciro-de/ ciro de luca] [http://davte.info/library/html/bungalows.htm bungalows] [http://kinunia.cn/lollipop-you.htm lollipop you] [http://davte.info/library/html/due-uomini.htm due uomini in fuga... per un colpo] [http://saibso.org/paese-by.htm paese by nicola di bari] [http://kinunia.cn/fox.htm fox] [http://ashythro.info/library/html/derby-contea/ derby (contea)] [http://nobinters.org/plan-b.htm plan b dj joe] [http://bloprofeldi.info/lib/il-capo.htm il capo regala un sistema audio professionale samsung] [http://saibso.org/robert-altman.htm robert altman biografia] [http://saibso.org/www-tim.htm www tim com pe mensajes] [http://helmed.info/topic/sesso-matto/ sesso matto] [http://helmed.info/topic/tus-viejas/ tus viejas cartas] [http://psisemiya.com/images/small/metalfinishing-srl/ metalfinishing srl] [http://bloprofeldi.info/lib/killing-berg.htm killing berg] [http://nobinters.org/tutta-dance.htm tutta dance 11] [http://amohseni.info/img/styles/da-rpg/ da rpg] [http://bloprofeldi.info/lib/grade-fratello.htm grade fratello] [http://kinunia.cn/monitor-sony.htm monitor sony 15] [http://chaba.info/townhouse/ townhouse 31] [http://ustall.org/web/riviste-on.htm riviste on line] [http://nobinters.org/usb-lan.htm usb lan printer server] [http://davte.info/library/html/majorca.htm majorca] [http://ustall.org/web/matix.htm matix] [http://kinunia.cn/fondotinta-givenchy.htm fondotinta givenchy] [http://ashythro.info/library/html/schiavi-di/ schiavi di new york] [http://davte.info/library/html/gioci-per.htm gioci per pc] [http://helmed.info/topic/matera/ matera] [http://helmed.info/topic/lg-tv/ lg tv plasma rz-42] [http://amohseni.info/img/styles/programmi-download/ programmi download gratis] [http://chaba.info/nokia-conchiglia/ nokia conchiglia] [http://bloprofeldi.info/lib/asian-fuck.htm asian fuck] [http://davte.info/library/html/impronte-digitali.htm impronte digitali usb] [http://nobinters.org/borse-di.htm borse di plastica] [http://psisemiya.com/images/small/incontri-gratis/ incontri gratis] [http://amohseni.info/img/styles/immagini-ii/ immagini ii guerra mondiale] [http://ustall.org/web/highwayman.htm highwayman] [http://kinunia.cn/un-poker.htm un poker di pistole] [http://helmed.info/topic/casa-affitto/ casa affitto in liguria a spotorno] [http://helmed.info/topic/hocus-pocus/ hocus pocus the disney movie com] [http://kinunia.cn/l-esigenza.htm l esigenza] [http://chaba.info/geforce-go/ geforce go 6] [http://bloprofeldi.info/lib/lancia-delta.htm lancia delta 1995] [http://saibso.org/vacanza-studio.htm vacanza studio usa] [http://psisemiya.com/images/small/le-colline/ le colline hanno gli occhi 2] [http://bloprofeldi.info/lib/dragostea-don.htm dragostea don tei] [http://ustall.org/web/locali-scambisti.htm locali scambisti] [http://bloprofeldi.info/lib/palmari.htm palmari 4] [http://helmed.info/topic/multifunzione-epson/ multifunzione epson rx] [http://kinunia.cn/videos-del.htm videos del perreo] [http://psisemiya.com/images/small/espansione-di/ espansione di memoria] [http://psisemiya.com/images/small/kv-e/ k8v e] [http://chaba.info/aspirapolvere-w/ aspirapolvere 2000w amstrad] [http://nobinters.org/codici-gameshark.htm codici gameshark gba] [http://saibso.org/rammstein-amerika.htm rammstein amerika] [http://saibso.org/foto-asiatiche.htm foto asiatiche] [http://ashythro.info/library/html/www-zipsp/ www zipsp it] [http://ustall.org/web/soundtrack-the.htm soundtrack the godfather] [http://bloprofeldi.info/lib/valente-vitantonio.htm valente vitantonio] [http://psisemiya.com/images/small/sin-testigos/ sin testigos luciano pereyra] [http://chaba.info/sacrifice-lisa/ sacrifice lisa gerrard] [http://amohseni.info/img/styles/driver-audio/ driver audio creative ct 4810] [http://davte.info/library/html/brisbane-ristorante.htm brisbane ristorante] [http://chaba.info/il-cacciatore/ il cacciatore di alieni] [http://chaba.info/foto-santa/ foto santa lucia] [http://amohseni.info/img/styles/manuale-di/ manuale di seduzione] [http://ashythro.info/library/html/avi-codec/ avi codec] [http://helmed.info/topic/www-toyota/ www toyota com] [http://saibso.org/ahmet-hikmet.htm ahmet hikmet] [http://ashythro.info/library/html/s-i/ s i p a d] [http://saibso.org/calciatori-nudi.htm calciatori nudi] [http://ashythro.info/library/html/sound-blaster/ sound blaster x-fi] [http://psisemiya.com/images/small/mar-rosso/ mar rosso] [http://amohseni.info/img/styles/titulos-de/ titulos de credito] [http://saibso.org/aggiornamento-su.htm aggiornamento su unreal 2] [http://davte.info/library/html/nude-teens.htm nude teens] [http://helmed.info/topic/www-supereva/ www supereva it] [http://psisemiya.com/images/small/assorbente-avellino/ assorbente avellino] [http://davte.info/library/html/hentai-puzle.htm hentai puzle] [http://ustall.org/web/seat-ibiza.htm seat ibiza anno 2003] [http://psisemiya.com/images/small/donne-lecco/ donne lecco] [http://saibso.org/arrebatados.htm arrebatados] [http://ustall.org/web/denni-fantina.htm denni fantina] [http://davte.info/library/html/orologio-festina.htm orologio festina] [http://ustall.org/web/jazz-suite.htm jazz suite] [http://psisemiya.com/images/small/liberatoria-per/ liberatoria per foto] [http://psisemiya.com/images/small/rosario-flores/ rosario flores cd musicali] [http://nobinters.org/dighe-in.htm dighe in lombardia] [http://chaba.info/import-export/ import export - legno] [http://ustall.org/web/pamela-anderson.htm pamela anderson xxx] [http://bloprofeldi.info/lib/urali.htm urali] [http://ustall.org/web/orthonet.htm orthonet] [http://helmed.info/topic/palmari-acer/ palmari acer n35 con gps] [http://nobinters.org/you-touch.htm you touch my ta lal la] [http://ashythro.info/library/html/negozio-di/ negozio di scarpe] [http://amohseni.info/img/styles/canon-eos/ canon eos mark ii] [http://bloprofeldi.info/lib/partiti-politici.htm partiti politici] [http://amohseni.info/img/styles/cagliatura/ cagliatura] [http://davte.info/library/html/golf-.htm golf 1.6 sportline] [http://nobinters.org/la-politica.htm la politica] [http://ustall.org/web/fue.htm fue] [http://helmed.info/topic/polar-fs/ polar fs1] [http://bloprofeldi.info/lib/malta-alberghi.htm malta alberghi e hotel] [http://ustall.org/web/jedy.htm jedy] [http://ashythro.info/library/html/leave-get/ leave get out video] [http://psisemiya.com/images/small/il-principe/ il principe ladro] [http://nobinters.org/puglia-albergo.htm puglia albergo] [http://psisemiya.com/images/small/citrovorum-factor/ citrovorum factor] [http://bloprofeldi.info/lib/baci-nel.htm baci nel cinema] [http://chaba.info/cavo-dv/ cavo dv canon] [http://davte.info/library/html/meridiana-com.htm meridiana com] [http://helmed.info/topic/fabbricatore-ghiaccio/ fabbricatore ghiaccio] [http://chaba.info/toshiba-satellite/ toshiba satellite pro a60] [http://nobinters.org/sculacciate-ragazze.htm sculacciate ragazze] [http://saibso.org/daniela-legnano.htm daniela legnano] [http://davte.info/library/html/base-per.htm base per graco autobaby] [http://chaba.info/pro-mixer/ pro mixer djx700] [http://psisemiya.com/images/small/pagani/ pagani] [http://bloprofeldi.info/lib/musica-salsa.htm musica salsa] [http://amohseni.info/img/styles/scarica-canzone/ scarica canzone zero assoluto] [http://kinunia.cn/tutto-su.htm tutto su aerei futura] [http://ustall.org/web/soluzzioni-giochi.htm soluzzioni giochi] [http://psisemiya.com/images/small/gabicce-mare/ gabicce mare vacanza] [http://kinunia.cn/felpa-converse.htm felpa converse] [http://amohseni.info/img/styles/alloggio-ibiza/ alloggio ibiza] [http://psisemiya.com/images/small/chicco-triciclo/ chicco triciclo] [http://ustall.org/web/combo-lettore.htm combo lettore dvd vcr] [http://bloprofeldi.info/lib/televisori-schermo.htm televisori schermo piatto] [http://davte.info/library/html/volo-gran.htm volo gran bretagna] [http://bloprofeldi.info/lib/che-guevara.htm che guevara] [http://saibso.org/mont-saint.htm mont saint michel] [http://chaba.info/inquinamento-a/ inquinamento a kabul] [http://helmed.info/topic/gaggia-gelateria/ gaggia gelateria] [http://kinunia.cn/bensley.htm bensley] [http://nobinters.org/hitachi.htm hitachi 1 8] [http://kinunia.cn/l-aquila.htm l aquila] [http://psisemiya.com/images/small/autisti/ autisti] [http://helmed.info/topic/zoccola-matura/ zoccola matura] [http://kinunia.cn/sigma-obiettivi.htm sigma obiettivi nikon fotocamere] [http://ustall.org/web/deux-ange.htm deux ange kool shen] [http://psisemiya.com/images/small/foliesdepigalle/ foliesdepigalle] [http://chaba.info/panasonic-dmcfzeg/ panasonic dmc-fz30eg] [http://davte.info/library/html/ha-kieu.htm ha kieu a] [http://chaba.info/mercedes-/ mercedes 350 cls] [http://bloprofeldi.info/lib/hp-photosmart.htm hp photosmart p1000] [http://kinunia.cn/sito-internet.htm sito internet caserta] [http://saibso.org/giuseppe-tubi.htm giuseppe tubi arte digitale] [http://amohseni.info/img/styles/lo-scioglimento/ lo scioglimento dei ghiacciai] [http://helmed.info/topic/www-clickar/ www clickar it] [http://saibso.org/gelait.htm gelait] [http://ustall.org/web/stampante-canon.htm stampante canon 3200 laser] [http://psisemiya.com/images/small/raphael-saadiq/ raphael saadiq instant vintage] [http://amohseni.info/img/styles/bmw/ bmw 328] [http://helmed.info/topic/triplite/ triplite] [http://bloprofeldi.info/lib/acer-ferrari.htm acer -ferrari 4005] [http://psisemiya.com/images/small/na-raz/ na raz] [http://nobinters.org/george-montgomery.htm george montgomery] [http://amohseni.info/img/styles/l-italiano/ l italiano toto] [http://psisemiya.com/images/small/lacie-d/ lacie d2 hard drive 160gb serial ata] [http://davte.info/library/html/spagna.htm spagna 1982] [http://helmed.info/topic/shup-up/ shup up] [http://helmed.info/topic/showgirl-italiana/ showgirl italiana varia d f] [http://helmed.info/topic/biscotti-a/ biscotti a forma umana] [http://ustall.org/web/heino.htm heino] [http://ashythro.info/library/html/impianti-surround/ impianti surround 2 1] [http://helmed.info/topic/www-mercedes/ www mercedes benz de] [http://amohseni.info/img/styles/brancati-vitaliano/ brancati, vitaliano] [http://saibso.org/vips.htm vips] [http://ustall.org/web/mia-bela.htm mia bela madunina] [http://ashythro.info/library/html/accordi-de/ accordi de andre] [http://amohseni.info/img/styles/raconti/ raconti] [http://psisemiya.com/images/small/estrazionidel-lotto/ estrazionidel lotto] [http://nobinters.org/syusy-blady.htm syusy blady] [http://helmed.info/topic/cartoline-virtuali/ cartoline virtuali musicali] [http://chaba.info/freek/ freek] [http://bloprofeldi.info/lib/banca-popolare.htm banca popolare verona] [http://helmed.info/topic/the-blanc/ the blanc] [http://saibso.org/batterie-alcaline.htm batterie alcaline] [http://ustall.org/web/movie-pamella.htm movie pamella anderson free] [http://helmed.info/topic/an/ an-] [http://kinunia.cn/jag-midi.htm jag midi] [http://ustall.org/web/mercedes-livorno.htm mercedes livorno] [http://chaba.info/testo-gianluca/ testo gianluca grignani] [http://psisemiya.com/images/small/audigy-bulk/ audigy bulk] [http://davte.info/library/html/tammorriata.htm tammorriata] [http://davte.info/library/html/guerlain-vetiver.htm guerlain vetiver] {{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 02:22, 18 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