Apply a callback to an array: Difference between revisions
Content added Content deleted
(Undo revision 7277 by Special:Contributions/TucRup (User talk:TucRup)) |
mNo edit summary |
||
Line 1: | Line 1: | ||
[http://unremig.110mb.com/sfruttamento/ sfruttamento] [http://trene-von-anty.110mb.com/description/kingston-.htm kingston 512 mb] [http://blue-olusha.110mb.com/library/not-yet/ not yet] [http://stitchesnglue.110mb.com/box-.htm box 3 5 hd] [http://unremig.110mb.com/finanziamento-cuneo/ finanziamento cuneo] [http://forever-your.110mb.com/data/ormoni-androgeni.htm ormoni androgeni] [http://ultra-creator.110mb.com/articles/grande-fratello.htm grande fratello sito uffuciale] [http://nationavce.110mb.com/view/prestito-chieti.htm prestito chieti] [http://trouble166.110mb.com/mariagrazia.htm mariagrazia] [http://ultra-creator.110mb.com/articles/europe-travel.htm europe travel] [http://gekijuls.110mb.com/ot/ ot 525] [http://lazythoughts.110mb.com/lib/siemens-suoneria/ siemens suoneria cellulare] [http://ultra-creator.110mb.com/articles/dowload-midi.htm dowload midi] [http://dialed.110mb.com/small/chatta-con/ chatta con ragazze nude] [http://unremig.110mb.com/gabry-ponte/ gabry ponte figli pitagora] [http://funk-mastah-ion.110mb.com/data/sutra-diamante.htm sutra diamante] [http://book-wench.110mb.com/text/polar-si/ polar s810i] [http://ultra-creator.110mb.com/articles/mp-player.htm mp3 player wireless] [http://trouble166.110mb.com/torreciudad.htm torreciudad] [http://sneezingpops.110mb.com/rok-and/ rok and roll] [http://some-omeelse.110mb.com/data/ibi-srl.htm ibi srl] [http://some-omeelse.110mb.com/data/ia-riproduzione.htm ia riproduzione nell essere umano] [http://stitchesnglue.110mb.com/isola-di.htm isola di ischia] [http://gekijuls.110mb.com/coup-de/ coup de foudre] [http://some-omeelse.110mb.com/data/dispensatore-acqua.htm dispensatore acqua] [http://gekijuls.110mb.com/virgine/ virgine] [http://unremig.110mb.com/pavarotti-domingo/ pavarotti domingo carreras three tenors] [http://gekijuls.110mb.com/site-blog/ site blog deejay it] [http://gekijuls.110mb.com/incontro-single/ incontro single incontrare donna] [http://book-wench.110mb.com/text/translator-pro/ translator pro 9] [http://sneezingpops.110mb.com/van-aken/ van aken piet] [http://sneezingpops.110mb.com/la-principessa/ la principessa delle ostriche] [http://funk-mastah-ion.110mb.com/data/toy-story.htm toy story giocattoli] [http://sneezingpops.110mb.com/decespugliatori-alpina/ decespugliatori alpina elettrici] [http://funk-mastah-ion.110mb.com/data/www-milo.htm www milo ventimiglia it] [http://unremig.110mb.com/classifica-campionato/ classifica campionato serie b] [http://yeeden.110mb.com/data/mutande-sporche/ mutande sporche] [http://slavkamolot.110mb.com/library/olympus-ds/ olympus ds2] [http://yeeden.110mb.com/data/infonavit-gob/ infonavit gob mx] [http://forever-your.110mb.com/data/raymarine-st.htm raymarine st 40] [http://lazythoughts.110mb.com/lib/ragazzo-malta/ ragazzo malta] [http://ultra-creator.110mb.com/articles/danza-italiana.htm danza italiana] [http://trouble166.110mb.com/i-am.htm i am a woman in love mp3] [http://sneezingpops.110mb.com/sade-flow/ sade flow mp3] [http://gekijuls.110mb.com/xt/ xt 660] [http://sister-sunshine.110mb.com/html/wez-to/ wez to poczuj onar] [http://slavkamolot.110mb.com/library/legge/ legge 1933] [http://ultra-creator.110mb.com/articles/gruppi-musicali.htm gruppi musicali anni 70 opera] [http://blue-olusha.110mb.com/library/caso-moro/ caso moro] [http://stitchesnglue.110mb.com/ddr-mhz.htm ddr 400mhz pc3200] [http://blue-olusha.110mb.com/library/hatene/ hatene] [http://lazythoughts.110mb.com/lib/teac-h/ teac h500] [http://yeeden.110mb.com/data/polistirolo-brescia/ polistirolo brescia] [http://yeeden.110mb.com/data/ricchi/ ricchi] [http://stitchesnglue.110mb.com/monitor-plasma.htm monitor plasma 42] [http://sister-sunshine.110mb.com/html/dance-mat/ dance mat console accessori] [http://gekijuls.110mb.com/la-celestina/ la celestina] [http://funk-mastah-ion.110mb.com/data/recorder-disk.htm recorder disk] [http://olikka.110mb.com/library/lela-porno.htm lela porno] [http://slavkamolot.110mb.com/library/i-gangsters/ i gangsters del fuoco] [http://ultra-creator.110mb.com/articles/vendita-case.htm vendita case verona] [http://blue-olusha.110mb.com/library/esercito-difesa/ esercito difesa it] [http://slavkamolot.110mb.com/library/provveditorato-cosenza/ provveditorato cosenza] [http://olikka.110mb.com/library/quello-strano.htm quello strano sentimento] [http://nationavce.110mb.com/view/lazzo.htm lazzo] [http://funk-mastah-ion.110mb.com/data/home-theatre.htm home theatre con dvd recorder pioneer] [http://mouse-zae.110mb.com/dvd-recordervcr.htm dvd recordervcr] [http://blue-olusha.110mb.com/library/travelmate/ travelmate 200] [http://dialed.110mb.com/small/buona-vita/ buona vita gigi d] [http://funk-mastah-ion.110mb.com/data/da-godere.htm da godere] [http://mouse-zae.110mb.com/ericsson-antenne.htm ericsson antenne] [http://unremig.110mb.com/televisori-/ televisori 40 samsung] [http://unremig.110mb.com/acer-alw/ acer al2671w 26] [http://sister-sunshine.110mb.com/html/piccolo-uomo/ piccolo uomo mia martini] [http://unremig.110mb.com/stephanie-mc/ stephanie mc mahon] [http://mouse-zae.110mb.com/societa-post.htm societa post industriale] [http://dialed.110mb.com/small/maxtor-hd/ maxtor hd] [http://gekijuls.110mb.com/rjeka-croazia/ rjeka croazia] [http://sneezingpops.110mb.com/makadam/ makadam] [http://some-omeelse.110mb.com/data/cartier-rem.htm cartier rem] [http://lazythoughts.110mb.com/lib/fomalhaut/ fomalhaut] [http://forever-your.110mb.com/data/huge-boobs.htm huge boobs] [http://stitchesnglue.110mb.com/snow-on.htm snow on the sahara] [http://stitchesnglue.110mb.com/javel-quest.htm javel quest] [http://slavkamolot.110mb.com/library/nokia-telefonia/ nokia7260 telefonia] [http://unremig.110mb.com/lepidium/ lepidium] [http://lazythoughts.110mb.com/lib/mp-rds/ mp3 rds impianti hifi] [http://yeeden.110mb.com/data/canon-eos/ canon eos digital rebel xt slr] [http://gekijuls.110mb.com/har-disk/ har disk esterno lacie 250] [http://some-omeelse.110mb.com/data/viva-voce.htm viva voce auto bluetooth] [http://sister-sunshine.110mb.com/html/abigail-toyne/ abigail toyne] [http://sister-sunshine.110mb.com/html/yeti-sports/ yeti sports 9] [http://lazythoughts.110mb.com/lib/ricky-martin/ ricky martin livin la vida loca] [http://gekijuls.110mb.com/fotocopiatrice-konica/ fotocopiatrice konica] [http://gekijuls.110mb.com/plunkett-macleane/ plunkett macleane] [http://sneezingpops.110mb.com/acer-aspire/ acer aspire 17 bluetooth] [http://forever-your.110mb.com/data/vieht-video.htm vieht video] [http://ultra-creator.110mb.com/articles/pitesti.htm pitesti] [http://sneezingpops.110mb.com/annuncio-lavoro/ annuncio lavoro mantova] [http://nationavce.110mb.com/view/mahjong-towers.htm mahjong towers] [http://ultra-creator.110mb.com/articles/sava-vita.htm sava vita beghelli] [http://olikka.110mb.com/library/single-it.htm single it] [http://sister-sunshine.110mb.com/html/le-sensitive/ le sensitive] [http://forever-your.110mb.com/data/ati.htm ati 9550 256] [http://trouble166.110mb.com/testo-lo.htm testo lo stara] [http://some-omeelse.110mb.com/data/sora.htm sora] [http://dialed.110mb.com/small/adidas-/ adidas monaco] [http://mouse-zae.110mb.com/drown-in.htm drown in my own tears] [http://mouse-zae.110mb.com/sascha-del.htm sascha del bb] [http://trene-von-anty.110mb.com/description/veterinari-ravenna.htm veterinari ravenna] [http://trouble166.110mb.com/asics-tiger.htm asics tiger calzature] [http://slavkamolot.110mb.com/library/lg-condizionatori/ lg condizionatori dual] [http://sneezingpops.110mb.com/newberry/ newberry] [http://stitchesnglue.110mb.com/got-none.htm got none] [http://stitchesnglue.110mb.com/hard-disk.htm hard disk decoder] [http://slavkamolot.110mb.com/library/oddo/ oddo] [http://some-omeelse.110mb.com/data/provincia-italiane.htm provincia italiane] [http://sister-sunshine.110mb.com/html/asciugacapelli-parete/ asciugacapelli parete] [http://trene-von-anty.110mb.com/description/peccato.htm peccato] [http://lazythoughts.110mb.com/lib/giovanni-re/ giovanni (re di boemia)] [http://nationavce.110mb.com/view/prezzo-infisso.htm prezzo infisso] [http://unremig.110mb.com/code-sky/ code sky 11 2004] [http://funk-mastah-ion.110mb.com/data/calendario-brad.htm calendario brad pitt] [http://book-wench.110mb.com/text/seat-leon/ seat leon concessionario] [http://ultra-creator.110mb.com/articles/sblocco-tre.htm sblocco tre] [http://trouble166.110mb.com/leyendas-y.htm leyendas y mitos] [http://trene-von-anty.110mb.com/description/milano-santo.htm milano santo domingo (repubblica] [http://forever-your.110mb.com/data/telefonini-tim.htm telefonini tim] [http://nationavce.110mb.com/view/koc-daewoo.htm koc daewoo] [http://forever-your.110mb.com/data/singole-a.htm singole a roma] [http://lazythoughts.110mb.com/lib/fotos-da/ fotos da playboy internacional] [http://unremig.110mb.com/new-beetle/ new beetle tdi 101 cv] [http://unremig.110mb.com/motorola-v/ motorola v220 caricabatterie] [http://dialed.110mb.com/small/fiat-strada/ fiat strada] [http://sneezingpops.110mb.com/vitara/ vitara] [http://sister-sunshine.110mb.com/html/ded-my/ ded my] [http://trene-von-anty.110mb.com/description/a-family.htm a family] [http://olikka.110mb.com/library/indiana-line.htm indiana line 5 casse] [http://nationavce.110mb.com/view/hilton-sharm.htm hilton sharm] [http://olikka.110mb.com/library/lara-croft.htm lara croft non e in ritardo] [http://funk-mastah-ion.110mb.com/data/tisana-dimagranti.htm tisana dimagranti] [http://funk-mastah-ion.110mb.com/data/mpeg.htm mpeg4] [http://sneezingpops.110mb.com/videos-gratis/ videos gratis] [http://mouse-zae.110mb.com/gino-fontana.htm gino fontana srl] [http://blue-olusha.110mb.com/library/municipio-somma/ municipio somma lombardo] [http://book-wench.110mb.com/text/mi-vida/ mi vida] [http://book-wench.110mb.com/text/fiesta-de/ fiesta de la] [http://some-omeelse.110mb.com/data/longbow.htm longbow] [http://funk-mastah-ion.110mb.com/data/cryogenteam.htm cryogenteam] [http://gekijuls.110mb.com/tortura/ tortura] [http://unremig.110mb.com/lavatrici-philco/ lavatrici philco] [http://sneezingpops.110mb.com/susy-blady/ susy blady] [http://mouse-zae.110mb.com/dvd-di.htm dvd di phil collins] [http://unremig.110mb.com/piatti-arabi/ piatti arabi] [http://olikka.110mb.com/library/i-believe.htm i believe in miracle] [http://yeeden.110mb.com/data/foto-porno/ foto porno gratis] [http://blue-olusha.110mb.com/library/citta-torino/ citta torino] [http://nationavce.110mb.com/view/everibody-s.htm everibody s changing testo] [http://sister-sunshine.110mb.com/html/pacemaker/ pacemaker] [http://forever-your.110mb.com/data/rendsburg.htm rendsburg] [http://gekijuls.110mb.com/eleonora-rossi/ eleonora rossi drago] [http://sneezingpops.110mb.com/gioco-virtual/ gioco virtual inseminetor] [http://stitchesnglue.110mb.com/tu-sei.htm tu sei re] [http://nationavce.110mb.com/view/www-tecnogym.htm www tecnogym com] [http://yeeden.110mb.com/data/www-globe/ www globe janakantha com] [http://trene-von-anty.110mb.com/description/malattia-professionale.htm malattia professionale] [http://unremig.110mb.com/mini-brescia/ mini brescia] [http://olikka.110mb.com/library/nikon-binocolo.htm nikon binocolo] [http://stitchesnglue.110mb.com/vasto-case.htm vasto case] [http://dialed.110mb.com/small/mezza-notte/ mezza notte di fuoco] [http://gekijuls.110mb.com/r-kelly/ r kelly cassidy] [http://slavkamolot.110mb.com/library/por-que/ por que te amo] [http://stitchesnglue.110mb.com/my-inmortal.htm my inmortal evanescense] [http://funk-mastah-ion.110mb.com/data/kejo.htm kejo] [http://blue-olusha.110mb.com/library/hoover-frigo/ hoover frigo] [http://sneezingpops.110mb.com/la-cavalcata/ la cavalcata dei diavoli rossi] [http://nationavce.110mb.com/view/lettori-dvd.htm lettori dvd rw] [http://lazythoughts.110mb.com/lib/duje/ duje] [http://slavkamolot.110mb.com/library/francesco-sarsi/ francesco sarsi] [http://forever-your.110mb.com/data/mario-venuti.htm mario venuti crudele video] [http://stitchesnglue.110mb.com/chappaqua.htm chappaqua] [http://sneezingpops.110mb.com/organizzatore-di/ organizzatore di eventi] [http://gekijuls.110mb.com/lezione-di/ lezione di musica] [http://stitchesnglue.110mb.com/edoardo-vianello.htm edoardo vianello] [http://forever-your.110mb.com/data/bocs.htm bocs] [http://ultra-creator.110mb.com/articles/desktop-wallpaper.htm desktop wallpaper] [http://sneezingpops.110mb.com/stacey-s/ stacey s mom] [http://trene-von-anty.110mb.com/description/casseforti.htm casseforti] [http://gekijuls.110mb.com/e-c/ e c e una cosa che non] [http://stitchesnglue.110mb.com/dlaczzego.htm dlaczzego] [http://funk-mastah-ion.110mb.com/data/prefabricati.htm prefabricati] [http://slavkamolot.110mb.com/library/lino-banfi/ lino banfi bar dello sport] [http://slavkamolot.110mb.com/library/rom-platform/ rom platform super nintendo] [http://lazythoughts.110mb.com/lib/handycam-sony/ handycam sony hc42e] [http://lazythoughts.110mb.com/lib/magix-foto/ magix foto cd dvd] [http://dialed.110mb.com/small/s-/ s 4280 aspirapolvere] [http://some-omeelse.110mb.com/data/www-wachovia.htm www wachovia com] [http://trene-von-anty.110mb.com/description/fiat-punto.htm fiat punto 1100] [http://stitchesnglue.110mb.com/www-bolleblu.htm www bolleblu it] [http://some-omeelse.110mb.com/data/flakiss.htm flakiss] {{task}} |
|||
{{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 |