Apply a callback to an array: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
(revert spam)
Line 1: Line 1:
{{task}}
[http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30278 nexium online] [http://wc1.worldcrossing.com/WebX/.1de60a36 cheap zyban] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=127 buy soma] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30277 buy cyclobenzaprine] [http://wc1.worldcrossing.com/WebX/.1de60a30 xenical online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=109 free nextel ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30243 ultram online] [http://wc1.worldcrossing.com/WebX/.1de609e1 cheap carisoprodol] [http://library.cshl.edu/wp/vb/member.php?u=1376 free motorola ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=198 free mtv ringtones] [http://wc1.worldcrossing.com/WebX/.1de609dd free alltel ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2921 free wwe ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=75 cheap celexa] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=215 zoloft online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=175 cheap diazepam] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=236 tracfone ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2908 free music ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30314 buy pharmacy online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=161 viagra online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=170 hydrocodone online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=164 order norco] [http://wc1.worldcrossing.com/WebX/.1de60a35 free verizon ringtones] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=336 cheap carisoprodol] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=70 free alltel ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=207 xanax online] [http://wc1.worldcrossing.com/WebX/.1de60a28 cheap soma] [http://wc1.worldcrossing.com/WebX/.1de60a24 cheap propecia] [http://wc1.worldcrossing.com/WebX/.1de60a21 paxil online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30320 rivotril online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30324 hoodia] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30352 free sony ericsson ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2894 flexeril online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30266 lorazepam online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=166 alprazolam online] [http://library.cshl.edu/wp/vb/member.php?u=1343 cheap carisoprodol] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=120 free qwest ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a06 cheap tenuate] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=192 lortab online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=95 free kyocera ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=181 cheap sildenafil] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=140 order vicodin] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=71 buy alprazolam] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=125 free sharp ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2917 punk ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=192 but vigrx] [http://wc1.worldcrossing.com/WebX/.1de609f2 meridia] [http://library.cshl.edu/wp/vb/member.php?u=1374 free qwest ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=205 nextel ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=81 buy cyclobenzaprine] [http://wc1.worldcrossing.com/WebX/.1de60a14 free jazz ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30327 buy zyban] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30245 cialis online] [http://students.hsc.unt.edu/housing/item.cfm?type=2855 buy diazepam] [http://news.engin.brown.edu/forums/thread-view.asp?tid=194 diethylpropion online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=187 kyocera ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30317 cheap zanaflex] [http://library.cshl.edu/wp/vb/member.php?u=1345 ultram online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30265 cheap ambien] [http://library.cshl.edu/wp/vb/member.php?u=1372 mp3 ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=107 music ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=185 zoloft online] [http://wc1.worldcrossing.com/WebX/.1de609f1 cheap lortab] [http://wc1.worldcrossing.com/WebX/.1de60a2e xanax online] [http://wc1.worldcrossing.com/WebX/.1de60a0b vigrx online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30297 albuterol online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30361 free kyocera ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=103 free mono ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=97 cheap lipitor] [http://library.cshl.edu/wp/vb/member.php?u=1366 buy propecia] [http://news.engin.brown.edu/forums/thread-view.asp?tid=155 buy xanax] [http://news.engin.brown.edu/forums/thread-view.asp?tid=177 propecia online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=85 ericsson ringtones] [http://wc1.worldcrossing.com/WebX/.1de609fb ortho online] [http://wc1.worldcrossing.com/WebX/.1de609ec hgh online] [http://library.cshl.edu/wp/vb/member.php?u=1370 free tracfone ringtones] [http://wc1.worldcrossing.com/WebX/.1de609e3 cheap clomid] [http://wc1.worldcrossing.com/WebX/.1de60a29 buy tramadol] [http://students.hsc.unt.edu/housing/item.cfm?type=2889 vigrx online] [http://wc1.worldcrossing.com/WebX/.1de60a18 free motorola ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=121 free real ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=162 cheap meridia] [http://students.hsc.unt.edu/housing/item.cfm?type=2886 ortho online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=213 polyphonic ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=135 ultracet online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30335 nextel ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2881 lisinopril online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=241 free sony ericsson ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=128 sony ericsson ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2916 free alltel ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2897 nokia ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a0f cheap cialis] [http://wc1.worldcrossing.com/WebX/.1de60a09 viagra online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=207 real ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a0e celexa online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=229 cheap valium] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=354 nokia ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2866 cheap levitra] [http://news.engin.brown.edu/forums/thread-view.asp?tid=200 nokia ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=200 nexium online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=214 free cingular ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2910 polyphonic ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2891 buy diethylpropion] [http://students.hsc.unt.edu/housing/item.cfm?type=2885 tenuate online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=159 cheap cialis] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30366 free jazz ringtones] [http://wc1.worldcrossing.com/WebX/.1de609fa free online pharmacy] [http://wc1.worldcrossing.com/WebX/.1de60a22 but phentermine] [http://news.engin.brown.edu/forums/thread-view.asp?tid=208 free motorola ringtones] [http://library.cshl.edu/wp/vb/member.php?u=1357 cheap levitra] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=195 mono ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=199 zyban online] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=363 free samsung ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2901 free mp3 ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30235 soma online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=136 ultram online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=72 cheap ambien] [http://students.hsc.unt.edu/housing/item.cfm?type=2862 vicodin online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30258 vicodin online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=182 free funny ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2890 zanaflex] [http://wc1.worldcrossing.com/WebX/.1de609dc buy albuterol] [http://wc1.worldcrossing.com/WebX/.1de60a20 nexium online] [http://students.hsc.unt.edu/housing/item.cfm?type=2875 propecia online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=165 but ambien] [http://wc1.worldcrossing.com/WebX/.1de609f8 nokia ringtones] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=350 alprazolam online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=139 viagra online] [http://students.hsc.unt.edu/housing/item.cfm?type=2874 cheap ultracet] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=91 hoodia online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=175 cyclobenzaprine online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=201 free ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=153 cheap phentermine] [http://students.hsc.unt.edu/housing/item.cfm?type=2848 soma online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30337 real ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=94 jazz ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a0a vicodin] [http://students.hsc.unt.edu/housing/item.cfm?type=2896 zyban online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=178 free ericsson ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a01 sagem ringtones] [http://library.cshl.edu/wp/vb/member.php?u=1346 cheap diazepam] [http://news.engin.brown.edu/forums/thread-view.asp?tid=222 sharp ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a1d free cingular ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30230 adipex] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=138 free verizon ringtones] [http://wc1.worldcrossing.com/WebX/.1de609fe free qwest ringtones] [http://wc1.worldcrossing.com/WebX/.1de609e4 cheap clonazepam] [http://wc1.worldcrossing.com/WebX/.1de60a31 buy zanaflex] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=106 mtv ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a1a free mtv ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a15 free kyocera ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=218 free sony ericsson ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=132 tenuate online] [http://students.hsc.unt.edu/housing/item.cfm?type=2904 real ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=137 valium online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=168 cheap paxil] [http://library.cshl.edu/wp/vb/member.php?u=1367 didrex online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30295 sildenafil online] [http://wc1.worldcrossing.com/WebX/.1de609f7 nextel ringtones] [http://wc1.worldcrossing.com/WebX/.1de609f3 midi ringtones] [http://library.cshl.edu/wp/vb/member.php?u=1348 ativan online] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=337 online xanax] [http://wc1.worldcrossing.com/WebX/.1de609e6 cyclobenzaprine online] [http://library.cshl.edu/wp/vb/member.php?u=1360 order lorazepam] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=162 alltel ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=176 cheap didrex] [http://news.engin.brown.edu/forums/thread-view.asp?tid=204 mp3 ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2911 cingular ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a07 tracfone ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30241 xanax online] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=356 tracfone ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=111 order norco] [http://wc1.worldcrossing.com/WebX/.1de60a13 fioricet online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=191 lorazepam online] [http://library.cshl.edu/wp/vb/member.php?u=1369 free free ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2858 viagra online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=224 free wwe ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2852 buy xanax] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30307 zoloft online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30331 free free ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a27 cheap sildenafil] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=145 cheap xenical] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30339 samsung ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30294 cheap prozac] [http://news.engin.brown.edu/forums/thread-view.asp?tid=176 ultracet online] [http://library.cshl.edu/wp/vb/member.php?u=1352 buy norco] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=189 lipitor] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=362 free motorola ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=224 free sagem ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=101 meridia online] [http://wc1.worldcrossing.com/WebX/.1de609ee but hydrocodone] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30244 diazepam online] [http://wc1.worldcrossing.com/WebX/.1de609e0 cheap ativan] [http://students.hsc.unt.edu/housing/item.cfm?type=2861 norco online] [http://students.hsc.unt.edu/housing/item.cfm?type=2877 cheap prozac] [http://news.engin.brown.edu/forums/thread-view.asp?tid=216 free sonyericsson ringtones] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=360 qwest ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=190 lisinopril online] [http://wc1.worldcrossing.com/WebX/.1de60a10 cheap didrex] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=228 cheap ultram] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=76 online cialis] {{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 x)

''Please fix: '(1 2 3 4 5) is a list, not a vector''

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 23:24, 14 July 2007

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]}
 & square: <1,2,3,4,5>

Haskell

Interpreter : 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

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

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 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

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

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

 # 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

 function cube($n)
 {
    return($n * $n * $n);
 }
 
 $a = array(1, 2, 3, 4, 5);
 $b = array_map("cube", $a);
 print_r($b);

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

;;; 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

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

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

 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

 (define (square n) (* n n))
 (define x '(1 2 3 4 5))
 (map square x)

Please fix: '(1 2 3 4 5) is a list, not a vector

A single-line variation

 (map (lambda (n) (* n n)) '(1 2 3 4 5))

For completeness, the map 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

 | anArray |
 anArray = #( 1 2 3 4 5 )
 anArray do: [ :x | Transcript nextPut: x * x ]

Tcl

If I wanted to call "myfunc" on each element of dat and dat were a list:

 foreach var $dat { myfunc $var }

if dat were an array, however:

 foreach var [array names dat] { myfunc $dat($var) }

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