Apply a callback to an array: Difference between revisions
Content added Content deleted
mNo edit summary |
(revert spam) |
||
Line 1: | Line 1: | ||
{{task}} |
|||
[http://manoke.cn/topic/cristian-meier/ cristian meier] [http://xionny.cn/topic/giochi-per/ giochi per motorolav525] [http://soler.net.cn/data/linea-rossa.htm linea rossa 7000] [http://manoke.cn/topic/black/ black2] [http://wedner.info/content/view/duetto.htm duetto] [http://xionny.cn/topic/ibanez-gsa/ ibanez gsa] [http://veggis.org.cn/resources/articles/armadio-x.htm armadio x camerette] [http://polex.com.cn/resources/articles/filmato-decapitazione.htm filmato decapitazione civile a] [http://budget7i.info/lib/terroristi-ceceni/ terroristi ceceni] [http://veggis.org.cn/resources/articles/minibus.htm minibus] [http://svike.info/view/new/barbers-adagio.htm barbers adagio] [http://xionny.cn/topic/modern-groove/ modern groove ministry of sound edition] [http://sneck.info/data/t-sony/ t1 sony] [http://klohy.info/img/styles/puma-scarpe.htm puma scarpe moda tiebreak] [http://veggis.org.cn/resources/articles/taurine.htm taurine] [http://wedner.info/content/view/venetico.htm venetico] [http://sneck.info/data/bandolero-stanco/ bandolero stanco] [http://svike.info/view/new/chicken-.htm chicken invaders] [http://primonona.info/content/view/perfect-niepokonani/ perfect niepokonani] [http://joperan.org/data/compilation-festival/ compilation festival bar] [http://polex.com.cn/resources/articles/lanier-i.htm lanier 5212i] [http://sneck.info/data/blue-staff/ blue staff] [http://svike.info/view/new/jaworzno.htm jaworzno] [http://klohy.info/img/styles/duple.htm duple] [http://joperan.org/data/ivan-segreto/ ivan segreto mp3] [http://manoke.cn/topic/fear/ fear] [http://joperan.org/data/musica-romantica/ musica romantica cl] [http://manoke.cn/topic/fotos-ivy/ fotos ivy queen] [http://budget7i.info/lib/erotico/ erotico] [http://svike.info/view/new/carolina-marconi.htm carolina marconi nuda] [http://veggis.org.cn/resources/articles/hotel-.htm hotel 4 stelle sardegna] [http://manoke.cn/topic/ragazze-taormina/ ragazze taormina] [http://joperan.org/data/asus-ansli/ asus a8n-sli deluxe nforce] [http://veggis.org.cn/resources/articles/let-s.htm let s get] [http://funkall.us/images/small/sfondi-su/ sfondi su articolo31] [http://budget7i.info/lib/portatile-msi/ portatile msi] [http://primonona.info/content/view/chi-tocca/ chi tocca il giallo muore] [http://soler.net.cn/data/ora-legale.htm ora legale 2006] [http://funkall.us/images/small/uruguay-fiume/ uruguay (fiume)] [http://budget7i.info/lib/time-is/ time is running out] [http://wedner.info/content/view/batteria-per.htm batteria per nokia 3100] [http://wedner.info/content/view/guta-de.htm guta de ce ma minti asa] [http://soler.net.cn/data/wolkswagen-passat.htm wolkswagen passat nuova] [http://manoke.cn/topic/foto-scooter/ foto scooter preparati] [http://funkall.us/images/small/living/ living 20] [http://budget7i.info/lib/la-ginestra/ la ginestra] [http://xionny.cn/topic/edu-scuola/ edu scuola] [http://budget7i.info/lib/thierry-mugler/ thierry mugler cologne] [http://soler.net.cn/data/porno-antico.htm porno antico] [http://veggis.org.cn/resources/articles/chopin-bal.htm chopin bal 23] [http://veggis.org.cn/resources/articles/fortunale.htm fortunale] [http://budget7i.info/lib/video-hard/ video hard gratuiti di oggi] [http://veggis.org.cn/resources/articles/queen-limousine.htm queen limousine and service] [http://svike.info/view/new/il-medico.htm il medico per forza] [http://wedner.info/content/view/neoliberalismo.htm neoliberalismo] [http://xionny.cn/topic/jarre-aero/ jarre aero] [http://svike.info/view/new/delta-airline.htm delta airline] [http://veggis.org.cn/resources/articles/irsi.htm irsi] [http://budget7i.info/lib/sony-dcrhc/ sony dcr-hc30] [http://funkall.us/images/small/chat-mexico/ chat mexico] [http://primonona.info/content/view/nilo-bianco/ nilo bianco] [http://wedner.info/content/view/tale-of.htm tale of cinema] [http://xionny.cn/topic/guide-new/ guide new york] [http://klohy.info/img/styles/magari-di.htm magari di renato zero] [http://funkall.us/images/small/rivenditori-auto/ rivenditori auto kia] [http://manoke.cn/topic/giardino-illuminazione/ giardino illuminazione] [http://funkall.us/images/small/la-lunga/ la lunga attesa] [http://sneck.info/data/pegki-zina/ pegki zina] [http://sneck.info/data/regione/ regione] [http://primonona.info/content/view/bersaglio-eccellente/ bersaglio eccellente] [http://veggis.org.cn/resources/articles/il-rompicollo.htm il rompicollo] [http://primonona.info/content/view/kit-home/ kit home theatre con divx] [http://primonona.info/content/view/prestito-isola/ prestito isola del giglio] [http://veggis.org.cn/resources/articles/xiaoxiao.htm xiao-xiao] [http://polex.com.cn/resources/articles/network-news.htm network news] [http://wedner.info/content/view/pudelsi-dawna.htm pudelsi dawna] [http://primonona.info/content/view/chimicale/ chimicale] [http://xionny.cn/topic/bg-sites/ bg sites] [http://manoke.cn/topic/mensile-le/ mensile le ore] [http://klohy.info/img/styles/viata-cu.htm viata cu tine] [http://budget7i.info/lib/camping-la/ camping la mandragola] [http://primonona.info/content/view/erikson-e/ erikson e la crisi psico sociale] [http://svike.info/view/new/oncinema-media.htm oncinema media center] [http://xionny.cn/topic/grumiaux-arthur/ grumiaux, arthur] [http://veggis.org.cn/resources/articles/dernier.htm dernier] [http://wedner.info/content/view/la-cordobesa.htm la cordobesa] [http://klohy.info/img/styles/radio-modem.htm radio modem] [http://xionny.cn/topic/prestito-berlin/ prestito berlin] [http://wedner.info/content/view/mine-s.htm mine s doboy] [http://klohy.info/img/styles/monitor-samsung.htm monitor samsung] [http://klohy.info/img/styles/execelsior.htm execelsior] [http://xionny.cn/topic/carrie-otis/ carrie otis] [http://xionny.cn/topic/www-cerbone/ www cerbone moto it] [http://sneck.info/data/fotocopiatrici-xerox/ fotocopiatrici xerox] [http://soler.net.cn/data/sonus-faber.htm sonus faber electa amator] [http://soler.net.cn/data/scuola-agopuntura.htm scuola agopuntura pisa] [http://joperan.org/data/fast-and/ fast and the fourios] [http://sneck.info/data/yulia-nova/ yulia nova] [http://joperan.org/data/bleachin-peakin/ bleachin peakin] [http://budget7i.info/lib/delitto-nella/ delitto nella tempesta] [http://joperan.org/data/inteligente/ inteligente] [http://soler.net.cn/data/castello-gatti.htm castello gatti 3] [http://soler.net.cn/data/el-sol.htm el sol] [http://funkall.us/images/small/yamaha-tt/ yamaha tt 600 re] [http://budget7i.info/lib/festa-in/ festa in famiglia] [http://veggis.org.cn/resources/articles/inni-di.htm inni di calcio vola lazio vola] [http://soler.net.cn/data/nives-celzijus.htm nives celzijus] [http://veggis.org.cn/resources/articles/isola-dei.htm isola dei famosi2] [http://manoke.cn/topic/monaldi/ monaldi] [http://joperan.org/data/suonerie-siemens/ suonerie siemens c62] [http://wedner.info/content/view/trussardi-cagliari.htm trussardi cagliari] [http://klohy.info/img/styles/batman.htm batman 5] [http://manoke.cn/topic/yahoo-france/ yahoo france] [http://joperan.org/data/viaggi-last/ viaggi last minute] [http://joperan.org/data/gordon-lightfoot/ gordon lightfoot] [http://budget7i.info/lib/de-bary/ de bary, heinrich anton] [http://manoke.cn/topic/il-dopoguerra/ il dopoguerra della 2 guerra mondiale] [http://manoke.cn/topic/il-nostro/ il nostro anniversario] [http://primonona.info/content/view/day-daniel/ day daniel] [http://joperan.org/data/imbarcazione-motore/ imbarcazione motore] [http://primonona.info/content/view/free-sex/ free sex pics] [http://joperan.org/data/giochi-del/ giochi del 3000] [http://funkall.us/images/small/dolci-italiani/ dolci italiani] [http://svike.info/view/new/produccion-artesanal.htm produccion artesanal] [http://funkall.us/images/small/microsoft-xp/ microsoft xp home edition] [http://budget7i.info/lib/concessionari-lotus/ concessionari lotus] [http://budget7i.info/lib/televisori-hd/ televisori hd ready] [http://klohy.info/img/styles/athlon-.htm athlon 64 fx-53] [http://funkall.us/images/small/www-canzoni/ www canzoni da scaricare it] [http://budget7i.info/lib/the-rock/ the rock steady crew] [http://manoke.cn/topic/illegal-baby/ illegal baby sex] [http://soler.net.cn/data/agenzie-spettacolo.htm agenzie spettacolo bologna] [http://xionny.cn/topic/hard-disk/ hard disk ultra dma 133] [http://soler.net.cn/data/garzanti-aldo.htm garzanti, aldo] [http://manoke.cn/topic/dymo/ dymo 450] [http://budget7i.info/lib/sony-dcrdvd/ sony dcr-dvd201] [http://funkall.us/images/small/simone-bigazzi/ simone bigazzi] [http://polex.com.cn/resources/articles/no-face.htm no face no name no number] [http://veggis.org.cn/resources/articles/aspirapolvere-ad.htm aspirapolvere ad acqua simac] [http://sneck.info/data/lettori-mp/ lettori mp3 jpg sd] [http://veggis.org.cn/resources/articles/sigma-.htm sigma 24 per minolta] [http://sneck.info/data/bloodrayne-arriva/ bloodrayne arriva su psp] [http://budget7i.info/lib/maserada-sul/ maserada sul piave] [http://polex.com.cn/resources/articles/ventola-cpu.htm ventola cpu amd] [http://budget7i.info/lib/all-stars/ all stars 60s - s] [http://polex.com.cn/resources/articles/automodelli-tamiya.htm automodelli tamiya] [http://polex.com.cn/resources/articles/borgani.htm borgani] [http://budget7i.info/lib/le-r/ le 23r51 samsung] [http://xionny.cn/topic/orchidea/ orchidea 71] [http://klohy.info/img/styles/samsung-cedns.htm samsung ce287dns] [http://joperan.org/data/motorizazione-firenze/ motorizazione firenze] [http://klohy.info/img/styles/de-chacalon.htm de chacalon] [http://xionny.cn/topic/noi-ragazzi/ noi ragazzi] [http://svike.info/view/new/pcie-xgt.htm pci-e x800gt 256 gddr3] [http://funkall.us/images/small/syncback/ syncback] [http://joperan.org/data/bella-gnocca/ bella gnocca] [http://polex.com.cn/resources/articles/attaccapanni-titti.htm attaccapanni titti] [http://primonona.info/content/view/pierre-renoir/ pierre renoir] [http://svike.info/view/new/siti-internet.htm siti internet lecco] [http://svike.info/view/new/hard-disk.htm hard disk esterno teac] [http://wedner.info/content/view/quando-tramonta.htm quando tramonta il sol] [http://polex.com.cn/resources/articles/rj.htm rj12] [http://veggis.org.cn/resources/articles/acquamarina.htm acquamarina] [http://soler.net.cn/data/giardino-gazebo.htm giardino gazebo] [http://wedner.info/content/view/rl.htm rl 36] [http://joperan.org/data/serate-tommy/ serate tommy vee] [http://wedner.info/content/view/modem-adsl.htm modem adsl ericsson] [http://wedner.info/content/view/reg-.htm reg 133 sdram ecc dimm] [http://veggis.org.cn/resources/articles/epson-stylus.htm epson stylus color 670] [http://sneck.info/data/proiettore-per/ proiettore per diapositive] [http://soler.net.cn/data/test-odontoiatria.htm test odontoiatria 2004] [http://klohy.info/img/styles/danza-del.htm danza del vampiro] [http://xionny.cn/topic/formule-per/ formule per equivalenze] [http://joperan.org/data/hotels-/ hotels - bulgaria] [http://soler.net.cn/data/yakumo-hypersound.htm yakumo hypersound car] [http://sneck.info/data/tuga-dolazi/ tuga dolazi kasnije] [http://klohy.info/img/styles/guns-and.htm guns and roses videoclip] [http://manoke.cn/topic/incontro-piombino/ incontro piombino] [http://budget7i.info/lib/chatlibera/ chatlibera] [http://manoke.cn/topic/cuba-libre/ cuba libre - velocipedi ai tropici] [http://funkall.us/images/small/ddr-sdram/ ddr sdram 512] [http://budget7i.info/lib/antonello-de/ antonello de pierro marina la rosa] [http://primonona.info/content/view/amd-athlon/ amd athlon 64 x2 4600] [http://wedner.info/content/view/fotos-de.htm fotos de luciana salasar desnuda] [http://soler.net.cn/data/bianca-guaccero.htm bianca guaccero] [http://veggis.org.cn/resources/articles/foto-inculate.htm foto inculate] [http://veggis.org.cn/resources/articles/hilary-duff.htm hilary duff metamorphosis] [http://joperan.org/data/il-film/ il film al calar delle tenebre in dvd] [http://xionny.cn/topic/corton/ corton] [http://wedner.info/content/view/jeans-criminal.htm jeans criminal] [http://wedner.info/content/view/van-morrison.htm van morrison days like this] [http://manoke.cn/topic/microfono-ps/ microfono ps2] [http://budget7i.info/lib/baricco/ baricco] [http://manoke.cn/topic/sandals/ sandals] [http://joperan.org/data/la-passionaria/ la passionaria] [http://veggis.org.cn/resources/articles/ford-focus.htm ford focus anno 2004] [http://sneck.info/data/gioco-mac/ gioco mac sport] [http://manoke.cn/topic/aiptek/ aiptek 5700] [http://funkall.us/images/small/cosa/ cosa] [http://funkall.us/images/small/worldsex-it/ worldsex it] {{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 |