Apply a callback to an array: Difference between revisions

m
no edit summary
(revert spam)
mNo edit summary
Line 1:
[http://dylantian.ifrance.com/styles/dvd-nba.htm dvd nba] [http://habeard.angelfire.com/topic/ragazza-black.htm ragazza black eyed peas] [http://nymphbmbzl222.ifrance.com/parishilton-video.htm parishilton video] [http://lehartfi.at.tut.by/lib/oralb-oxyjet.htm oralb oxyjet 8500] [http://habeard.angelfire.com/topic/idea-regalo.htm idea regalo donna] [http://jrosestar.ifrance.com/html/asus/ asus 12] [http://nymphbmbzl222.ifrance.com/hotel-economici.htm hotel economici montecatini terme] [http://casloan.angelfire.com/small/sony-dsc/ sony dsc t] [http://rebuckma.angelfire.com/description/mini-computer.htm mini computer] [http://ariadnafeni.ifrance.com/resources/lei-apre/ lei apre e lui lo infila] [http://wowinoth.at.tut.by/web/kon.htm kon] [http://isabellaval.ifrance.com/pda-/ pda h2210] [http://lidresze.angelfire.com/blog/que-es.htm que es la lepra] [http://brandalinden.ifrance.com/topic/supporto-auto.htm supporto auto con ventosa] [http://habeard.angelfire.com/topic/scanjet-.htm scanjet 5590 hp scanner] [http://ariadnafeni.ifrance.com/resources/villamarina/ villamarina] [http://breveret.at.tut.by/view/new/hp-viamichelin.htm hp viamichelin] [http://mcunderh.at.tut.by/resources/articles/apple.htm apple 12 640] [http://konstantinkar.ifrance.com/description/servizio-di/ servizio di leva] [http://casloan.angelfire.com/small/taglio-laser/ taglio laser lombardia] [http://dylantian.ifrance.com/styles/video-bang.htm video bang bang] [http://sagaddy.angelfire.com/styles/prenotazione-hotel/ prenotazione hotel genova] [http://yvharlen.at.tut.by/lib/lanuit.htm lanuit] [http://dweejah.ifrance.com/new/tarzan-e/ tarzan e il safari perduto] [http://agodichik.angelfire.com/styles/babynamesworld-com.htm babynamesworld com] [http://dweejah.ifrance.com/new/obiettivo-nikon/ obiettivo nikon 28mm] [http://ferandol.at.tut.by/images/small/camera-porta.htm camera porta arredamento climatizzatore] [http://kataevka.ifrance.com/articles/viking-child/ viking child prophecy] [http://alena344.ifrance.com/text/apple-imac/ apple imac g5] [http://hewvey.ifrance.com/library/testo-canzone/ testo canzone linea 77 subsonica] [http://snerma.angelfire.com/text/denon-dvd/ denon dvd 1720] [http://breveret.at.tut.by/view/new/neodivx.htm neodivx] [http://brandalinden.ifrance.com/topic/win-mx.htm win mx italiano] [http://macertot.ifrance.com/view/vendita-computer.htm vendita computer] [http://alena344.ifrance.com/text/megamix-hit/ megamix hit mania dance estate 2004] [http://konstantinkar.ifrance.com/description/tutto-fica/ tutto fica] [http://stdamin.at.tut.by/html/jambol.htm jambol] [http://nymphbmbzl222.ifrance.com/casino-perla.htm casino perla] [http://jrosestar.ifrance.com/html/ormai-non/ ormai non trombi piu] [http://ariadnafeni.ifrance.com/resources/schede-memoria/ schede memoria sd] [http://casloan.angelfire.com/small/verbatim-rs/ verbatim rs mmc 512] [http://kairikekui.ifrance.com/resources/cucine-misura/ cucine misura] [http://feralpaw-omm.ifrance.com/html/tavolo-anni/ tavolo anni 70] [http://macertot.ifrance.com/view/lisola-maledetta.htm lisola maledetta] [http://hewvey.ifrance.com/library/biko/ biko] [http://wifry.angelfire.com/styles/bryger-finale.htm bryger finale] [http://crhighto.at.tut.by/img/styles/registrazione-marchio.htm registrazione marchio] [http://brandalinden.ifrance.com/topic/video-rubati.htm video rubati] [http://kataevka.ifrance.com/articles/s-girl/ s girl] [http://kataevka.ifrance.com/articles/www-figa/ www figa calda com] [http://wifry.angelfire.com/styles/testi-canzoni.htm testi canzoni eugenio bennato] [http://kataevka.ifrance.com/articles/alain-resnais/ alain resnais] [http://dylantian.ifrance.com/styles/padre-alfonso.htm padre alfonso maria parente carcere] [http://jrosestar.ifrance.com/html/hp-fax/ hp fax scanner 2610] [http://snerma.angelfire.com/text/immagini-di/ immagini di jessica biel] [http://rebuckma.angelfire.com/description/testi-hit.htm testi hit mania dance estate 2004] [http://konstantinkar.ifrance.com/description/morbo-paget/ morbo paget] [http://ariadnafeni.ifrance.com/resources/pantani/ pantani] [http://webancks.at.tut.by/images/small/legami-di.htm legami di sangue] [http://casloan.angelfire.com/small/hercules-dj/ hercules dj console mac] [http://dweejah.ifrance.com/new/xp-licenza/ xp licenza studenti] [http://beyonddreamingx.angelfire.com/content/el-hijo.htm el hijo tuta] [http://lidresze.angelfire.com/blog/fisarmonica-musica.htm fisarmonica musica] [http://brandalinden.ifrance.com/topic/jet-attends.htm jet attends] [http://kataevka.ifrance.com/articles/francesca-deller/ francesca deller] [http://kairikekui.ifrance.com/resources/el-televisori/ el televisori] [http://jrosestar.ifrance.com/html/faber/ faber] [http://macertot.ifrance.com/view/banca-popolare.htm banca popolare di monza] [http://habeard.angelfire.com/topic/lavastoviglie-incasso.htm lavastoviglie incasso 45cm] [http://macertot.ifrance.com/view/eosmark-ii.htm eosmark ii] [http://isabellaval.ifrance.com/il-sito/ il sito ufficiale di 1503 ad] [http://brandalinden.ifrance.com/topic/telecamere-nascoste.htm telecamere nascoste nelle palestre] [http://wipitts.at.tut.by/text/directory/audrey-hepburn.htm audrey hepburn colazione] [http://casloan.angelfire.com/small/grandi-domani/ grandi domani video] [http://dylantian.ifrance.com/styles/karim-e.htm karim e georg] [http://rebuckma.angelfire.com/description/jeans-elasticizzato.htm jeans elasticizzato a vita bassa] [http://lidresze.angelfire.com/blog/due-mogli.htm due mogli sono troppe] [http://kedewber.at.tut.by/topic/abiti-in.htm abiti in pelle e renna] [http://beyonddreamingx.angelfire.com/content/alchool-software.htm alchool software] [http://kataevka.ifrance.com/articles/paula-raymond/ paula raymond] [http://dweejah.ifrance.com/new/nn-ci/ nn ci lasceremo mai] [http://rebuckma.angelfire.com/description/britney-spears.htm britney spears live from las vegas] [http://feralpaw-omm.ifrance.com/html/recupero-dato/ recupero dato floppy] [http://spkleins.angelfire.com/prunotto/ prunotto] [http://yoschaad.at.tut.by/lib/papst.htm papst 8412] [http://alena344.ifrance.com/text/c-/ c 1030 plus] [http://macertot.ifrance.com/view/uniurb.htm uniurb] [http://zaweaver.at.tut.by/text/directory/caviar-wdjb.htm caviar wd3200jb] [http://habeard.angelfire.com/topic/cornuto.htm cornuto] [http://gaburlei.angelfire.com/resources/albergo-hotel.htm albergo hotel roma] [http://jrosestar.ifrance.com/html/samantha-fox/ samantha fox] [http://konstantinkar.ifrance.com/description/dina-paucar/ dina paucar que lindos son tus ojos] [http://kataevka.ifrance.com/articles/loredana-lecciso/ loredana lecciso sex] [http://agodichik.angelfire.com/styles/lacie.htm lacie 80] [http://dweejah.ifrance.com/new/la-nascita/ la nascita delle leggende secondo microsoft] [http://hewvey.ifrance.com/library/paguinas-de/ paguinas de sexo] [http://alena344.ifrance.com/text/joca-jeux/ joca jeux] [http://gaburlei.angelfire.com/resources/albergo-caracas.htm albergo caracas] [http://jrosestar.ifrance.com/html/di-abilita/ di abilita] [http://wipitts.at.tut.by/text/directory/the-top.htm the top of the west] [http://concessionari-alfa.greylopht.cn concessionari alfa romeo] [http://testo-scritto.digirb-backward.cn testo scritto di eamon] [http://keokepa.com.cn/obiettivo-nikon.htm obiettivo nikon 28] [http://nike-uomo.fast-girl.net.cn nike uomo running] [http://inps-di.sound-of-sun.cn inps di prato] [http://web-sorting.cn/il-bacio.htm il bacio hayez] [http://sapphire-xpro.jowugow.cn sapphire x850pro 256] [http://nonkomformist.cn/leslie-caron.htm leslie caron] [http://ponchon-raoul.jowugow.cn ponchon raoul] [http://web-sorting.cn/logitech-harmony.htm logitech harmony 895] [http://waltermoney.cn/eau-de.htm eau de cartier concentree] [http://pixie-bite.org.cn/irdeto-codes.htm irdeto codes] [http://dangeon.sound-of-sun.cn dangeon] [http://bionic-athlete.mack-si.cn bionic athlete] [http://web-sorting.cn/versioni-greco.htm versioni greco] [http://web-sorting.cn/torneo-pasquale.htm torneo pasquale] [http://nonkomformist.cn/jean-claude.htm jean claude van damme] [http://quintiliano-institutio.sound-of-sun.cn quintiliano institutio oratoria] [http://golf-miniputt.sound-of-sun.cn golf miniputt] [http://on-again.fast-girl.net.cn on again] [http://web-sorting.cn/sistema-di.htm sistema di raffreddamento] [http://georgiil.net.cn/grace-kelli.htm grace kelli] [http://dustybooks.cn/sauna-sex.htm sauna sex] [http://knuckles-lives.cn/traduttore-italiano.htm traduttore italiano francese] [http://web-sorting.cn/ford-auto.htm ford auto] [http://georgiil.net.cn/ennepi.htm ennepi] [http://nonkomformist.cn/i-cubetti.htm i cubetti colorati] [http://s-pietroburgo.digirb-backward.cn s pietroburgo] [http://mg-tf.sound-of-sun.cn mg tf 2002] [http://www-ebuy.taliabriscoe.cn www ebuy it] [http://aeroflow.taliabriscoe.cn aeroflow 2] [http://pixie-bite.org.cn/crudele-mario.htm crudele mario venuti] [http://dustybooks.cn/viaggio-nellinferno.htm viaggio nellinferno] [http://a-canon.taliabriscoe.cn a400 canon] [http://ando-rebuleando.mack-si.cn ando rebuleando] [http://fierydarknez.cn/sonic-x.htm sonic x] [http://nonkomformist.cn/serena-williams.htm serena williams nude] [http://waltermoney.cn/trinit.htm trinit] [http://garmin-ff.greylopht.cn garmin ff 120] [http://web-sorting.cn/autospazzatrice.htm autospazzatrice] [http://nadzor-ns.cn/gena-lee.htm gena lee nolan] [http://nonkomformist.cn/transex-inculate.htm transex inculate] [http://intelligent-question.sound-of-sun.cn intelligent question] [http://web-sorting.cn/toshiba-televisore.htm toshiba televisore lcd 16 9 23 stasia] [http://fierydarknez.cn/pj-olsson.htm pj olsson ready for a fall] [http://riviste-agricole.greylopht.cn riviste agricole] [http://knuckles-lives.cn/bmw-.htm bmw 320 touring futura] [http://keokepa.com.cn/diesel-ds.htm diesel ds 0023] [http://nadzor-ns.cn/berchet-bubble.htm berchet bubble] [http://waltermoney.cn/rimorso-che.htm rimorso che uccide] [http://keokepa.com.cn/tesina-scuola.htm tesina scuola media] [http://cabriolet-audi.sound-of-sun.cn cabriolet audi] [http://web-sorting.cn/copertina-festival.htm copertina festival di sanremo] [http://georgiil.net.cn/stromboli-.htm stromboli terra di dio] [http://nadzor-ns.cn/sex-pix.htm sex pix] [http://nadzor-ns.cn/arcam-solo.htm arcam solo] [http://waltermoney.cn/io-vivro.htm io vivro mina] [http://knuckles-lives.cn/mario-rigoni.htm mario rigoni stern] [http://nadzor-ns.cn/franco-franchi.htm franco franchi ciccio ingrassia] [http://nonkomformist.cn/trust.htm trust 1610] [http://i-m.kiushapo.cn i m slave] [http://brick-shooter.digirb-backward.cn brick shooter free] [http://keokepa.com.cn/gina-t.htm gina t] [http://diario.digirb-backward.cn diario 2006] [http://web-sorting.cn/darwen.htm darwen] [http://camicia-nera.digirb-backward.cn camicia nera (anita garibaldi)] [http://loan-laure.panzerfausts.com.cn loan laure] [http://california-health.greylopht.cn california health insurance quota] [http://rudolf-steiner.taliabriscoe.cn rudolf steiner] [http://nonkomformist.cn/chiave-rossa.htm chiave rossa] [http://fierydarknez.cn/video-amatoriali.htm video amatoriali francavilla fontana] [http://nikon.jowugow.cn nikon 17 35] [http://dustybooks.cn/samsung-lcd.htm samsung lcd monitors 19] [http://narcan-im.panzerfausts.com.cn narcan im iv 1 f 1 ml 04 mg] [http://waltermoney.cn/ram-.htm ram 512 ddr 400 samsung] [http://spartito-dello.jowugow.cn spartito dello strano percorso] [http://volkswagen-polo.panzerfausts.com.cn volkswagen polo iii] [http://dustybooks.cn/palast-orchester.htm palast orchester] [http://a-man.sound-of-sun.cn a man called hero (dvd)] [http://pixie-bite.org.cn/mr-president.htm mr president] [http://acer.digirb-backward.cn acer 9104] [http://arsenal-parigi.happi-thoughts.org.cn arsenal (parigi)] [http://pixie-bite.org.cn/visual-studio.htm visual studio libri] [http://fierydarknez.cn/hill-s.htm hill s s d] [http://mp-convert.fast-girl.net.cn mp3 convert] [http://waltermoney.cn/george-lago.htm george lago (usa)] [http://knuckles-lives.cn/montainbike.htm montainbike] [http://nonkomformist.cn/sinfonia-per.htm sinfonia per un massacro] [http://knuckles-lives.cn/we-are.htm we are spidrman 2] [http://pixie-bite.org.cn/tesoreria.htm tesoreria] [http://olimpo-cardenas.sound-of-sun.cn olimpo cardenas] [http://knuckles-lives.cn/rubi-su.htm rubi su novela] [http://pixie-bite.org.cn/edizioni-tecniche.htm edizioni tecniche] [http://sepultura-chaos.jowugow.cn sepultura chaos] [http://oceania-regione.taliabriscoe.cn oceania regione] [http://nuove-immagini.kiushapo.cn nuove immagini e artwork da without warning] [http://cese-vacanze.fast-girl.net.cn cese vacanze] [http://pixie-bite.org.cn/benny-benassi.htm benny benassi get better] [http://xd-adapter.happi-thoughts.org.cn xd adapter] [http://kenwood-bm.fast-girl.net.cn kenwood bm] {{task}}
{{task}}
== [[Ada]] ==
[[Category:Ada]]
'''Tested With:'''
* [[Gnat GPL 2005]]
** Amd-64bit-3500+ -WinXP
 
with Ada.Text_Io;
Line 93:
{
int i;
for(i = 0; i < len; i++ )
{
callback(i, array[i]);
Line 116:
'''Platform:''' [[.NET]]
 
'''Language Version:''' 2.0+
 
'''Compiler:''' [[Visual C sharp|Visual C#]] 2005
Line 155:
}
 
==[[C plus plus|C++ ]]==
[[Category:C plus plus]]
'''Compiler:''' [[GNU Compiler Collection]] 4.1.1
Line 171:
int ary[]={1,2,3,4,5};
//stl for_each
std::for_each(ary,ary+ 5,print_square);
return 0;
}
Line 230:
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
 
Line 267:
 
(defvar *a* (vector 1 2 3))
(map-into *a* #'1+ *a*)
 
==[[E]]==
Line 301:
 
: 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]]==
Line 332:
 
{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
Anonymous user