Apply a callback to an array: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
Line 1: Line 1:
[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}}
{{task}}
== [[Ada]] ==
== [[Ada]] ==
[[Category:Ada]]
[[Category:Ada]]
'''Tested With:'''
'''Tested With:'''
* [[Gnat GPL 2005]]
* [[Gnat GPL 2005]]
** Amd-64bit-3500+-WinXP
** 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+5,print_square);
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 = ++var(i)); // init array
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+ *a*)
(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 +loop ;
-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+ map \ adds one to each element of data
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 03:57, 22 August 2007

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

Task
Apply a callback to an array
You are encouraged to solve this task according to the task description, using any language you may know.

Ada

Tested With:

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

Using std::vector

#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]}