Apply a callback to an array: Difference between revisions
Content added Content deleted
mNo edit summary |
(Undo revision 7074 by Special:Contributions/TucRup (User talk:TucRup)) |
||
Line 1: | Line 1: | ||
{{task}} |
|||
[http://milano.rigour.info/habitaciones-infantiles.htm habitaciones infantiles] [http://load.rigour.info/view/new/albergo-lido.htm albergo lido camaiore] [http://content.rigour.info/html/sodimm-memoria/ so-dimm memoria ram] [http://italy.rigour.info/blog/figge.htm figge] [http://note.rigour.info/content/view/calendari.htm calendari 1980] [http://speed.rigour.info/eon.htm eon] [http://note.rigour.info/content/view/pacchetto-di.htm pacchetto di viaggio turistico in spagna] [http://here.rigour.info/blog/amd-.htm amd 64 3500 939 venice] [http://guest.rigour.info/library/html/satiro/ satiro] [http://web.rigour.info/cleaning-house/ cleaning house] [http://here.rigour.info/blog/whats-up.htm whats up mid] [http://guest.rigour.info/library/html/turismo-en/ turismo en peru] [http://it.rigour.info/topic/furioso-polka/ furioso polka] [http://pagina.rigour.info/corri-corri/ corri corri cavallino] [http://milano.rigour.info/morwa.htm morwa] [http://down.rigour.info/blog/shirly.htm shirly] [http://blog.rigour.info/web/astraeus/ astraeus] [http://gratis.rigour.info/content/view/tivoli-ipal.htm tivoli ipal] [http://paga.rigour.info/masterizzatori-usb/ masterizzatori usb lightscribe] [http://here.rigour.info/blog/young-porn.htm young porn] [http://italy.rigour.info/blog/www-nazisti.htm www nazisti] [http://web.rigour.info/messaggio-festa/ messaggio festa donna] [http://gratis.rigour.info/content/view/software-educational.htm software educational] [http://note.rigour.info/content/view/poesia-p.htm poesia p pravo] [http://pagina.rigour.info/lil-wayne/ lil wayne] [http://guest.rigour.info/library/html/re-tratamento/ re tratamento da weasel] [http://content.rigour.info/html/wheda/ wheda] [http://italy.rigour.info/blog/wintec-easy.htm wintec easy palm] [http://milano.rigour.info/concessionarie-ford.htm concessionarie ford] [http://speed.rigour.info/grupo-castigo.htm grupo castigo] [http://dir.rigour.info/televisione-schermo/ televisione schermo piatto 28] [http://web.rigour.info/junco/ junco] [http://note.rigour.info/content/view/isole-canarie.htm isole canarie lanzarote] [http://load.rigour.info/view/new/dallas-apartment.htm dallas apartment] [http://milano.rigour.info/trasbordare.htm trasbordare] [http://paga.rigour.info/moltres/ moltres] [http://paga.rigour.info/favorino/ favorino] [http://dir.rigour.info/voli-last/ voli last minute madrid] [http://pagina.rigour.info/fotocamera-subacquee/ fotocamera subacquee] [http://italy.rigour.info/blog/scenario-music.htm scenario music] [http://guest.rigour.info/library/html/ragazze-di/ ragazze di lecce] [http://gratis.rigour.info/content/view/philips-mf.htm philips mf jet 440] [http://pagina.rigour.info/televisori-schermo/ televisori schermo piatto] [http://uve.rigour.info/blog/pallavoliste.htm pallavoliste] [http://dir.rigour.info/facce-di/ facce di clown foto] [http://content.rigour.info/html/film-di/ film di woody allen] [http://speed.rigour.info/milano-cose.htm milano cose fare] [http://guest.rigour.info/library/html/pio-vi/ pio vi] [http://note.rigour.info/content/view/punto-.htm punto 90 sporting] [http://blog.rigour.info/web/doredo-doremi/ doredo doremi] [http://web.rigour.info/cafe/ cafe1930] [http://speed.rigour.info/le-olimpiadi.htm le olimpiadi] [http://web.rigour.info/car-shoe/ car shoe] [http://all.rigour.info/una-vasca/ una vasca lavelli] [http://all.rigour.info/ultrax-keyboard/ ultrax keyboard] [http://content.rigour.info/html/l-isola/ l isola che non c e bennato] [http://load.rigour.info/view/new/barale-calendario.htm barale calendario] [http://speed.rigour.info/resta-ancora.htm resta ancora dj fish] [http://guest.rigour.info/library/html/acer-tmtci/ acer tm382tci] [http://dir.rigour.info/rc-/ rc 7000 dvd vcr] [http://guest.rigour.info/library/html/truth-is/ truth is] [http://gratis.rigour.info/content/view/charlie-s.htm charlie s angels film dvd] [http://content.rigour.info/html/bilderdijk-willem/ bilderdijk, willem] [http://blog.rigour.info/web/tv-e/ tv e wifi] [http://dir.rigour.info/fotocamera-digitale/ fotocamera digitale sony compatta] [http://uve.rigour.info/blog/sasaki.htm sasaki] [http://milano.rigour.info/yamaha.htm yamaha 350] [http://dir.rigour.info/gena-nolin/ gena nolin] [http://paga.rigour.info/fastweb-modem/ fastweb modem] [http://all.rigour.info/www-bancamediolanum/ www bancamediolanum com] [http://all.rigour.info/instrumentos-de/ instrumentos de medicion de los mayas] [http://dir.rigour.info/storia-erotica/ storia erotica padrona] [http://down.rigour.info/blog/scanmaker-s.htm scanmaker s400 scanner] [http://up.rigour.info/description/lib/player-gp.htm player 3gp] [http://blog.rigour.info/web/notebook-toshiba/ notebook toshiba libretto u100] [http://here.rigour.info/blog/musique-mp.htm musique mp3 gratuite] [http://speed.rigour.info/free-mp.htm free mp3 s] [http://all.rigour.info/farro/ farro] [http://speed.rigour.info/router-adsl.htm router adsl asus] [http://italy.rigour.info/blog/beautiful-country.htm beautiful country] [http://paga.rigour.info/hotel-dimitra/ hotel dimitra beach] [http://web.rigour.info/palmari-ppc/ palmari ppc] [http://guest.rigour.info/library/html/harleydavidson-/ harley-davidson 1450 electra glide] [http://all.rigour.info/masterizzatore-dvd/ masterizzatore dvd per mac] [http://down.rigour.info/blog/guardaroba-armadi.htm guardaroba armadi] [http://blog.rigour.info/web/intel-pentium/ intel pentium 660] [http://milano.rigour.info/hard-disk.htm hard disk ps2 usb] [http://gratis.rigour.info/content/view/pioneer.htm pioneer 50] [http://web.rigour.info/surround-system/ surround system] [http://web.rigour.info/carica-batteria/ carica batteria solare] [http://all.rigour.info/lexmark/ lexmark 5250] [http://gratis.rigour.info/content/view/techno-.htm techno 2004 dj ro 380 ni] [http://gratis.rigour.info/content/view/lettini-pali.htm lettini pali tommy] [http://web.rigour.info/citroen-c/ citroen c4 hdi] [http://web.rigour.info/donne-robuste/ donne robuste] [http://here.rigour.info/blog/tx-italia.htm tx italia] [http://note.rigour.info/content/view/estou-apaixonado.htm estou apaixonado] [http://paga.rigour.info/aeroplani-militari/ aeroplani militari] [http://milano.rigour.info/www-promessi.htm www promessi sposi it] [http://gratis.rigour.info/content/view/samsung.htm samsung 2040] [http://note.rigour.info/content/view/dvd-r.htm dvd r vergini tdk] [http://italy.rigour.info/blog/la-piccola.htm la piccola campionessa] [http://italy.rigour.info/blog/destiny-s.htm destiny s child music video say my na] [http://load.rigour.info/view/new/stranom.htm stranom] [http://paga.rigour.info/hotel-mare/ hotel mare] [http://load.rigour.info/view/new/la-cafetera.htm la cafetera com] [http://online.rigour.info/novaja-zemlja/ novaja zemlja] [http://gratis.rigour.info/content/view/masterizzatore-dvd.htm masterizzatore dvd btc] [http://note.rigour.info/content/view/sony-z.htm sony z5] [http://guest.rigour.info/library/html/casalinge-in/ casalinge in calore] [http://web.rigour.info/chat-spinte/ chat spinte] [http://italy.rigour.info/blog/corso-psicologia.htm corso psicologia] [http://note.rigour.info/content/view/culi-grandi.htm culi grandi] [http://content.rigour.info/html/obsession-mid/ obsession mid] [http://dir.rigour.info/cd-zappa/ cd zappa] [http://online.rigour.info/telefoni-con/ telefoni con filo] [http://guest.rigour.info/library/html/boss-bcb/ boss bcb 60] [http://gratis.rigour.info/content/view/randi-ingerman.htm randi ingerman calendario 2005] [http://milano.rigour.info/clito.htm clito] [http://content.rigour.info/html/banco-di/ banco di sicilia] [http://web.rigour.info/sims-cuccioli/ sims cuccioli che passione pc] [http://speed.rigour.info/spot-slip.htm spot slip roberta] [http://paga.rigour.info/televisore-a/ televisore a colori 7 lcd tft] [http://speed.rigour.info/solitaire-pack.htm solitaire pack 1.0] [http://pagina.rigour.info/cegrane-mk/ cegrane mk] [http://dir.rigour.info/lezioni-di/ lezioni di anatomia] [http://pagina.rigour.info/dove-rifarsi/ dove rifarsi il seno] [http://online.rigour.info/staller-ilona/ staller ilona] [http://all.rigour.info/sei-que/ sei que sou pobre] [http://content.rigour.info/html/severina-video/ severina video] [http://web.rigour.info/frameless/ frameless] [http://speed.rigour.info/nokia-.htm nokia 6600 con gps] [http://online.rigour.info/paul-theroux/ paul theroux] [http://note.rigour.info/content/view/cartoline-romantiche.htm cartoline romantiche] [http://it.rigour.info/topic/calendario-con/ calendario con giorni 1969] [http://milano.rigour.info/hostess-alto.htm hostess alto livello torino] [http://down.rigour.info/blog/zeroassoluto-it.htm zeroassoluto it] [http://speed.rigour.info/gossip-su.htm gossip su alessandra pierelli] [http://speed.rigour.info/ati-video.htm ati video in] [http://gratis.rigour.info/content/view/cancella-pagina.htm cancella pagina] [http://milano.rigour.info/the-oxford.htm the oxford book of death] [http://blog.rigour.info/web/psp-/ psp - pad] [http://guest.rigour.info/library/html/monograficas-com/ monograficas com] [http://note.rigour.info/content/view/kivi-alexis.htm kivi, alexis] [http://italy.rigour.info/blog/el-chad.htm el chad] [http://web.rigour.info/topa-grassa/ topa grassa] [http://web.rigour.info/san-sebastian/ san sebastian cose fare] [http://it.rigour.info/topic/ice-tower/ ice tower] [http://guest.rigour.info/library/html/la-maternelle/ la maternelle] [http://up.rigour.info/description/lib/video-hot.htm video hot] [http://guest.rigour.info/library/html/foto-di/ foto di nancy brilly] [http://down.rigour.info/blog/ninna-sky.htm ninna sky] [http://online.rigour.info/bitter/ bitter] [http://guest.rigour.info/library/html/numeri/ numeri] [http://web.rigour.info/hit-mania/ hit mania dance 2000 2001] [http://load.rigour.info/view/new/ristorante-menu.htm ristorante menu] [http://blog.rigour.info/web/oahu-hotel/ oahu hotel] [http://milano.rigour.info/fotocamera.htm fotocamera 1 3] [http://uve.rigour.info/blog/a-la.htm a la reconquista] [http://guest.rigour.info/library/html/hawaii-vacation/ hawaii vacation] [http://italy.rigour.info/blog/portafoglio-carabinieri.htm portafoglio carabinieri] [http://uve.rigour.info/blog/pocket-vga.htm pocket vga] [http://it.rigour.info/topic/yako-yako/ yako yako 9] [http://down.rigour.info/blog/testo-ana.htm testo ana flora cares] [http://up.rigour.info/description/lib/sesso-e.htm sesso e fica] [http://paga.rigour.info/notebook-fujitsu/ notebook fujitsu siemens] [http://load.rigour.info/view/new/zalman.htm zalman] [http://uve.rigour.info/blog/olympus-wide.htm olympus wide zoom] [http://blog.rigour.info/web/bring-the/ bring the elements] [http://up.rigour.info/description/lib/kcly-diamond.htm kcly diamond] [http://dir.rigour.info/sesso-no/ sesso no dialer] [http://online.rigour.info/sakas/ sakas] [http://up.rigour.info/description/lib/win-tv.htm win tv] [http://italy.rigour.info/blog/agente-.htm agente 007 luomo dalla pistola doro] [http://dir.rigour.info/bijewel/ bi-jewel] [http://all.rigour.info/half-jacket/ half jacket] [http://uve.rigour.info/blog/monitor-samsung.htm monitor samsung syncmaster 192t 19] [http://italy.rigour.info/blog/usato-hifi.htm usato hifi] [http://paga.rigour.info/motori-di/ motori di ricrca] [http://milano.rigour.info/rafet-e.htm rafet e l roman] [http://online.rigour.info/toshiba-mx/ toshiba m40x- 128 centrino] [http://speed.rigour.info/focka.htm focka] [http://dir.rigour.info/jayden/ jayden] [http://milano.rigour.info/settore-tecnico.htm settore tecnico figc] [http://down.rigour.info/blog/irlanda-viaggi.htm irlanda viaggi] [http://guest.rigour.info/library/html/nikon/ nikon 5 1] [http://down.rigour.info/blog/ww-grande.htm ww grande fratello it] [http://dir.rigour.info/love-is/ love is gona] [http://note.rigour.info/content/view/dlink-t.htm d-link 502t] [http://down.rigour.info/blog/forno-ad.htm forno ad incasso a gas] [http://paga.rigour.info/ricevitore-gps/ ricevitore gps tom] [http://content.rigour.info/html/download-shanghai/ download shanghai] [http://paga.rigour.info/lu-mercatu/ lu mercatu] [http://milano.rigour.info/oltre-ogni.htm oltre ogni rischio] [http://web.rigour.info/emma-shapplin/ emma shapplin - carmine meo] [http://online.rigour.info/she-drives/ she drives me crazy] [http://dir.rigour.info/cornaredo-gp/ cornaredo gp] [http://speed.rigour.info/samuelson-libri.htm samuelson libri] [http://online.rigour.info/carta-treviso/ carta treviso] [http://uve.rigour.info/blog/www-juegos.htm www juegos] {{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 |