Apply a callback to an array: Difference between revisions
Added code for FreeBASIC |
Langurmonkey (talk | contribs) |
||
(154 intermediate revisions by 75 users not shown) | |||
Line 1: | Line 1: | ||
{{task|Basic language learning}} |
|||
[[Category:Iteration]] |
[[Category:Iteration]] |
||
{{task|Basic language learning}} |
|||
;Task: |
;Task: |
||
Take a combined set of elements and apply a function to each element. |
Take a combined set of elements and apply a function to each element. |
||
<br><br> |
<br><br> |
||
=={{header|11l}}== |
|||
{{trans|Kotlin}} |
|||
<syntaxhighlight lang="11l">V array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
|||
V arrsq = array.map(i -> i * i) |
|||
print(arrsq)</syntaxhighlight> |
|||
{{out}} |
|||
<pre>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</pre> |
|||
=={{header|6502 Assembly}}== |
|||
For this example, assume both the source array and the destination have a size of 86 elements (memory offsets base+0x00 to base+0x55.) |
|||
This was implemented in easy6502. |
|||
<syntaxhighlight lang="6502asm">define SRC_LO $00 |
|||
define SRC_HI $01 |
|||
define DEST_LO $02 |
|||
define DEST_HI $03 |
|||
define temp $04 ;temp storage used by foo |
|||
;some prep work since easy6502 doesn't allow you to define arbitrary bytes before runtime. |
|||
SET_TABLE: |
|||
TXA |
|||
STA $1000,X |
|||
INX |
|||
BNE SET_TABLE |
|||
;stores the identity table at memory address $1000-$10FF |
|||
CLEAR_TABLE: |
|||
LDA #0 |
|||
STA $1200,X |
|||
INX |
|||
BNE CLEAR_TABLE |
|||
;fills the range $1200-$12FF with zeroes. |
|||
LDA #$10 |
|||
STA SRC_HI |
|||
LDA #$00 |
|||
STA SRC_LO |
|||
;store memory address $1000 in zero page |
|||
LDA #$12 |
|||
STA DEST_HI |
|||
LDA #$00 |
|||
STA DEST_LO |
|||
;store memory address $1200 in zero page |
|||
loop: |
|||
LDA (SRC_LO),y ;load accumulator from memory address $1000+y |
|||
JSR foo ;multiplies accumulator by 3. |
|||
STA (DEST_LO),y ;store accumulator in memory address $1200+y |
|||
INY |
|||
CPY #$56 ;alternatively you can store a size variable and check that here instead. |
|||
BCC loop |
|||
BRK |
|||
foo: |
|||
STA temp |
|||
ASL ;double accumulator |
|||
CLC |
|||
ADC temp ;2a + a = 3a |
|||
RTS</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1200: 00 03 06 09 0c 0f 12 15 18 1b 1e 21 24 27 2a 2d |
|||
1210: 30 33 36 39 3c 3f 42 45 48 4b 4e 51 54 57 5a 5d |
|||
1220: 60 63 66 69 6c 6f 72 75 78 7b 7e 81 84 87 8a 8d |
|||
1230: 90 93 96 99 9c 9f a2 a5 a8 ab ae b1 b4 b7 ba bd |
|||
1240: c0 c3 c6 c9 cc cf d2 d5 d8 db de e1 e4 e7 ea ed |
|||
1250: f0 f3 f6 f9 fc ff |
|||
</pre> |
|||
=={{header|68000 Assembly}}== |
|||
{{trans|11l}} |
|||
The following assumes all code/data is stored/executed in RAM and is therefore mutable. |
|||
<syntaxhighlight lang="68000devpac">LEA MyArray,A0 |
|||
MOVE.W #(MyArray_End-MyArray)-1,D7 ;Len(MyArray)-1 |
|||
MOVEQ #0,D0 ;sanitize D0-D2 to ensure nothing from any previous work will affect our math. |
|||
MOVEQ #0,D1 |
|||
MOVEQ #0,D2 |
|||
loop: |
|||
MOVE.B (A0),D0 |
|||
MOVE.B D0,D1 |
|||
MOVE.B D0,D2 |
|||
MULU D1,D2 |
|||
MOVE.B D2,(A0)+ |
|||
dbra d7,loop |
|||
jmp * ;halt the CPU |
|||
MyArray: |
|||
DC.B 1,2,3,4,5,6,7,8,9,10 |
|||
MyArray_End:</syntaxhighlight> |
|||
=={{header|8th}}== |
=={{header|8th}}== |
||
The builtin word "a:map" does this: |
The builtin word "a:map" does this: |
||
< |
<syntaxhighlight lang="forth"> |
||
[ 1 , 2, 3 ] |
[ 1 , 2, 3 ] |
||
' n:sqr |
' n:sqr |
||
a:map |
a:map |
||
</syntaxhighlight> |
|||
</lang> |
|||
That results in the array [1,4,9] |
That results in the array [1,4,9] |
||
Line 19: | Line 120: | ||
ACL2 does not have first-class functions; this is close, however: |
ACL2 does not have first-class functions; this is close, however: |
||
< |
<syntaxhighlight lang="lisp">(defun apply-to-each (xs) |
||
(if (endp xs) |
(if (endp xs) |
||
nil |
nil |
||
Line 27: | Line 128: | ||
(defun fn-to-apply (x) |
(defun fn-to-apply (x) |
||
(* x x)) |
(* x x)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang="actionscript">package |
||
{ |
{ |
||
public class ArrayCallback |
public class ArrayCallback |
||
Line 48: | Line 149: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
{{works with|GNAT|GPL 2005}} |
{{works with|GNAT|GPL 2005}} |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_Io; |
||
with Ada.Integer_text_IO; |
with Ada.Integer_text_IO; |
||
Line 88: | Line 189: | ||
begin |
begin |
||
Map(Sample, Display'access); |
Map(Sample, Display'access); |
||
end Call_Back_Example;</ |
end Call_Back_Example;</syntaxhighlight> |
||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">void |
||
map(list l, void (*fp) |
map(list l, void (*fp)(object)) |
||
{ |
{ |
||
l.ucall(fp, 0); |
|||
i = 0; |
|||
while (i < l_length(l)) { |
|||
fp(l[i]); |
|||
i += 1; |
|||
} |
|||
} |
} |
||
void |
void |
||
out(object o) |
out(object o) |
||
{ |
{ |
||
o_(o, "\n"); |
|||
o_byte(10); |
|||
} |
} |
||
integer |
integer |
||
main(void) |
main(void) |
||
{ |
{ |
||
list |
list(0, 1, 2, 3).map(out); |
||
l_append(l, 0); |
|||
l_append(l, 1); |
|||
l_append(l, 2); |
|||
l_append(l, 3); |
|||
map(l, out); |
|||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 132: | Line 217: | ||
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}} |
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}} |
||
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}} |
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}} |
||
< |
<syntaxhighlight lang="algol68"> PROC call back proc = (INT location, INT value)VOID: |
||
( |
( |
||
printf(($"array["g"] = "gl$, location, value)) |
printf(($"array["g"] = "gl$, location, value)) |
||
Line 148: | Line 233: | ||
[4]INT array := ( 1, 4, 9, 16 ); |
[4]INT array := ( 1, 4, 9, 16 ); |
||
map(array, call back proc) |
map(array, call back proc) |
||
)</ |
)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 156: | Line 242: | ||
array[ +4] = +16 |
array[ +4] = +16 |
||
</pre> |
</pre> |
||
=={{header|ALGOL W}}== |
|||
<syntaxhighlight lang="algolw">begin |
|||
procedure printSquare ( integer value x ) ; writeon( i_w := 1, s_w := 0, " ", x * x ); |
|||
% applys f to each element of a from lb to ub (inclusive) % |
|||
procedure applyI ( procedure f; integer array a ( * ); integer value lb, ub ) ; |
|||
for i := lb until ub do f( a( i ) ); |
|||
% test applyI % |
|||
begin |
|||
integer array a ( 1 :: 3 ); |
|||
a( 1 ) := 1; a( 2 ) := 2; a( 3 ) := 3; |
|||
applyI( printSquare, a, 1, 3 ) |
|||
end |
|||
end.</syntaxhighlight> |
|||
=={{header|APL}}== |
|||
By default functions in APL work on arrays as it is an array oriented language. Some examples: |
|||
<syntaxhighlight lang="apl"> - 1 2 3 |
|||
¯1 ¯2 ¯3 |
|||
2 * 1 2 3 4 |
|||
2 4 8 16 |
|||
2 × ⍳4 |
|||
2 4 6 8 |
|||
3 * 3 3 ⍴ ⍳9 |
|||
3 9 27 |
|||
81 243 729 |
|||
2187 6561 19683 |
|||
</syntaxhighlight> |
|||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">on callback for arg |
||
-- Returns a string like "arc has 3 letters" |
|||
arg & " has " & (count arg) & " letters" |
|||
end callback |
end callback |
||
set alist to {"arc", "be", "circle"} |
set alist to {"arc", "be", "circle"} |
||
repeat with aref in alist |
repeat with aref in alist |
||
-- Passes a reference to some item in alist |
|||
-- to callback, then speaks the return value. |
|||
say (callback for aref) |
|||
end repeat</ |
end repeat</syntaxhighlight> |
||
If the callback would <code>set arg's contents to "something"</code>, then <code>alist</code> would be mutated. |
If the callback would <code>set arg's contents to "something"</code>, then <code>alist</code> would be mutated. |
||
For a more general implementation of '''map( |
For a more general implementation of '''map(function, list)''', '''foldl(function, startValue, list)''', and '''filter(predicate, list)''', we could write: |
||
< |
<syntaxhighlight lang="applescript">on run |
||
set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} |
set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} |
||
{map(square, xs), ¬ |
{map(square, xs), ¬ |
||
filter( |
filter(even, xs), ¬ |
||
foldl(add, 0, xs)} |
|||
--> {{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}, {2, 4, 6, 8, 10}, 55} |
|||
end run |
end run |
||
-- square :: Num -> Num -> Num |
|||
on square(x) |
on square(x) |
||
x * x |
x * x |
||
end square |
end square |
||
-- add :: Num -> Num -> Num |
|||
on sum(a, b) |
|||
on add(a, b) |
|||
a + b |
a + b |
||
end |
end add |
||
-- even :: Int -> Bool |
|||
on isEven(n) |
|||
on even(x) |
|||
n mod 2 = 0 |
|||
0 = x mod 2 |
|||
end isEven |
|||
end even |
|||
-- GENERIC HIGHER ORDER FUNCTIONS |
|||
-- map :: (a -> b) -> [a] -> [b] |
|||
on map(f, xs) |
|||
set mf to mReturn(f) |
|||
set lng to length of xs |
|||
set lst to {} |
|||
repeat with i from 1 to lng |
|||
set end of lst to mf's lambda(item i of xs, i, xs) |
|||
end repeat |
|||
return lst |
|||
end map |
|||
-- reduce :: (a -> b -> a) -> a -> [b] -> a |
|||
on reduce(f, startValue, xs) |
|||
set mf to mReturn(f) |
|||
set v to startValue |
|||
set lng to length of xs |
|||
repeat with i from 1 to lng |
|||
set v to mf's lambda(v, item i of xs, i, xs) |
|||
end repeat |
|||
return v |
|||
end reduce |
|||
-- filter :: (a -> Bool) -> [a] -> [a] |
-- filter :: (a -> Bool) -> [a] -> [a] |
||
on filter(f, xs) |
on filter(f, xs) |
||
tell mReturn(f) |
|||
set lst to {} |
|||
set |
set lng to length of xs |
||
repeat with i from 1 to lng |
|||
set lng to length of xs |
|||
set v to item i of xs |
|||
if |λ|(v, i, xs) then set end of lst to v |
|||
end repeat |
|||
return lst |
|||
end tell |
|||
end repeat |
|||
return lst |
|||
end filter |
end filter |
||
-- foldl :: (a -> b -> a) -> a -> [b] -> a |
|||
-- 2nd class handler function lifted into 1st class script wrapper |
|||
on foldl(f, startValue, xs) |
|||
-- mReturn :: Handler -> Script |
|||
tell mReturn(f) |
|||
set v to startValue |
|||
set lng to length of xs |
|||
repeat with i from 1 to lng |
|||
set v to |λ|(v, item i of xs, i, xs) |
|||
end repeat |
|||
return v |
|||
end tell |
|||
end foldl |
|||
-- Lift 2nd class handler function into 1st class script wrapper |
|||
-- mReturn :: First-class m => (a -> b) -> m (a -> b) |
|||
on mReturn(f) |
on mReturn(f) |
||
if class of f is script then |
if class of f is script then |
||
f |
|||
else |
|||
property lambda : f |
|||
script |
|||
property |λ| : f |
|||
end script |
|||
end if |
|||
end mReturn |
end mReturn |
||
</lang> |
|||
-- map :: (a -> b) -> [a] -> [b] |
|||
on map(f, xs) |
|||
tell mReturn(f) |
|||
set lng to length of xs |
|||
set lst to {} |
|||
repeat with i from 1 to lng |
|||
set end of lst to |λ|(item i of xs, i, xs) |
|||
end repeat |
|||
return lst |
|||
end tell |
|||
end map</syntaxhighlight> |
|||
{{Out}} |
{{Out}} |
||
<pre>{{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}, {2, 4, 6, 8, 10}, 55}</pre> |
<pre>{{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}, {2, 4, 6, 8, 10}, 55}</pre> |
||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol">arr: [1 2 3 4 5] |
|||
print map arr => [2*&]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>2 4 6 8 10</pre> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">map("callback", "3,4,5") |
||
callback(array){ |
callback(array){ |
||
Line 261: | Line 390: | ||
map(callback, array){ |
map(callback, array){ |
||
%callback%(array) |
%callback%(array) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk">$ awk 'func psqr(x){print x,x*x}BEGIN{split("1 2 3 4 5",a);for(i in a)psqr(a[i])}' |
||
4 16 |
4 16 |
||
5 25 |
5 25 |
||
1 1 |
1 1 |
||
2 4 |
2 4 |
||
3 9</ |
3 9</syntaxhighlight> |
||
=={{header|Babel}}== |
=={{header|Babel}}== |
||
Line 275: | Line 404: | ||
Let us define a squaring operator: |
Let us define a squaring operator: |
||
< |
<syntaxhighlight lang="babel">sq { dup * } <</syntaxhighlight> |
||
Now, we apply the sq operator over a list and display the result using the lsnum utility: |
Now, we apply the sq operator over a list and display the result using the lsnum utility: |
||
< |
<syntaxhighlight lang="babel">( 0 1 1 2 3 5 8 13 21 34 ) { sq ! } over ! lsnum !</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 286: | Line 415: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<syntaxhighlight lang="bbcbasic"> DIM a(4) |
||
a() = 1, 2, 3, 4, 5 |
a() = 1, 2, 3, 4, 5 |
||
PROCmap(a(), FNsqrt()) |
PROCmap(a(), FNsqrt()) |
||
Line 302: | Line 431: | ||
NEXT |
NEXT |
||
ENDPROC |
ENDPROC |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 311: | Line 440: | ||
2.23606798 |
2.23606798 |
||
</pre> |
</pre> |
||
=={{header|Binary Lambda Calculus}}== |
|||
In the lambda calculus, we can map over a list as in https://github.com/tromp/AIT/blob/master/lists/map.lam, which gives the following BLC program to negate every bit of input: |
|||
<pre>010001101000000101100000000001011000000101111111010110010111111101111110111010</pre> |
|||
=={{header|BQN}}== |
|||
<syntaxhighlight lang="bqn">Square ← ט |
|||
array ← 2‿3‿5‿7‿11‿13 |
|||
Square¨ array</syntaxhighlight> |
|||
The use of the ¨ modifier is the general approach, but actually not necessary with arithmetic functions. |
|||
{{out}} |
|||
<pre>⟨ 4 9 25 49 121 169 ⟩</pre> |
|||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat">( ( callbackFunction1 |
||
= location value |
= location value |
||
. !arg:(?location,?value) |
. !arg:(?location,?value) |
||
Line 323: | Line 466: | ||
& !!value^2:?!value |
& !!value^2:?!value |
||
) |
) |
||
& ( |
& ( mapar |
||
= arr len callback i |
= arr len callback i |
||
. !arg:(?arr,?len,?callback) |
. !arg:(?arr,?len,?callback) |
||
Line 338: | Line 481: | ||
& 3:?(2$array) |
& 3:?(2$array) |
||
& 4:?(3$array) |
& 4:?(3$array) |
||
& |
& mapar$(array,4,callbackFunction1) |
||
& |
& mapar$(array,4,callbackFunction2) |
||
& |
& mapar$(array,4,callbackFunction1) |
||
);</ |
);</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>array[0] = 1 |
<pre>array[0] = 1 |
||
Line 354: | Line 497: | ||
=={{header|Brat}}== |
=={{header|Brat}}== |
||
< |
<syntaxhighlight lang="brat">#Print out each element in array |
||
[:a :b :c :d :e].each { element | |
[:a :b :c :d :e].each { element | |
||
p element |
p element |
||
}</ |
}</syntaxhighlight> |
||
Alternatively: |
Alternatively: |
||
< |
<syntaxhighlight lang="brat">[:a :b :c :d :e].each ->p</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
'''callback.h''' |
'''callback.h''' |
||
< |
<syntaxhighlight lang="c">#ifndef CALLBACK_H |
||
#define CALLBACK_H |
#define CALLBACK_H |
||
Line 381: | Line 524: | ||
void map(int* array, int len, void(*callback)(int,int)); |
void map(int* array, int len, void(*callback)(int,int)); |
||
#endif</ |
#endif</syntaxhighlight> |
||
'''callback.c''' |
'''callback.c''' |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include "callback.h" |
#include "callback.h" |
||
Line 410: | Line 553: | ||
map(array, 4, callbackFunction); |
map(array, 4, callbackFunction); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 420: | Line 563: | ||
</pre> |
</pre> |
||
=={{header|C sharp}}== |
=={{header|C sharp|C#}}== |
||
{{works with|C sharp|C#|3.0+}} |
|||
This version uses the C# 3 lambda notation. |
|||
<syntaxhighlight lang="csharp">int[] intArray = { 1, 2, 3, 4, 5 }; |
|||
// Simplest method: LINQ, functional |
|||
int[] squares1 = intArray.Select(x => x * x).ToArray(); |
|||
// Slightly fancier: LINQ, query expression |
|||
int[] squares2 = (from x in intArray |
|||
select x * x).ToArray(); |
|||
// Or, if you only want to call a function on each element, just use foreach |
|||
foreach (var i in intArray) |
|||
Console.WriteLine(i * i);</syntaxhighlight> |
|||
{{works with|C sharp|C#|2.0+}} |
{{works with|C sharp|C#|2.0+}} |
||
{{works with|Visual C sharp|Visual C#|2005}} |
{{works with|Visual C sharp|Visual C#|2005}} |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
static class Program |
static class Program |
||
Line 457: | Line 615: | ||
Console.WriteLine(value * value); |
Console.WriteLine(value * value); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{works with|C sharp|C#|3.0+}} |
|||
This version uses the C# 3 lambda notation. |
|||
<lang csharp>int[] intArray = { 1, 2, 3, 4, 5 }; |
|||
Array.ForEach(intArray, i => Console.WriteLine(i * i));</lang> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
Line 469: | Line 621: | ||
{{works with|g++|4.1.1}} |
{{works with|g++|4.1.1}} |
||
===C-Style Array=== |
===C-Style Array=== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> //cout for printing |
||
#include <algorithm> //for_each defined here |
#include <algorithm> //for_each defined here |
||
Line 484: | Line 636: | ||
return 0; |
return 0; |
||
} |
} |
||
//prints 1 4 9 16 25</ |
//prints 1 4 9 16 25</syntaxhighlight> |
||
===std::vector=== |
===std::vector=== |
||
{{libheader|STL}} |
{{libheader|STL}} |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> // cout for printing |
||
#include <algorithm> // for_each defined here |
#include <algorithm> // for_each defined here |
||
#include <vector> // stl vector class |
#include <vector> // stl vector class |
||
Line 509: | Line 661: | ||
return 0; |
return 0; |
||
} |
} |
||
//prints 1 4 9 16 25</ |
//prints 1 4 9 16 25</syntaxhighlight> |
||
More tricky with binary function |
More tricky with binary function |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> // cout for printing |
||
#include <algorithm> // for_each defined here |
#include <algorithm> // for_each defined here |
||
#include <vector> // stl vector class |
#include <vector> // stl vector class |
||
Line 535: | Line 687: | ||
return 0; |
return 0; |
||
} |
} |
||
//prints 1x 2x 3x 4x 5x</ |
//prints 1x 2x 3x 4x 5x</syntaxhighlight> |
||
===Boost.Lambda=== |
===Boost.Lambda=== |
||
{{libheader|Boost}} |
{{libheader|Boost}} |
||
< |
<syntaxhighlight lang="cpp">using namespace std; |
||
using namespace boost::lambda; |
using namespace boost::lambda; |
||
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</syntaxhighlight> |
||
===C++11=== |
===C++11=== |
||
< |
<syntaxhighlight lang="cpp">#include <vector> |
||
#include <iostream> |
#include <iostream> |
||
#include <algorithm> |
#include <algorithm> |
||
Line 561: | Line 713: | ||
std::cout << std::endl; |
std::cout << std::endl; |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Clean}}== |
=={{header|Clean}}== |
||
Line 567: | Line 719: | ||
Define a function and an initial (unboxed) array. |
Define a function and an initial (unboxed) array. |
||
< |
<syntaxhighlight lang="clean">square x = x * x |
||
values :: {#Int} |
values :: {#Int} |
||
values = {x \\ x <- [1 .. 10]}</ |
values = {x \\ x <- [1 .. 10]}</syntaxhighlight> |
||
One can easily define a map for arrays, which is overloaded and works for all kinds of arrays (lazy, strict, unboxed). |
One can easily define a map for arrays, which is overloaded and works for all kinds of arrays (lazy, strict, unboxed). |
||
< |
<syntaxhighlight lang="clean">mapArray f array = {f x \\ x <-: array}</syntaxhighlight> |
||
Apply the function to the initial array (using a comprehension) and print result. |
Apply the function to the initial array (using a comprehension) and print result. |
||
< |
<syntaxhighlight lang="clean">Start :: {#Int} |
||
Start = mapArray square values</ |
Start = mapArray square values</syntaxhighlight> |
||
=={{header|Clio}}== |
|||
'''Math operations''' |
|||
<syntaxhighlight lang="clio">[1 2 3 4] * 2 + 1 -> print</syntaxhighlight> |
|||
'''Quick functions''' |
|||
<syntaxhighlight lang="text">[1 2 3 4] -> * n: n * 2 + 1 -> print</syntaxhighlight> |
|||
'''Anonymous function''' |
|||
<syntaxhighlight lang="clio">[1 2 3 4] |
|||
-> * fn n: |
|||
n * 2 + 1 |
|||
-> print</syntaxhighlight> |
|||
'''Named function''' |
|||
<syntaxhighlight lang="clio">fn double-plus-one n: |
|||
n * 2 + 1 |
|||
[1 2 3 4] -> * double-plus-one -> print</syntaxhighlight> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="lisp">;; apply a named function, inc |
||
(map inc [1 2 3 4])</ |
(map inc [1 2 3 4])</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lisp">;; apply a function |
||
(map (fn [x] (* x x)) [1 2 3 4])</ |
(map (fn [x] (* x x)) [1 2 3 4])</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lisp">;; shortcut syntax for a function |
||
(map #(* % %) [1 2 3 4])</ |
(map #(* % %) [1 2 3 4])</syntaxhighlight> |
||
=={{header| |
=={{header|CLU}}== |
||
<syntaxhighlight lang="clu">% This procedure will call a given procedure with each element |
|||
% of the given array. Thanks to CLU's type parameterization, |
|||
% it will work for any type of element. |
|||
apply_to_all = proc [T: type] (a: array[T], f: proctype(int,T)) |
|||
for i: int in array[T]$indexes(a) do |
|||
f(i, a[i]) |
|||
end |
|||
end apply_to_all |
|||
% Callbacks for both string and int |
|||
Basic implementation of a map function: |
|||
show_int = proc (i, val: int) |
|||
<lang cobol> IDENTIFICATION DIVISION. |
|||
po: stream := stream$primary_output() |
|||
PROGRAM-ID. Map. |
|||
stream$putl(po, "array[" || int$unparse(i) || "] = " || int$unparse(val)); |
|||
end show_int |
|||
show_string = proc (i: int, val: string) |
|||
DATA DIVISION. |
|||
po: stream := stream$primary_output() |
|||
WORKING-STORAGE SECTION. |
|||
stream$putl(po, "array[" || int$unparse(i) || "] = " || val); |
|||
01 Table-Size CONSTANT 30. |
|||
end show_string |
|||
% Here's how to use them |
|||
LOCAL-STORAGE SECTION. |
|||
start_up = proc () |
|||
01 I USAGE UNSIGNED-INT. |
|||
po: stream := stream$primary_output() |
|||
ints: array[int] := array[int]$[2, 3, 5, 7, 11] |
|||
strings: array[string] := array[string]$ |
|||
["enemy", "lasagna", "robust", "below", "wax"] |
|||
stream$putl(po, "Ints: ") |
|||
apply_to_all[int](ints, show_int) |
|||
stream$putl(po, "\nStrings: ") |
|||
apply_to_all[string](strings, show_string) |
|||
end start_up</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Ints: |
|||
array[1] = 2 |
|||
array[2] = 3 |
|||
array[3] = 5 |
|||
array[4] = 7 |
|||
array[5] = 11 |
|||
Strings: |
|||
LINKAGE SECTION. |
|||
array[1] = enemy |
|||
01 Table-Param. |
|||
array[2] = lasagna |
|||
03 Table-Values USAGE COMP-2 OCCURS Table-Size TIMES. |
|||
array[3] = robust |
|||
array[4] = below |
|||
array[5] = wax</pre> |
|||
=={{header|COBOL}}== |
|||
{{Works with|COBOL 2002}} |
|||
Basic implementation of a map function: |
|||
<syntaxhighlight lang="cobolfree"> >>SOURCE FORMAT IS FREE |
|||
IDENTIFICATION DIVISION. |
|||
PROGRAM-ID. map. |
|||
DATA DIVISION. |
|||
01 Func-Id PIC X(30). |
|||
LOCAL-STORAGE SECTION. |
|||
01 i USAGE IS INDEX. |
|||
01 table-size CONSTANT AS 30. |
|||
LINKAGE SECTION. |
|||
01 table-param. |
|||
03 table-values USAGE IS FLOAT-LONG, OCCURS table-size TIMES. |
|||
01 func-ptr USAGE IS PROGRAM-POINTER. |
|||
PROCEDURE DIVISION USING BY REFERENCE table-param, BY VALUE func-ptr. |
|||
PROCEDURE DIVISION USING Table-Param Func-Id. |
|||
PERFORM VARYING i FROM 1 BY 1 UNTIL i IS GREATER THAN table-size |
|||
CALL func-ptr USING BY REFERENCE table-values(i) |
|||
END-PERFORM |
|||
GOBACK. |
|||
END PROGRAM map.</syntaxhighlight> |
|||
GOBACK |
|||
.</lang> |
|||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript"> |
||
map = (arr, f) -> (f(e) for e in arr) |
map = (arr, f) -> (f(e) for e in arr) |
||
arr = [1, 2, 3, 4, 5] |
arr = [1, 2, 3, 4, 5] |
||
f = (x) -> x * x |
f = (x) -> x * x |
||
console.log map arr, f # prints [1, 4, 9, 16, 25] |
console.log map arr, f # prints [1, 4, 9, 16, 25] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
Line 632: | Line 846: | ||
Imperative: print 1, 2, 3, 4 and 5: |
Imperative: print 1, 2, 3, 4 and 5: |
||
< |
<syntaxhighlight lang="lisp">(map nil #'print #(1 2 3 4 5))</syntaxhighlight> |
||
Functional: collect squares into new vector that is returned: |
Functional: collect squares into new vector that is returned: |
||
< |
<syntaxhighlight lang="lisp">(defun square (x) (* x x)) |
||
(map 'vector #'square #(1 2 3 4 5))</ |
(map 'vector #'square #(1 2 3 4 5))</syntaxhighlight> |
||
Destructive, like the Javascript example; add 1 to every slot of vector *a*: |
Destructive, like the Javascript example; add 1 to every slot of vector *a*: |
||
< |
<syntaxhighlight lang="lisp">(defvar *a* (vector 1 2 3)) |
||
(map-into *a* #'1+ *a*)</ |
(map-into *a* #'1+ *a*)</syntaxhighlight> |
||
=={{header|Component Pascal}}== |
=={{header|Component Pascal}}== |
||
BlackBox Component Builder |
BlackBox Component Builder |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE Callback; |
MODULE Callback; |
||
IMPORT StdLog; |
IMPORT StdLog; |
||
Line 701: | Line 915: | ||
END Do; |
END Do; |
||
END Callback. |
END Callback. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Execute: ^Q Callback.Do<br/> |
Execute: ^Q Callback.Do<br/> |
||
{{Out}} |
{{Out}} |
||
Line 727: | Line 941: | ||
6561 |
6561 |
||
</pre> |
</pre> |
||
=={{header|Crystal}}== |
|||
Calling with a block |
|||
<syntaxhighlight lang="ruby">values = [1, 2, 3] |
|||
new_values = values.map do |number| |
|||
number * 2 |
|||
end |
|||
puts new_values #=> [2, 4, 6]</syntaxhighlight> |
|||
Calling with a function/method |
|||
<syntaxhighlight lang="ruby">values = [1, 2, 3] |
|||
def double(number) |
|||
number * 2 |
|||
end |
|||
# the `->double(Int32)` syntax creates a proc from a function/method. argument types must be specified. |
|||
# the `&proc` syntax passes a proc as a block. |
|||
# combining the two passes a function/method as a block |
|||
new_values = values.map &->double(Int32) |
|||
puts new_values #=> [2, 4, 6]</syntaxhighlight> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm; |
||
void main() { |
void main() { |
||
Line 735: | Line 973: | ||
auto m = items.map!(x => x + 5)(); |
auto m = items.map!(x => x + 5)(); |
||
writeln(m); |
writeln(m); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[6, 7, 8, 9, 10]</pre> |
<pre>[6, 7, 8, 9, 10]</pre> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
// Declare the callback function |
// Declare the callback function |
||
procedure callback(const AInt:Integer); |
procedure callback(const AInt:Integer); |
||
Line 758: | Line 996: | ||
callback(myArray[i]); |
callback(myArray[i]); |
||
end. |
end. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Dyalect}}== |
|||
<syntaxhighlight lang="dyalect">func Array.Select(pred) { |
|||
let ys = [] |
|||
for x in this when pred(x) { |
|||
ys.Add(x) |
|||
} |
|||
return ys |
|||
} |
|||
var arr = [1, 2, 3, 4, 5] |
|||
var squares = arr.Select(x => x * x) |
|||
print(squares)</syntaxhighlight> |
|||
=={{header|Déjà Vu}}== |
=={{header|Déjà Vu}}== |
||
There is a <code>map</code> builtin that does just this. |
There is a <code>map</code> builtin that does just this. |
||
< |
<syntaxhighlight lang="dejavu">!. map @++ [ 1 4 8 ] |
||
#implemented roughly like this: |
#implemented roughly like this: |
||
Line 768: | Line 1,022: | ||
# for i in lst: |
# for i in lst: |
||
# f i |
# f i |
||
# [</ |
# [</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[ 2 5 9 ]</pre> |
<pre>[ 2 5 9 ]</pre> |
||
Line 774: | Line 1,028: | ||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">def array := [1,2,3,4,5] |
||
def square(value) { |
def square(value) { |
||
return value * value |
return value * value |
||
}</ |
}</syntaxhighlight> |
||
Example of builtin iteration: |
Example of builtin iteration: |
||
< |
<syntaxhighlight lang="e">def callback(index, value) { |
||
println(`Item $index is $value.`) |
println(`Item $index is $value.`) |
||
} |
} |
||
array.iterate(callback)</ |
array.iterate(callback)</syntaxhighlight> |
||
There is no built-in map function '''yet'''. |
There is no built-in map function '''yet'''. |
||
Line 790: | Line 1,044: | ||
returning a plain list (which is usually an array in implementation). |
returning a plain list (which is usually an array in implementation). |
||
< |
<syntaxhighlight lang="e">def map(func, collection) { |
||
def output := [].diverge() |
def output := [].diverge() |
||
for item in collection { |
for item in collection { |
||
Line 797: | Line 1,051: | ||
return output.snapshot() |
return output.snapshot() |
||
} |
} |
||
println(map(square, array))</ |
println(map(square, array))</syntaxhighlight> |
||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
(vector-map sqrt #(0 4 16 49)) |
(vector-map sqrt #(0 4 16 49)) |
||
→ #( 0 2 4 7) |
→ #( 0 2 4 7) |
||
Line 812: | Line 1,066: | ||
v[2] = 4 |
v[2] = 4 |
||
→ #( 4 9 16) |
→ #( 4 9 16) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Efene}}== |
=={{header|Efene}}== |
||
< |
<syntaxhighlight lang="efene">square = fn (N) { |
||
N * N |
N * N |
||
} |
} |
||
Line 848: | Line 1,102: | ||
io.format("squares3 : ~p~n", [squares3(Numbers)]) |
io.format("squares3 : ~p~n", [squares3(Numbers)]) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|EGL}}== |
=={{header|EGL}}== |
||
< |
<syntaxhighlight lang="egl">delegate callback( i int ) returns( int ) end |
||
program ApplyCallbackToArray |
program ApplyCallbackToArray |
||
Line 870: | Line 1,124: | ||
return( i * i ); |
return( i * i ); |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 6.x : |
|||
<syntaxhighlight lang="elena">import system'routines; |
|||
PrintSecondPower(n){ console.writeLine(n * n) } |
|||
<lang elena>#define system. |
|||
#define system'routines. |
|||
public program() |
|||
#symbol PrintSecondPower = |
|||
{ |
|||
(:n) [ console writeLine:(n * n) ]. |
|||
new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.forEach(PrintSecondPower) |
|||
}</syntaxhighlight> |
|||
=={{header|Elixir}}== |
|||
#symbol program = |
|||
<syntaxhighlight lang="elixir"> |
|||
[ |
|||
Enum.map([1, 2, 3], fn(n) -> n * 2 end) |
|||
Enum.map [1, 2, 3], &(&1 * 2) |
|||
]. |
|||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
|||
<pre> |
|||
[2, 4, 6] |
|||
</pre> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
A list would be more commonly used in Erlang rather than an array. |
A list would be more commonly used in Erlang rather than an array. |
||
<syntaxhighlight lang="erlang"> |
|||
<lang Erlang> |
|||
1> L = [1,2,3]. |
1> L = [1,2,3]. |
||
[1,2,3] |
[1,2,3] |
||
</syntaxhighlight> |
|||
</lang> |
|||
You can use lists:foreach/2 if you just want to apply the callback to each element of the list. |
You can use lists:foreach/2 if you just want to apply the callback to each element of the list. |
||
<lang> |
<syntaxhighlight lang="text"> |
||
2> lists:foreach(fun(X) -> io:format("~w ",[X]) end, L). |
2> lists:foreach(fun(X) -> io:format("~w ",[X]) end, L). |
||
1 2 3 ok |
1 2 3 ok |
||
</syntaxhighlight> |
|||
</lang> |
|||
Or you can use lists:map/2 if you want to create a new list with the result of the callback on each element. |
Or you can use lists:map/2 if you want to create a new list with the result of the callback on each element. |
||
<syntaxhighlight lang="erlang"> |
|||
<lang Erlang> |
|||
3> lists:map(fun(X) -> X + 1 end, L). |
3> lists:map(fun(X) -> X + 1 end, L). |
||
[2,3,4] |
[2,3,4] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Or you can use lists:foldl/3 if you want to accumulate the result of the callback on each element into one value. |
Or you can use lists:foldl/3 if you want to accumulate the result of the callback on each element into one value. |
||
<syntaxhighlight lang="erlang"> |
|||
<lang Erlang> |
|||
4> lists:foldl(fun(X, Sum) -> X + Sum end, 0, L). |
4> lists:foldl(fun(X, Sum) -> X + Sum end, 0, L). |
||
6 |
6 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
<lang> |
<syntaxhighlight lang="text"> |
||
PROGRAM CALLBACK |
PROGRAM CALLBACK |
||
Line 942: | Line 1,203: | ||
PRINT |
PRINT |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
This example shows how to pass a function to a procedure. |
This example shows how to pass a function to a procedure. |
||
{{Out}} |
{{Out}} |
||
Line 950: | Line 1,211: | ||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">function apply_to_all(sequence s, integer f) |
||
-- apply a function to all elements of a sequence |
-- apply a function to all elements of a sequence |
||
sequence result |
sequence result |
||
Line 967: | Line 1,228: | ||
-- add1() is visible here, so we can ask for its routine id |
-- add1() is visible here, so we can ask for its routine id |
||
? apply_to_all({1, 2, 3}, routine_id("add1")) |
? apply_to_all({1, 2, 3}, routine_id("add1")) |
||
-- displays {2,3,4}</ |
-- displays {2,3,4}</syntaxhighlight> |
||
This is also "Example 2" in the Euphoria documentation for <code>routine_id()</code>. |
This is also "Example 2" in the Euphoria documentation for <code>routine_id()</code>. |
||
Note that this example will not work for multi-dimensional sequences. |
Note that this example will not work for multi-dimensional sequences. |
||
=={{header|F_Sharp|F#}}== |
|||
Apply a named function to each member of the array. The result is a new array of the same size as the input. |
|||
<syntaxhighlight lang="fsharp">let evenp x = x % 2 = 0 |
|||
let result = Array.map evenp [| 1; 2; 3; 4; 5; 6 |]</syntaxhighlight> |
|||
The same can be done using anonymous functions, this time squaring the members of the input array. |
|||
<syntaxhighlight lang="fsharp">let result = Array.map (fun x -> x * x) [|1; 2; 3; 4; 5|]</syntaxhighlight> |
|||
Use ''iter'' if the applied function does not return a value. |
|||
<syntaxhighlight lang="fsharp">Array.iter (fun x -> printfn "%d" x) [|1; 2; 3; 4; 5|]</syntaxhighlight> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Print each element squared: |
Print each element squared: |
||
< |
<syntaxhighlight lang="factor">{ 1 2 3 4 } [ sq . ] each</syntaxhighlight> |
||
Collect return values: |
Collect return values: |
||
< |
<syntaxhighlight lang="factor">{ 1 2 3 4 } [ sq ] map</syntaxhighlight> |
||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
Line 982: | Line 1,252: | ||
In Fantom, functions can be passed to a collection iterator, such as 'each'. 'map' is used similarly, and the results are collected into a list. |
In Fantom, functions can be passed to a collection iterator, such as 'each'. 'map' is used similarly, and the results are collected into a list. |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 992: | Line 1,262: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 1,006: | Line 1,276: | ||
=={{header|FBSL}}== |
=={{header|FBSL}}== |
||
'''User-defined mapping function:''' |
'''User-defined mapping function:''' |
||
< |
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE |
||
FOREACH DIM e IN MyMap(Add42, {1, 2, 3}) |
FOREACH DIM e IN MyMap(Add42, {1, 2, 3}) |
||
Line 1,022: | Line 1,292: | ||
END FUNCTION |
END FUNCTION |
||
FUNCTION Add42(n): RETURN n + 42: END FUNCTION</ |
FUNCTION Add42(n): RETURN n + 42: END FUNCTION</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>43 44 45 |
<pre>43 44 45 |
||
Line 1,028: | Line 1,298: | ||
'''Standard MAP() function:''' |
'''Standard MAP() function:''' |
||
< |
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE |
||
DIM languages[] = {{"English", {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}}, _ |
DIM languages[] = {{"English", {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}}, _ |
||
Line 1,044: | Line 1,314: | ||
MAP(NameANumber, lang[0], 1 TO 10, lang[1]) |
MAP(NameANumber, lang[0], 1 TO 10, lang[1]) |
||
PRINT LPAD("", 40, "-") |
PRINT LPAD("", 40, "-") |
||
END SUB</ |
END SUB</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>The number 1 is called "one" in English |
<pre>The number 1 is called "one" in English |
||
Line 1,069: | Line 1,339: | ||
---------------------------------------- |
---------------------------------------- |
||
Press any key to continue...</pre> |
Press any key to continue...</pre> |
||
=={{header|Fe}}== |
|||
<syntaxhighlight lang="clojure"> |
|||
(= map (fn (f lst) |
|||
(let res (cons nil nil)) |
|||
(let tail res) |
|||
(while lst |
|||
(setcdr tail (cons (f (car lst)) nil)) |
|||
(= lst (cdr lst)) |
|||
(= tail (cdr tail))) |
|||
(cdr res))) |
|||
(print (map (fn (x) (* x x)) '(1 2 3 4 5 6 7 8 9 10))) |
|||
</syntaxhighlight> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
Line 1,074: | Line 1,358: | ||
This is a word that will call a given function on each cell in an array. |
This is a word that will call a given function on each cell in an array. |
||
< |
<syntaxhighlight lang="forth">: map ( addr n fn -- ) |
||
-rot cells bounds do i @ over execute i ! cell +loop ;</ |
-rot cells bounds do i @ over execute i ! cell +loop ;</syntaxhighlight> |
||
{{Out|Example usage}} |
{{Out|Example usage}} |
||
< |
<syntaxhighlight lang="forth">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</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
Line 1,085: | Line 1,369: | ||
{{Works with |Fortran|ISO 95 and later}} |
{{Works with |Fortran|ISO 95 and later}} |
||
< |
<syntaxhighlight lang="fortran">module arrCallback |
||
contains |
contains |
||
elemental function cube( x ) |
elemental function cube( x ) |
||
Line 1,093: | Line 1,377: | ||
cube = x * x * x |
cube = x * x * x |
||
end function cube |
end function cube |
||
end module arrCallback</ |
end module arrCallback</syntaxhighlight> |
||
< |
<syntaxhighlight lang="fortran">program testAC |
||
use arrCallback |
use arrCallback |
||
implicit none |
implicit none |
||
Line 1,111: | Line 1,395: | ||
write(*,*) b(i,:) |
write(*,*) b(i,:) |
||
end do |
end do |
||
end program testAC</ |
end program testAC</syntaxhighlight> |
||
{{Works with|ANSI FORTRAN| 77 (with MIL-STD-1753 structured DO) and later}} |
{{Works with|ANSI FORTRAN| 77 (with MIL-STD-1753 structured DO) and later}} |
||
< |
<syntaxhighlight lang="fortran"> program test |
||
C |
C |
||
C-- Declare array: |
C-- Declare array: |
||
Line 1,127: | Line 1,411: | ||
end do |
end do |
||
C |
C |
||
end</ |
end</syntaxhighlight> |
||
=={{header|FP}}== |
=={{header|FP}}== |
||
< |
<syntaxhighlight lang="fp">{square * . [id, id]} |
||
& square: <1,2,3,4,5></ |
& square: <1,2,3,4,5></syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Sub PrintEx(n As Integer) |
Sub PrintEx(n As Integer) |
||
Line 1,152: | Line 1,436: | ||
Print |
Print |
||
Print "Press any key to quit the program" |
Print "Press any key to quit the program" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,171: | Line 1,455: | ||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
< |
<syntaxhighlight lang="frink"> |
||
f = {|x| x^2} // Anonymous function to square input |
f = {|x| x^2} // Anonymous function to square input |
||
a = [1,2,3,5,7] |
a = [1,2,3,5,7] |
||
println[map[f, a]] |
println[map[f, a]] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|F_Sharp|F#}}== |
|||
Apply a named function to each member of the array. The result is a new array of the same size as the input. |
|||
<lang fsharp>let evenp x = x % 2 = 0 |
|||
let result = Array.map evenp [| 1; 2; 3; 4; 5; 6 |]</lang> |
|||
The same can be done using anonymous functions, this time squaring the members of the input array. |
|||
<lang fsharp>let result = Array.map (fun x -> x * x) [|1; 2; 3; 4; 5|]</lang> |
|||
Use ''iter'' if the applied function does not return a value. |
|||
<lang fsharp>Array.iter (fun x -> printfn "%d" x) [|1; 2; 3; 4; 5|]</lang> |
|||
=={{header|FunL}}== |
=={{header|FunL}}== |
||
< |
<syntaxhighlight lang="funl">[1, 2, 3].foreach( println ) |
||
[1, 2, 3].foreach( a -> println(2a) )</ |
[1, 2, 3].foreach( a -> println(2a) )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,201: | Line 1,476: | ||
6 |
6 |
||
</pre> |
</pre> |
||
=={{header|Futhark}}== |
|||
<syntaxhighlight lang="futhark"> |
|||
map f l |
|||
</syntaxhighlight> |
|||
e.g. |
|||
<syntaxhighlight lang="futhark"> |
|||
map (\x->x+1) [1,2,3] -- [2,3,4] |
|||
</syntaxhighlight> |
|||
or equivalently |
|||
<syntaxhighlight lang="futhark"> |
|||
map (+1) [1,2,3] -- [2,3,4] |
|||
</syntaxhighlight> |
|||
=={{header|FutureBasic}}== |
|||
<syntaxhighlight lang="futurebasic"> |
|||
include "NSLog.incl" |
|||
void local fn Callback( n as NSInteger ) |
|||
NSLog( @"Square root of %ld = %f", n, sqr(n) ) |
|||
end fn |
|||
void local fn DoIt |
|||
NSUInteger i, count |
|||
CFArrayRef array = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10] |
|||
count = len(array) |
|||
for i = 0 to count -1 |
|||
fn Callback( fn NumberIntegerValue( array[i] ) ) |
|||
next |
|||
end fn |
|||
fn DoIt |
|||
HandleEvents |
|||
</syntaxhighlight> |
|||
Another option is to enumerate the array. |
|||
<syntaxhighlight lang="futurebasic">include "NSLog.incl" |
|||
void local fn Callback( array as CFArrayRef, obj as CFTypeRef ) |
|||
long value = intVal(obj) |
|||
NSLog( @"Square root of %ld = %f", value, sqr(value) ) |
|||
end fn |
|||
void local fn DoIt |
|||
CFArrayRef array = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10] |
|||
ArrayEnumerateObjects( array, @fn Callback, NULL ) |
|||
end fn |
|||
fn DoIt |
|||
HandleEvents</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Square root of 1 = 1.000000 |
|||
Square root of 2 = 1.414214 |
|||
Square root of 3 = 1.732051 |
|||
Square root of 4 = 2.000000 |
|||
Square root of 5 = 2.236068 |
|||
Square root of 6 = 2.449490 |
|||
Square root of 7 = 2.645751 |
|||
Square root of 8 = 2.828427 |
|||
Square root of 9 = 3.000000 |
|||
Square root of 10 = 3.162278 |
|||
</pre> |
|||
=={{header|Fōrmulæ}}== |
|||
{{FormulaeEntry|page=https://formulae.org/?script=examples/Apply_a_callback_to_an_array}} |
|||
'''Solution''' |
|||
Most programming languages define a high-order map function. In Fōrmulæ, there is ''arraization'' (by analogy with ''summation''). In the following expression, the "big" curly braces resembles the "big" sigma of a summation: |
|||
[[File:Fōrmulæ - Apply a callback to an array 01.png]] |
|||
[[File:Fōrmulæ - Apply a callback to an array 02.png]] |
|||
The elements of the array are not required to be of the same type: |
|||
[[File:Fōrmulæ - Apply a callback to an array 03.png]] |
|||
[[File:Fōrmulæ - Apply a callback to an array 04.png]] |
|||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">a := [1 .. 4]; |
||
b := ShallowCopy(a); |
b := ShallowCopy(a); |
||
Line 1,223: | Line 1,586: | ||
b; |
b; |
||
# [ 1 .. 4 ]</ |
# [ 1 .. 4 ]</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
Line 1,230: | Line 1,593: | ||
Perhaps in contrast to Ruby, it is idiomatic in Go to use the for statement: |
Perhaps in contrast to Ruby, it is idiomatic in Go to use the for statement: |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 1,238: | Line 1,601: | ||
fmt.Println(i * i) |
fmt.Println(i * i) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Alternatively though, an array-like type can be defined and callback-style methods can be defined on it to apply a function to the elements. |
Alternatively though, an array-like type can be defined and callback-style methods can be defined on it to apply a function to the elements. |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 1,271: | Line 1,634: | ||
return i * i |
return i * i |
||
})) |
})) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,285: | Line 1,648: | ||
Print each value in a list |
Print each value in a list |
||
< |
<syntaxhighlight lang="groovy">[1,2,3,4].each { println it }</syntaxhighlight> |
||
Create a new list containing the squares of another list |
Create a new list containing the squares of another list |
||
< |
<syntaxhighlight lang="groovy">[1,2,3,4].collect { it * it }</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Line 1,294: | Line 1,657: | ||
===List=== |
===List=== |
||
{{works with|GHC}} |
{{works with|GHC}} |
||
< |
<syntaxhighlight lang="haskell">let square x = x*x |
||
let values = [1..10] |
let values = [1..10] |
||
map square values</ |
map square values</syntaxhighlight> |
||
Using list comprehension to generate a list of the squared values |
Using list comprehension to generate a list of the squared values |
||
< |
<syntaxhighlight lang="haskell">[square x | x <- values]</syntaxhighlight> |
||
More directly |
|||
<syntaxhighlight lang="haskell">[1 .. 10] >>= pure . (^ 2)</syntaxhighlight> |
|||
Or with one less layer of monadic wrapping |
|||
<syntaxhighlight lang="haskell">(^ 2) <$> [1..10]</syntaxhighlight> |
|||
Using function composition to create a function that will print the squares of a list |
Using function composition to create a function that will print the squares of a list |
||
< |
<syntaxhighlight lang="haskell">let printSquares = mapM_ (print.square) |
||
printSquares values</ |
printSquares values</syntaxhighlight> |
||
===Array=== |
===Array=== |
||
{{works with|GHC}} |
{{works with|GHC|7.10.3}} |
||
< |
<syntaxhighlight lang="haskell">import Data.Array (Array, listArray) |
||
let square x = x*x |
|||
square :: Int -> Int |
|||
let values = array (1,10) [(i,i)|i <- [1..10]] :: Array Int Int |
|||
square x = x * x |
|||
values :: Array Int Int |
|||
values = listArray (1, 10) [1 .. 10] |
|||
main :: IO () |
|||
main = print $ fmap square values</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>array (1,10) [(1,1),(2,4),(3,9),(4,16),(5,25),(6,36),(7,49),(8,64),(9,81),(10,100)]</pre> |
|||
=={{header|Guish}}== |
|||
{{works with|guish|2.5.1}} |
|||
<syntaxhighlight lang="guish"> |
|||
# applies add2 (adds 2) to each element |
|||
add2 = { |
|||
return add(@1, 2) |
|||
} |
|||
l = {1, 2, 3, 4, 5, 6, 7} |
|||
puts each(add2, flat(@l)) |
|||
</syntaxhighlight> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang="icon">procedure main() |
||
local lst |
local lst |
||
lst := [10, 20, 30, 40] |
lst := [10, 20, 30, 40] |
||
Line 1,321: | Line 1,709: | ||
procedure callback(p,arg) |
procedure callback(p,arg) |
||
return p(" -> ", arg) |
return p(" -> ", arg) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|IDL}}== |
=={{header|IDL}}== |
||
Line 1,327: | Line 1,715: | ||
Hard to come up with an example that isn't completely contrived. IDL doesn't really distinguish between a scalar and an array; thus |
Hard to come up with an example that isn't completely contrived. IDL doesn't really distinguish between a scalar and an array; thus |
||
< |
<syntaxhighlight lang="idl">b = a^3</syntaxhighlight> |
||
will yield a scalar if <tt>a</tt> is scalar or a vector if <tt>a</tt> is a vector or an n-dimensional array if <tt>a</tt> is an n-dimensional array |
will yield a scalar if <tt>a</tt> is scalar or a vector if <tt>a</tt> is a vector or an n-dimensional array if <tt>a</tt> is an n-dimensional array |
||
=={{header|Insitux}}== |
|||
<syntaxhighlight lang="insitux">; apply a named function |
|||
(map inc [1 2 3 4])</syntaxhighlight> |
|||
<syntaxhighlight lang="insitux">; apply a parameterised closure |
|||
(map (fn x (+ x 1)) [1 2 3 4])</syntaxhighlight> |
|||
<syntaxhighlight lang="insitux">; apply a non-parameterised closure |
|||
(map #(+ % 1) [1 2 3 4])</syntaxhighlight> |
|||
<syntaxhighlight lang="insitux">; apply an explicit partial closure |
|||
(map @(+ 1) [1 2 3 4])</syntaxhighlight> |
|||
<syntaxhighlight lang="insitux">; apply an implicit partial closure |
|||
(map (+ 1) [1 2 3 4])</syntaxhighlight> |
|||
=={{header|Io}}== |
=={{header|Io}}== |
||
< |
<syntaxhighlight lang="io">list(1,2,3,4,5) map(squared)</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
'''Solution''': |
'''Solution''': |
||
< |
<syntaxhighlight lang="j"> "_1</syntaxhighlight> |
||
'''Example''': |
'''Example''': |
||
< |
<syntaxhighlight lang="j"> callback =: *: |
||
array =: 1 2 3 4 5 |
array =: 1 2 3 4 5 |
||
callback"_1 array |
callback"_1 array |
||
1 4 9 16 25</ |
1 4 9 16 25</syntaxhighlight> |
||
But note that this is a trivial example since <code>*: 1 2 3 4 5</code> would get the same result. Then again, this is something of a trivial exercise in J since all of J is designed around the idea of applying functions usefully to arrays. |
But note that this is a trivial example since <code>*: 1 2 3 4 5</code> would get the same result. Then again, this is something of a trivial exercise in J since all of J is designed around the idea of applying functions usefully to arrays. |
||
=={{header|Jakt}}== |
|||
<syntaxhighlight lang="jakt"> |
|||
fn map<T, U>(anon array: [T], function: fn(anon x: T) -> U) throws -> [U] { |
|||
mut result: [U] = [] |
|||
result.ensure_capacity(array.size()) |
|||
for item in array { |
|||
result.push(value: function(item)) |
|||
} |
|||
return result |
|||
} |
|||
fn main() { |
|||
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
|||
let array_squared = map(array, function: fn(anon n: i64) => n * n) |
|||
println("{}", array_squared) |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] |
|||
</pre> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
Up to Java 7, you have to define an interface for each type of function you want to use. |
|||
The <code>IntConsumer</code> performs an action (which doesn't return anything) on an array of ints, |
|||
while the <code>IntToInt</code> is used to replace the array values. |
|||
<syntaxhighlight lang="java">public class ArrayCallback7 { |
|||
So if you want to perform an action (which doesn't return anything) on an array of int's: |
|||
interface IntConsumer { |
|||
void run(int x); |
void run(int x); |
||
} |
|||
} |
|||
interface IntToInt { |
|||
for (int z : myIntArray) { |
|||
int run(int x); |
|||
} |
|||
public void run(int x) { |
|||
System.out.println(x); |
|||
static void forEach(int[] arr, IntConsumer consumer) { |
|||
for (int i : arr) { |
|||
consumer.run(i); |
|||
} |
} |
||
} |
} |
||
}</lang> |
|||
static void update(int[] arr, IntToInt mapper) { |
|||
Or if you want to perform "map" - return an array of the results of function applications: |
|||
for (int i = 0; i < arr.length; i++) { |
|||
arr[i] = mapper.run(arr[i]); |
|||
} |
|||
} |
|||
public static void main(String[] args) { |
|||
<lang java>interface IntToInt { |
|||
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; |
|||
int run(int x); |
|||
} |
|||
forEach(numbers, new IntConsumer() { |
|||
int[] result = new int[myIntArray.length]; |
|||
public void run(int x) { |
|||
for (int i = 0; i < myIntArray.length; i++) { |
|||
System.out.println(x); |
|||
result[i] = |
|||
} |
|||
}); |
|||
update(numbers, new IntToInt() { |
|||
@Override |
|||
public int run(int x) { |
public int run(int x) { |
||
return x * x; |
return x * x; |
||
} |
} |
||
} |
}); |
||
}</lang> |
|||
forEach(numbers, new IntConsumer() { |
|||
public void run(int x) { |
|||
System.out.println(x); |
|||
} |
|||
}); |
|||
} |
|||
}</syntaxhighlight> |
|||
Using Java 8 streams: |
|||
{{works with|Java|8}} |
|||
<syntaxhighlight lang="java">import java.util.Arrays; |
|||
public class ArrayCallback { |
|||
public static void main(String[] args) { |
|||
int[] myIntArray = {1, 2, 3, 4, 5}; |
|||
int sum = Arrays.stream(myIntArray) |
|||
.map(x -> { |
|||
int cube = x * x * x; |
|||
System.out.println(cube); |
|||
return cube; |
|||
}) |
|||
.reduce(0, (left, right) -> left + right); // <-- could substitute .sum() for .reduce(...) here. |
|||
System.out.println("sum: " + sum); |
|||
} |
|||
}</syntaxhighlight> |
|||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
===ES3=== |
===ES3=== |
||
< |
<syntaxhighlight lang="javascript">function map(a, func) { |
||
var ret = []; |
var ret = []; |
||
for (var i = 0; i < a.length; i++) { |
for (var i = 0; i < a.length; i++) { |
||
Line 1,393: | Line 1,860: | ||
} |
} |
||
map([1, 2, 3, 4, 5], function(v) { return v * v; });</ |
map([1, 2, 3, 4, 5], function(v) { return v * v; });</syntaxhighlight> |
||
===ES5=== |
===ES5=== |
||
< |
<syntaxhighlight lang="javascript">[1, 2, 3, 4, 5].map(function(v) { return v * v; });</syntaxhighlight> |
||
===ES6=== |
===ES6=== |
||
< |
<syntaxhighlight lang="javascript">[1, 2, 3, 4, 5].map(v => v * v);</syntaxhighlight> |
||
The result is always: |
The result is always: |
||
Line 1,406: | Line 1,873: | ||
=={{header|Joy}}== |
=={{header|Joy}}== |
||
< |
<syntaxhighlight lang="joy">[1 2 3 4 5] [dup *] map.</syntaxhighlight> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
< |
<syntaxhighlight lang="jq"># Illustration of map/1 using the builtin filter: exp |
||
map(exp) # exponentiate each item in the input list |
map(exp) # exponentiate each item in the input list |
||
Line 1,423: | Line 1,890: | ||
# Elementwise operation |
# Elementwise operation |
||
[.[] + 1 ] # add 1 to each element of the input array |
[.[] + 1 ] # add 1 to each element of the input array |
||
</ |
</syntaxhighlight>Here is a transcript illustrating how the last of these jq expressions can be evaluated: |
||
< |
<syntaxhighlight lang="jq">$ jq -c ' [.[] + 1 ]' |
||
[0, 1 , 10] |
[0, 1 , 10] |
||
[1,2,11]</ |
[1,2,11]</syntaxhighlight> |
||
=={{header| |
=={{header|Jsish}}== |
||
<syntaxhighlight lang="javascript">/* Apply callback, in Jsish using array.map() */ |
|||
<lang julia> |
|||
;[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; }); |
|||
numbers = [1, 3, 5, 7] |
|||
square1 = [square(n) for n in numbers] # list comprehension |
|||
squares2a = map(square, numbers) # functional form |
|||
squares2b = map(x -> x*x, numbers) # functional form with `lambda` |
|||
/* |
|||
#There is also extended block form for the map function |
|||
=!EXPECTSTART!= |
|||
squares2c = map(numbers) do x |
|||
[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; }) ==> [ 1, 4, 9, 16, 25 ] |
|||
sum = 0 |
|||
=!EXPECTEND!= |
|||
for i = 1:x |
|||
*/</syntaxhighlight> |
|||
sum += x^2 #trivial, but you get the point |
|||
end |
|||
return sum |
|||
end |
|||
{{out}} |
|||
squares3 = [n * n for n in numbers] # no need for a function, |
|||
<pre>prompt$ jsish -u applyCallback.jsi |
|||
[PASS] applyCallback.jsi</pre> |
|||
=={{header|Julia}}== |
|||
squares4 = numbers .* numbers # element-wise operation |
|||
{{works with|Julia|0.6}} |
|||
<syntaxhighlight lang="julia">numbers = [1, 3, 5, 7] |
|||
@show [n ^ 2 for n in numbers] # list comprehension |
|||
squares4a = numbers .^ 2 # most arithmetic operations can be done element-wise</lang> |
|||
square(x) = x ^ 2; @show map(square, numbers) # functional form |
|||
@show map(x -> x ^ 2, numbers) # functional form with anonymous function |
|||
@show [n * n for n in numbers] # no need for a function, |
|||
@show numbers .* numbers # element-wise operation |
|||
@show numbers .^ 2 # includes .+, .-, ./, comparison, and bitwise operations as well</syntaxhighlight> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">fun main(args: Array<String>) { |
||
val array = arrayOf(1,2,3,4,5,6,7,8,9,10) // build |
val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // build |
||
val function = { i: Int -> i * i } // function to apply |
val function = { i: Int -> i * i } // function to apply |
||
val list = array.map { function(it) } // process each item |
val list = array.map { function(it) } // process each item |
||
println(list) // print results |
println(list) // print results |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</pre> |
<pre>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</pre> |
||
=={{header|Klingphix}}== |
|||
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy |
|||
( 1 2 3 4 ) [dup *] map |
|||
pstack |
|||
" " input</syntaxhighlight> |
|||
{{out}} |
|||
<pre>((1, 4, 9, 16))</pre> |
|||
=={{header|Lambdatalk}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
{A.map {lambda {:x} {* :x :x}} {A.new 1 2 3 4 5 6 7 8 9 10}} |
|||
-> [1,4,9,16,25,36,49,64,81,100] |
|||
</syntaxhighlight> |
|||
=={{header|Lang}}== |
|||
<syntaxhighlight lang="lang"> |
|||
&arr = fn.arrayGenerateFrom(fn.inc, 10) |
|||
fn.println(&arr) |
|||
fn.arrayMap(&arr, fn.combC(fn.pow, 2)) |
|||
fn.println(&arr) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
|||
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] |
|||
</pre> |
|||
=={{header|Lang5}}== |
=={{header|Lang5}}== |
||
< |
<syntaxhighlight lang="lang5">: square(*) dup * ; |
||
[1 2 3 4 5] square . "\n" . |
[1 2 3 4 5] square . "\n" . |
||
[1 2 3 4 5] 'square apply . "\n" .</ |
[1 2 3 4 5] 'square apply . "\n" .</syntaxhighlight> |
||
=={{header|langur}}== |
|||
<syntaxhighlight lang="langur">writeln map(fn{^2}, 1..10)</syntaxhighlight> |
|||
{{out}} |
|||
<pre>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</pre> |
|||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">define cube(n::integer) => #n*#n*#n |
||
local( |
local( |
||
Line 1,480: | Line 1,983: | ||
} |
} |
||
#mycube</ |
#mycube</syntaxhighlight> |
||
-> array(1, 8, 27, 64, 125) |
-> array(1, 8, 27, 64, 125) |
||
=={{header|Lisaac}}== |
=={{header|Lisaac}}== |
||
< |
<syntaxhighlight lang="lisaac">+ a : ARRAY(INTEGER); |
||
+ b : {INTEGER;}; |
+ b : {INTEGER;}; |
||
Line 1,497: | Line 2,000: | ||
}; |
}; |
||
a.foreach b;</ |
a.foreach b;</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">to square :x |
||
output :x * :x |
output :x * :x |
||
end |
end |
||
show map "square [1 2 3 4 5] ; [1 4 9 16 25] |
show map "square [1 2 3 4 5] ; [1 4 9 16 25] |
||
show map [? * ?] [1 2 3 4 5] ; [1 4 9 16 25] |
show map [? * ?] [1 2 3 4 5] ; [1 4 9 16 25] |
||
foreach [1 2 3 4 5] [print square ?] ; 1 4 9 16 25, one per line</ |
foreach [1 2 3 4 5] [print square ?] ; 1 4 9 16 25, one per line</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Say we have an array: |
Say we have an array: |
||
< |
<syntaxhighlight lang="lua">myArray = {1, 2, 3, 4, 5}</syntaxhighlight> |
||
A map function for this would be |
A map function for this would be |
||
< |
<syntaxhighlight lang="lua">map = function(f, data) |
||
local result = {} |
local result = {} |
||
for k,v in ipairs(data) do |
for k,v in ipairs(data) do |
||
Line 1,518: | Line 2,021: | ||
end |
end |
||
return result |
return result |
||
end</ |
end</syntaxhighlight> |
||
Together with our array and a square function this yields: |
Together with our array and a square function this yields: |
||
< |
<syntaxhighlight lang="lua">myFunc = function(x) return x*x end |
||
print(unpack( map(myFunc, myArray) )) |
print(unpack( map(myFunc, myArray) )) |
||
--> 1 4 9 16 25</ |
--> 1 4 9 16 25</syntaxhighlight> |
||
If you used pairs() instead of ipairs(), this would even work on a hash table in general. |
If you used pairs() instead of ipairs(), this would even work on a hash table in general. |
||
However, remember that hash table do not have an implicit ordering on their elements, like arrays do, |
However, remember that hash table do not have an implicit ordering on their elements, like arrays do, |
||
so pairs() is not guaranteed to return the elements in the same order as ipairs() |
so pairs() is not guaranteed to return the elements in the same order as ipairs() |
||
=={{header|M2000 Interpreter}}== |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
a=(1,2,3,4,5) |
|||
b=lambda->{ |
|||
push number**2 |
|||
} |
|||
Print a#map(b) ' 1 4 9 16 25 |
|||
Print a#map(b, b) ' 1 16 81 256 625 |
|||
b=lambda (z) ->{ |
|||
=lambda z ->{ |
|||
push number**z |
|||
} |
|||
} |
|||
Print a#map(b(2)) ' 1 4 9 16 25 |
|||
Print a#map(b(3)) ' 1 8 27 64 125 |
|||
\\ second example |
|||
a=(1,2,3,4,5) |
|||
class s {sum=0} |
|||
\\ s is a pointer to an instance of s() |
|||
s->s() |
|||
c=lambda s -> { |
|||
push number+number |
|||
s=>sum=stackitem() ' peek the value from stack |
|||
} |
|||
\\ c passed by value to fold(), but has a pointer to s |
|||
Print a#fold(c, 100)=115 |
|||
Print s=>sum=115 |
|||
</syntaxhighlight> |
|||
=={{header|M4}}== |
=={{header|M4}}== |
||
< |
<syntaxhighlight lang="m4">define(`foreach', `pushdef(`$1')_foreach($@)popdef(`$1')')dnl |
||
define(`_arg1', `$1')dnl |
define(`_arg1', `$1')dnl |
||
define(`_foreach', `ifelse(`$2', `()', `', |
define(`_foreach', `ifelse(`$2', `()', `', |
||
Line 1,537: | Line 2,071: | ||
dnl |
dnl |
||
define(`z',`eval(`$1*2') ')dnl |
define(`z',`eval(`$1*2') ')dnl |
||
apply(`(1,2,3)',`z')</ |
apply(`(1,2,3)',`z')</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 1,547: | Line 2,081: | ||
For lists and sets, which in Maple are immutable, a new object is returned. |
For lists and sets, which in Maple are immutable, a new object is returned. |
||
Either the built-in procedure map, or the short syntax of a trailing tilde (~) on the applied operator may be used. |
Either the built-in procedure map, or the short syntax of a trailing tilde (~) on the applied operator may be used. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> map( sqrt, [ 1.1, 3.2, 5.7 ] ); |
> map( sqrt, [ 1.1, 3.2, 5.7 ] ); |
||
[1.048808848, 1.788854382, 2.387467277] |
[1.048808848, 1.788854382, 2.387467277] |
||
Line 1,559: | Line 2,093: | ||
> (x -> x + 1)~( { 1, 3, 5 } ); |
> (x -> x + 1)~( { 1, 3, 5 } ); |
||
{2, 4, 6} |
{2, 4, 6} |
||
</syntaxhighlight> |
|||
</lang> |
|||
For Arrays (Vectors, Matrices, etc.) both map and trailing tilde also work, and by default create a new object, leaving the input Array unchanged. |
For Arrays (Vectors, Matrices, etc.) both map and trailing tilde also work, and by default create a new object, leaving the input Array unchanged. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> a := Array( [ 1.1, 3.2, 5.7 ] ); |
> a := Array( [ 1.1, 3.2, 5.7 ] ); |
||
a := [1.1, 3.2, 5.7] |
a := [1.1, 3.2, 5.7] |
||
Line 1,576: | Line 2,110: | ||
> a; |
> a; |
||
[1.1, 3.2, 5.7] |
[1.1, 3.2, 5.7] |
||
</syntaxhighlight> |
|||
</lang> |
|||
However, since these are mutable data structures in Maple, it is possible to use map to modify its input according to the applied procedure. |
However, since these are mutable data structures in Maple, it is possible to use map to modify its input according to the applied procedure. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> map[inplace]( sqrt, a ); |
> map[inplace]( sqrt, a ); |
||
[1.048808848, 1.788854382, 2.387467277] |
[1.048808848, 1.788854382, 2.387467277] |
||
Line 1,584: | Line 2,118: | ||
> a; |
> a; |
||
[1.048808848, 1.788854382, 2.387467277] |
[1.048808848, 1.788854382, 2.387467277] |
||
</syntaxhighlight> |
|||
</lang> |
|||
The Array a has been modified. |
The Array a has been modified. |
||
It is also possible to pass additional arguments to the mapped procedure. |
It is also possible to pass additional arguments to the mapped procedure. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> map( `+`, [ 1, 2, 3 ], 3 ); |
> map( `+`, [ 1, 2, 3 ], 3 ); |
||
[4, 5, 6] |
[4, 5, 6] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Passing additional arguments *before* the arguments from the mapped data structure is achieved using map2, or the more general map[n] procedure. |
Passing additional arguments *before* the arguments from the mapped data structure is achieved using map2, or the more general map[n] procedure. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> map2( `-`, 5, [ 1, 2, 3 ] ); |
> map2( `-`, 5, [ 1, 2, 3 ] ); |
||
[4, 3, 2] |
[4, 3, 2] |
||
Line 1,599: | Line 2,133: | ||
> map[2]( `/`, 5, [ 1, 2, 3 ] ); |
> map[2]( `/`, 5, [ 1, 2, 3 ] ); |
||
[5, 5/2, 5/3] |
[5, 5/2, 5/3] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mathematica}}== |
|||
<lang Mathematica>(#*#)& /@ {1, 2, 3, 4} |
|||
=={{header|Mathematica}}//{{header|Wolfram Language}}== |
|||
<syntaxhighlight lang="mathematica">(#*#)& /@ {1, 2, 3, 4} |
|||
Map[Function[#*#], {1, 2, 3, 4}] |
Map[Function[#*#], {1, 2, 3, 4}] |
||
Map[((#*#)&,{1,2,3,4}] |
Map[((#*#)&,{1,2,3,4}] |
||
Map[Function[w,w*w],{1,2,3,4}]</syntaxhighlight> |
|||
Map[Function[w,w*w],{1,2,3,4}]</lang> |
|||
=={{header|MATLAB}}== |
=={{header|MATLAB}}== |
||
Line 1,614: | Line 2,145: | ||
Example: |
Example: |
||
For both of these function the first argument is a function handle for the function we would like to apply to each element. The second argument is the array whose elements are modified by the function. The function can be any function, including user defined functions. |
For both of these function the first argument is a function handle for the function we would like to apply to each element. The second argument is the array whose elements are modified by the function. The function can be any function, including user defined functions. |
||
< |
<syntaxhighlight lang="matlab">>> array = [1 2 3 4 5] |
||
array = |
array = |
||
Line 1,648: | Line 2,179: | ||
Column 5 |
Column 5 |
||
-3.380515006246586</ |
-3.380515006246586</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">/* for lists or sets */ |
||
map(sin, [1, 2, 3, 4]); |
map(sin, [1, 2, 3, 4]); |
||
Line 1,658: | Line 2,189: | ||
/* for matrices */ |
/* for matrices */ |
||
matrixmap(sin, matrix([1, 2], [2, 4]));</ |
matrixmap(sin, matrix([1, 2], [2, 4]));</syntaxhighlight> |
||
=={{header|min}}== |
|||
{{works with|min|0.19.3}} |
|||
<syntaxhighlight lang="min">(1 2 3 4 5) (sqrt puts) foreach ; print each square root |
|||
(1 2 3 4 5) 'sqrt map ; collect return values</syntaxhighlight> |
|||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
< |
<syntaxhighlight lang="modula3">MODULE Callback EXPORTS Main; |
||
IMPORT IO, Fmt; |
IMPORT IO, Fmt; |
||
Line 1,686: | Line 2,222: | ||
BEGIN |
BEGIN |
||
Map(sample, NUMBER(sample), callback); |
Map(sample, NUMBER(sample), callback); |
||
END Callback.</ |
END Callback.</syntaxhighlight> |
||
=={{header|Nanoquery}}== |
|||
<syntaxhighlight lang="nanoquery">// create a list of numbers 1-10 |
|||
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} |
|||
// display the list as it is |
|||
println numbers |
|||
// square each element in the list |
|||
for i in range(1, len(numbers) - 1) |
|||
numbers[i] = numbers[i] * numbers[i] |
|||
end |
|||
// display the squared list |
|||
println numbers</syntaxhighlight> |
|||
{{out}} |
|||
<pre>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
|||
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</pre> |
|||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
The <tt>Nemerle.Collections</tt> namespace defines the methods <tt>Iter()</tt> (if the function applied is <tt>void</tt>) and <tt>Map()</tt> (if the function applied returns a value). |
The <tt>Nemerle.Collections</tt> namespace defines the methods <tt>Iter()</tt> (if the function applied is <tt>void</tt>) and <tt>Map()</tt> (if the function applied returns a value). |
||
< |
<syntaxhighlight lang="nemerle">def seg = array[1, 2, 3, 5, 8, 13]; |
||
def squares = seq.Map(x => x*x);</ |
def squares = seq.Map(x => x*x);</syntaxhighlight> |
||
=={{header|NetLogo}}== |
|||
<syntaxhighlight lang="netlogo"> |
|||
;; NetLogo “anonymous procedures” |
|||
;; stored in a variable, just to show it can be done. |
|||
let callback [ [ x ] x * x ] |
|||
show (map callback [ 1 2 3 4 5 ]) |
|||
</syntaxhighlight> |
|||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<syntaxhighlight lang="newlisp">> (map (fn (x) (* x x)) '(1 2 3 4)) |
||
(1 4 9 16) |
(1 4 9 16) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|NGS}}== |
=={{header|NGS}}== |
||
<syntaxhighlight lang="ngs">{ |
|||
<lang NGS>{ |
|||
[1, 2, 3, 4, 5].map(F(x) x*x) |
[1, 2, 3, 4, 5].map(F(x) x*x) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Nial}}== |
=={{header|Nial}}== |
||
< |
<syntaxhighlight lang="nial">each (* [first, first] ) 1 2 3 4 |
||
=1 4 9 16</ |
=1 4 9 16</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
<syntaxhighlight lang="nim"> |
|||
<lang nim>var arr = [1,2,3,4] |
|||
from std/sequtils import apply |
|||
arr.map proc(some: var int) = echo(some, " squared = ", some*some)</lang> |
|||
let arr = @[1,2,3,4] |
|||
arr.apply proc(some: int) = echo(some, " squared = ", some*some)</syntaxhighlight> |
|||
{{Out}} |
{{Out}} |
||
Line 1,719: | Line 2,283: | ||
3 squared = 9 |
3 squared = 9 |
||
4 squared = 16 |
4 squared = 16 |
||
=={{header|Nutt}}== |
|||
<syntaxhighlight lang="Nutt"> |
|||
module main |
|||
imports native.io.output.say |
|||
operator |> (arr:Array,f:Procedure):Array==>{f(x) of x |-> arr} |
|||
say({0,1,2,3,4,5}|>a==>a+2)//|{2,3,4,5,6,7} |
|||
end |
|||
</syntaxhighlight> |
|||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
{{Works with|oo2x}} |
{{Works with|oo2x}} |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE ApplyCallBack; |
MODULE ApplyCallBack; |
||
IMPORT |
IMPORT |
||
Line 1,811: | Line 2,388: | ||
Init(a);r := Map3(Fun3,a);Show(r^); |
Init(a);r := Map3(Fun3,a);Show(r^); |
||
END ApplyCallBack. |
END ApplyCallBack. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 1,820: | Line 2,397: | ||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
use Structure; |
use Structure; |
||
Line 1,842: | Line 2,419: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
This function is part of the standard library: |
This function is part of the standard library: |
||
<lang |
<syntaxhighlight lang="ocaml">Array.map</syntaxhighlight> |
||
Usage example: |
Usage example: |
||
< |
<syntaxhighlight lang="ocaml">let square x = x * x;; |
||
let values = Array.init 10 ((+) 1);; |
let values = Array.init 10 ((+) 1);; |
||
Array.map square values;;</ |
Array.map square values;;</syntaxhighlight> |
||
Or with lists (which are more typical in OCaml): |
Or with lists (which are more typical in OCaml): |
||
< |
<syntaxhighlight lang="ocaml">let values = [1;2;3;4;5;6;7;8;9;10];; |
||
List.map square values;;</ |
List.map square values;;</syntaxhighlight> |
||
Use <tt>iter</tt> if the applied function does not return a value. |
Use <tt>iter</tt> if the applied function does not return a value. |
||
< |
<syntaxhighlight lang="ocaml">Array.iter (fun x -> Printf.printf "%d" x) [|1; 2; 3; 4; 5|];;</syntaxhighlight> |
||
< |
<syntaxhighlight lang="ocaml">List.iter (fun x -> Printf.printf "%d" x) [1; 2; 3; 4; 5];;</syntaxhighlight> |
||
with partial application we can also write: |
with partial application we can also write: |
||
< |
<syntaxhighlight lang="ocaml">Array.iter (Printf.printf "%d") [|1; 2; 3; 4; 5|];;</syntaxhighlight> |
||
< |
<syntaxhighlight lang="ocaml">List.iter (Printf.printf "%d") [1; 2; 3; 4; 5];;</syntaxhighlight> |
||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
Line 1,872: | Line 2,449: | ||
Almost all the built-in can operate on each element of a vector or matrix; e.g. sin([pi/2, pi, 2*pi]) computes the function sin on pi/2, pi and 2*pi (returning a vector). If a function does not accept vectors/matrices as arguments, the <tt>arrayfun</tt> can be used. |
Almost all the built-in can operate on each element of a vector or matrix; e.g. sin([pi/2, pi, 2*pi]) computes the function sin on pi/2, pi and 2*pi (returning a vector). If a function does not accept vectors/matrices as arguments, the <tt>arrayfun</tt> can be used. |
||
< |
<syntaxhighlight lang="octave">function e = f(x, y) |
||
e = x^2 + exp(-1/(y+1)); |
e = x^2 + exp(-1/(y+1)); |
||
endfunction |
endfunction |
||
Line 1,878: | Line 2,455: | ||
% f([2,3], [1,4]) gives and error, but |
% f([2,3], [1,4]) gives and error, but |
||
arrayfun(@f, [2, 3], [1,4]) |
arrayfun(@f, [2, 3], [1,4]) |
||
% works</ |
% works</syntaxhighlight> |
||
(The function <tt>f</tt> can be rewritten so that it can accept vectors as argument simply changing operators to their dot ''relatives'': <code>e = x.^2 + exp(-1 ./ (y.+1))</code>) |
(The function <tt>f</tt> can be rewritten so that it can accept vectors as argument simply changing operators to their dot ''relatives'': <code>e = x.^2 + exp(-1 ./ (y.+1))</code>) |
||
=={{header|Odin}}== |
|||
<syntaxhighlight lang="odin">package main |
|||
import "core:slice" |
|||
import "core:fmt" |
|||
squared :: proc(x: int) -> int { |
|||
return x * x |
|||
} |
|||
main :: proc() { |
|||
arr := []int{1, 2, 3, 4, 5} |
|||
res := slice.mapper(arr, squared) |
|||
fmt.println(res) // prints: [1, 4, 9, 16, 25] |
|||
}</syntaxhighlight> |
|||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
apply allows to perform a function on all elements of a list : |
apply allows to perform a function on all elements of a list : |
||
<lang |
<syntaxhighlight lang="oforth">0 #+ [ 1, 2, 3, 4, 5 ] apply</syntaxhighlight> |
||
map regroups all results into a new list : |
map regroups all results into a new list : |
||
< |
<syntaxhighlight lang="oforth">#sq [ 1, 2, 3, 4, 5 ] map</syntaxhighlight> |
||
=={{header|Ol}}== |
|||
Apply custom callback (lambda) to every element of list. |
|||
<syntaxhighlight lang="scheme"> |
|||
(for-each |
|||
(lambda (element) |
|||
(display element)) |
|||
'(1 2 3 4 5)) |
|||
; ==> 12345 |
|||
</syntaxhighlight> |
|||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
ooRexx doesn't directly support callbacks on array items, but this is pretty easy to implement using Routine objects. |
ooRexx doesn't directly support callbacks on array items, but this is pretty easy to implement using Routine objects. |
||
<syntaxhighlight lang="oorexx">start = .array~of("Rick", "Mike", "David", "Mark") |
|||
<lang ooRexx> |
|||
start = .array~of("Rick", "Mike", "David", "Mark") |
|||
new = map(start, .routines~reversit) |
new = map(start, .routines~reversit) |
||
call map new, .routines~sayit |
call map new, .routines~sayit |
||
Line 1,915: | Line 2,519: | ||
use arg string |
use arg string |
||
say string |
say string |
||
return .true -- called as a function, so a result is required |
return .true -- called as a function, so a result is required</syntaxhighlight> |
||
{{out}} |
|||
<pre>kciR |
|||
</lang> |
|||
ekiM |
|||
divaD |
|||
kraM</pre> |
|||
=={{header|Order}}== |
=={{header|Order}}== |
||
Both sequences and tuples support the usual map operation seen in many functional languages. Sequences also support <code>8seq_for_each</code>, and a few variations, which returns <code>8nil</code>. |
Both sequences and tuples support the usual map operation seen in many functional languages. Sequences also support <code>8seq_for_each</code>, and a few variations, which returns <code>8nil</code>. |
||
< |
<syntaxhighlight lang="c">#include <order/interpreter.h> |
||
ORDER_PP( 8tuple_map(8fn(8X, 8times(8X, 8X)), 8tuple(1, 2, 3, 4, 5)) ) |
ORDER_PP( 8tuple_map(8fn(8X, 8times(8X, 8X)), 8tuple(1, 2, 3, 4, 5)) ) |
||
Line 1,930: | Line 2,537: | ||
ORDER_PP( 8seq_for_each(8fn(8X, 8print(8X 8comma)), 8seq(1, 2, 3, 4, 5)) ) |
ORDER_PP( 8seq_for_each(8fn(8X, 8print(8X 8comma)), 8seq(1, 2, 3, 4, 5)) ) |
||
// prints 1,2,3,4,5, and returns 8nil</ |
// prints 1,2,3,4,5, and returns 8nil</syntaxhighlight> |
||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang="oz">declare |
||
fun{Square A} |
fun{Square A} |
||
A*A |
A*A |
||
Line 1,945: | Line 2,552: | ||
%% apply a FUNCTION to every element |
%% apply a FUNCTION to every element |
||
Result = {Map Lst Square} |
Result = {Map Lst Square} |
||
{Show Result}</ |
{Show Result}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
{{works with|PARI/GP|2.4.2 and above}} |
{{works with|PARI/GP|2.4.2 and above}} |
||
< |
<syntaxhighlight lang="parigp">callback(n)=n+n; |
||
apply(callback, [1,2,3,4,5])</ |
apply(callback, [1,2,3,4,5])</syntaxhighlight> |
||
This should be contrasted with <code>call</code>: |
This should be contrasted with <code>call</code>: |
||
< |
<syntaxhighlight lang="parigp">call(callback, [1,2,3,4,5])</syntaxhighlight> |
||
which is equivalent to <code>callback(1, 2, 3, 4, 5)</code> rather than <code>[callback(1), callback(2), callback(3), callback(4), callback(5)]</code>. |
which is equivalent to <code>callback(1, 2, 3, 4, 5)</code> rather than <code>[callback(1), callback(2), callback(3), callback(4), callback(5)]</code>. |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
See [[Apply_a_callback_to_an_array#Delphi | Delphi]] |
See [[Apply_a_callback_to_an_array#Delphi | Delphi]] |
||
=={{header|PascalABC.NET}}== |
|||
<syntaxhighlight lang="pascal"> |
|||
begin |
|||
var a := Arr(1..10); |
|||
a := a.Select(x -> x * x).ToArray; |
|||
a.ForEach(x -> Print(x)); |
|||
end. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 4 9 16 25 36 49 64 81 100 |
|||
</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl"># create array |
||
my @a = (1, 2, 3, 4, 5); |
my @a = (1, 2, 3, 4, 5); |
||
Line 1,989: | Line 2,610: | ||
# filter an array |
# filter an array |
||
my @e = grep { $_ % 2 == 0 } @a; # @e is now (2, 4)</ |
my @e = grep { $_ % 2 == 0 } @a; # @e is now (2, 4)</syntaxhighlight> |
||
=={{header| |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
|||
{{works with|Rakudo|2015.10-11}} |
|||
<!--<syntaxhighlight lang="phix">(phixonline)--> |
|||
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"0.8.2"</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">function</span> <span style="color: #000000;">add1</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">return</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">1</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},</span><span style="color: #000000;">add1</span><span style="color: #0000FF;">)</span> |
|||
<!--</syntaxhighlight>--> |
|||
{{out}} |
|||
<pre> |
|||
{2,3,4} |
|||
</pre> |
|||
There are in fact three ways to invoke apply:<br> |
|||
The oldest/original, as above, is apply(s,fn), where fn is invoked length(s) times with a single parameter of s[i].<br> |
|||
apply(false,fn,s) likewise invokes fn length(s) times, but each time with length(s[i]) parameters.<br> |
|||
apply(true,sprintf,{{"%d"},s}), the third way, invokes sprintf length(s) times with two parameters, being "%d" and each s[i].<br> |
|||
This last way scans it's third argument looking for a (consistent) longest length to determine how many times to invoke sprintf, <br> |
|||
uses the length of it's third argument to determine how many parameters each call will get, and <br> |
|||
uses the same value on every call for any atom or length 1 elements, such as that {"%d"}. |
|||
=={{header|Phixmonti}}== |
|||
<lang perl6>sub function { 2 * $^x + 3 }; |
|||
<syntaxhighlight lang="phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Apply_a_callback_to_an_array |
|||
my @array = 1 .. 5; |
|||
by Galileo, 05/2022 #/ |
|||
include ..\Utilitys.pmt |
|||
# via map function |
|||
.say for map &function, @array; |
|||
def ++ |
|||
# via map method |
|||
1 + |
|||
.say for @array.map(&function); |
|||
enddef |
|||
def square |
|||
# via for loop |
|||
dup * |
|||
for @array { |
|||
enddef |
|||
say function($_); |
|||
} |
|||
( 1 2 3 ) dup |
|||
# via the "hyper" metaoperator and method indirection |
|||
say @array».&function; |
|||
getid ++ map swap |
|||
# we neither need a variable for the array nor for the function |
|||
getid square map |
|||
say [1,2,3]>>.&({ $^x + 1}); |
|||
</lang> |
|||
pstack</syntaxhighlight> |
|||
=={{header|Phix}}== |
|||
<lang Phix>function apply(integer f, sequence s) |
|||
-- apply function f to all elements of sequence s |
|||
for i = 1 to length(s) do |
|||
s[i] = call_func(f, {s[i]}) |
|||
end for |
|||
return s |
|||
end function |
|||
function add1(integer x) |
|||
return x + 1 |
|||
end function |
|||
? apply(routine_id("add1"),{1,2,3})</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
[[2, 3, 4], [1, 4, 9]] |
|||
</pre> |
|||
=== Press any key to exit ===</pre> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">function cube($n) |
||
{ |
{ |
||
return($n * $n * $n); |
return($n * $n * $n); |
||
Line 2,042: | Line 2,669: | ||
$a = array(1, 2, 3, 4, 5); |
$a = array(1, 2, 3, 4, 5); |
||
$b = array_map("cube", $a); |
$b = array_map("cube", $a); |
||
print_r($b);</ |
print_r($b);</syntaxhighlight> |
||
=={{header|Picat}}== |
|||
Picat doesn't support anonymous (lambda) functions so the function must be defined in the program to be used by - say - map/2. |
|||
There are - however - quite a few ways without proper lambdas, using map/2, apply/2, or list comprehensions. |
|||
<syntaxhighlight lang="picat">go => |
|||
L = 1..10, |
|||
% Using map/2 in different ways |
|||
println(L.map(fun)), |
|||
println(map(L,fun)), |
|||
println(map(fun,L)), |
|||
% List comprehensions |
|||
println([fun(I) : I in L]), |
|||
% Using apply/2 |
|||
println([apply(fun,I) : I in L]), |
|||
% And using list comprehension with the function directly. |
|||
println([I*I : I in L]), |
|||
nl. |
|||
% Some function |
|||
fun(X) = X*X. |
|||
</syntaxhighlight> |
|||
{{trans|Prolog}} |
|||
This variant is inspired by the Prolog solution (using assert/1 to define a predicate) and shows the integration with Picat's underlying B-Prolog engine. |
|||
Picat does not support assert/1 directly, so one have to do the assert/1 in the bp module space (the module/space for the B-Prolog engine). To call the defined predicate, one must prepend the predicate name with "bp.". |
|||
Note that fun2/2 is not a function so map/2 or apply/2 cannot be used here. |
|||
<syntaxhighlight lang="picat">go2 => |
|||
L = 1..10, |
|||
% Define the predicate _in the bp space_. |
|||
bp.assert( $(fun2(X,Y) :- Y is X*X) ), |
|||
% Use bp.fun2 to call the function. |
|||
println([B : A in L, bp.fun2(A,B)]), |
|||
nl. |
|||
</syntaxhighlight> |
|||
Using this technique one can do quite much "real" Prolog stuff even though Picat doesn't support it directly. However, one should be careful with this approach since it can sometimes be confusing and it doesn't work in all cases. |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">: (mapc println (1 2 3 4 5)) # Print numbers |
||
1 |
1 |
||
2 |
2 |
||
Line 2,060: | Line 2,731: | ||
: (mapcar if '(T NIL T NIL) '(1 2 3 4) '(5 6 7 8)) # Conditional function |
: (mapcar if '(T NIL T NIL) '(1 2 3 4) '(5 6 7 8)) # Conditional function |
||
-> (1 6 3 8)</ |
-> (1 6 3 8)</syntaxhighlight> |
||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
< |
<syntaxhighlight lang="pike">int cube(int n) |
||
{ |
{ |
||
return n*n*n; |
return n*n*n; |
||
Line 2,070: | Line 2,741: | ||
array(int) a = ({ 1,2,3,4,5 }); |
array(int) a = ({ 1,2,3,4,5 }); |
||
array(int) b = cube(a[*]); // automap operator |
array(int) b = cube(a[*]); // automap operator |
||
array(int) c = map(a, cube); // conventional map function</ |
array(int) c = map(a, cube); // conventional map function</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pl/i"> declare x(5) initial (1,3,5,7,8); |
||
x = sqrt(x); |
x = sqrt(x); |
||
x = sin(x);</ |
x = sin(x);</syntaxhighlight> |
||
=={{header|PL/SQL}}== |
=={{header|PL/SQL}}== |
||
PL/SQL doesn't have callbacks, though we can pass around an object and use its method to simulate one. Further, this callback method can be defined in an abstract class that the mapping function will expect. |
PL/SQL doesn't have callbacks, though we can pass around an object and use its method to simulate one. Further, this callback method can be defined in an abstract class that the mapping function will expect. |
||
< |
<syntaxhighlight lang="plsql">-- Let's create a generic class with one method to be used as an interface: |
||
create or replace |
create or replace |
||
TYPE callback AS OBJECT ( |
TYPE callback AS OBJECT ( |
||
Line 2,154: | Line 2,825: | ||
PKG_CALLBACK.TEST_CALLBACK(); |
PKG_CALLBACK.TEST_CALLBACK(); |
||
END; |
END; |
||
/</ |
/</syntaxhighlight> |
||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
< |
<syntaxhighlight lang="pop11">;;; Define a procedure |
||
define proc(x); |
define proc(x); |
||
printf(x*x, '%p,'); |
printf(x*x, '%p,'); |
||
Line 2,167: | Line 2,838: | ||
;;; Apply procedure to array |
;;; Apply procedure to array |
||
appdata(ar, proc);</ |
appdata(ar, proc);</syntaxhighlight> |
||
If one wants to create a new array consisting of transformed values then procedure mapdata may be more convenient. |
If one wants to create a new array consisting of transformed values then procedure mapdata may be more convenient. |
||
Line 2,173: | Line 2,844: | ||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
The <code>forall</code> operator applies a procedure to each element of an array, a packed array or a string. |
The <code>forall</code> operator applies a procedure to each element of an array, a packed array or a string. |
||
< |
<syntaxhighlight lang="postscript">[1 2 3 4 5] { dup mul = } forall</syntaxhighlight> |
||
In this case the respective square numbers for the elements are printed. |
In this case the respective square numbers for the elements are printed. |
||
To create a new array from the results above code can simply be wrapped in <code>[]</code>: |
To create a new array from the results above code can simply be wrapped in <code>[]</code>: |
||
< |
<syntaxhighlight lang="postscript">[ [1 2 3 4 5] { dup mul } forall ]</syntaxhighlight> |
||
{{libheader|initlib}} |
{{libheader|initlib}} |
||
< |
<syntaxhighlight lang="postscript"> |
||
[1 2 3 4 5] {dup *} map |
[1 2 3 4 5] {dup *} map |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
This can be done in PowerShell with the <code>ForEach-Object</code> cmdlet which applies a scriptblock to each element of an array: |
This can be done in PowerShell with the <code>ForEach-Object</code> cmdlet which applies a scriptblock to each element of an array: |
||
< |
<syntaxhighlight lang="powershell">1..5 | ForEach-Object { $_ * $_ }</syntaxhighlight> |
||
To recreate a ''map'' function, found in other languages the same method applies: |
To recreate a ''map'' function, found in other languages the same method applies: |
||
< |
<syntaxhighlight lang="powershell">function map ([array] $a, [scriptblock] $s) { |
||
$a | ForEach-Object $s |
$a | ForEach-Object $s |
||
} |
|||
}</lang> |
|||
map (1..5) { $_ * $_ }</syntaxhighlight> |
|||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Prolog doesn't have arrays, but we can do it with lists. This can be done in the console mode. |
Prolog doesn't have arrays, but we can do it with lists. This can be done in the console mode. |
||
< |
<syntaxhighlight lang="prolog"> ?- assert((fun(X, Y) :- Y is 2 * X)). |
||
true. |
true. |
||
?- maplist(fun, [1,2,3,4,5], L). |
?- maplist(fun, [1,2,3,4,5], L). |
||
L = [2,4,6,8,10]. |
L = [2,4,6,8,10]. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Procedure Cube(Array param.i(1)) |
||
Protected n.i |
Protected n.i |
||
For n = 0 To ArraySize(param()) |
For n = 0 To ArraySize(param()) |
||
Line 2,215: | Line 2,887: | ||
Next |
Next |
||
Cube(AnArray()) </ |
Cube(AnArray()) </syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">def square(n): |
||
return n * n |
return n * n |
||
Line 2,235: | Line 2,907: | ||
import itertools |
import itertools |
||
isquares2 = itertools.imap(square, numbers) # iterator, lazy</ |
isquares2 = itertools.imap(square, numbers) # iterator, lazy</syntaxhighlight> |
||
To print squares of integers in the range from 0 to 9, type: |
To print squares of integers in the range from 0 to 9, type: |
||
< |
<syntaxhighlight lang="python">print " ".join(str(n * n) for n in range(10))</syntaxhighlight> |
||
Or: |
Or: |
||
< |
<syntaxhighlight lang="python">print " ".join(map(str, map(square, range(10))))</syntaxhighlight> |
||
Result: |
Result: |
||
< |
<syntaxhighlight lang="python">0 1 4 9 16 25 36 49 64 81</syntaxhighlight> |
||
=={{header|QB64}}== |
|||
<syntaxhighlight lang="qb64"> |
|||
'Task |
|||
'Take a combined set of elements and apply a function to each element. |
|||
'UDT |
|||
Type Friend |
|||
Names As String * 8 |
|||
Surnames As String * 8 |
|||
Age As Integer |
|||
End Type |
|||
Dim Friends(1 To 6) As Friend |
|||
Restore |
|||
FillArray |
|||
SearchForAdult Friends(), LBound(friends), UBound(friends) |
|||
End |
|||
Data "John","Beoz",13,"Will","Strange",22 |
|||
Data "Arthur","Boile",16,"Peter","Smith",21 |
|||
Data "Tom","Parker",14,"Tim","Wesson",24 |
|||
Sub FillArray |
|||
Shared Friends() As Friend |
|||
Dim indeX As Integer |
|||
For indeX = LBound(friends) To UBound(friends) Step 1 |
|||
Read Friends(indeX).Names, Friends(indeX).Surnames, Friends(indeX).Age |
|||
Next |
|||
End Sub |
|||
Sub SearchForAdult (F() As Friend, Min As Integer, Max As Integer) |
|||
Dim Index As Integer |
|||
Print "Friends with more than 18 years old" |
|||
For Index = Min To Max Step 1 |
|||
If F(Index).Age > 18 Then Print F(Index).Names; " "; F(Index).Surnames; " "; F(Index).Age |
|||
Next Index |
|||
End Sub |
|||
</syntaxhighlight> |
|||
=={{header|Quackery}}== |
|||
As a dialogue in the Quackery shell (REPL), applying the word <code>cubed</code> to the nest <code>[ 1 2 3 4 5 6 7 8 9 10 ]</code>, first treating the nest as a list, then as an array. |
|||
<syntaxhighlight lang="quackery">/O> [ 3 ** ] is cubed ( n --> n ) |
|||
... |
|||
Stack empty. |
|||
/O> ' [ 1 2 3 4 5 6 7 8 9 10 ] |
|||
... [] swap witheach |
|||
... [ cubed join ] |
|||
... |
|||
Stack: [ 1 8 27 64 125 216 343 512 729 1000 ] |
|||
/O> drop |
|||
... |
|||
Stack empty. |
|||
/O> ' [ 1 2 3 4 5 6 7 8 9 10 ] |
|||
... dup witheach |
|||
... [ cubed swap i^ poke ] |
|||
... |
|||
Stack: [ 1 8 27 64 125 216 343 512 729 1000 ]</syntaxhighlight> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
Many functions can take advantage of implicit vectorisation, e.g. |
Many functions can take advantage of implicit vectorisation, e.g. |
||
< |
<syntaxhighlight lang="r">cube <- function(x) x*x*x |
||
elements <- 1:5 |
elements <- 1:5 |
||
cubes <- cube(elements)</ |
cubes <- cube(elements)</syntaxhighlight> |
||
Explicit looping over array elements is also possible. |
Explicit looping over array elements is also possible. |
||
< |
<syntaxhighlight lang="r">cubes <- numeric(5) |
||
for(i in seq_along(cubes)) |
for(i in seq_along(cubes)) |
||
{ |
{ |
||
cubes[i] <- cube(elements[i]) |
cubes[i] <- cube(elements[i]) |
||
}</ |
}</syntaxhighlight> |
||
Loop syntax can often simplified using the [http://stat.ethz.ch/R-manual/R-patched/library/base/html/apply.html *apply] family of functions. |
Loop syntax can often simplified using the [http://stat.ethz.ch/R-manual/R-patched/library/base/html/apply.html *apply] family of functions. |
||
< |
<syntaxhighlight lang="r">elements2 <- list(1,2,3,4,5) |
||
cubes <- sapply(elements2, cube)</ |
cubes <- sapply(elements2, cube)</syntaxhighlight> |
||
In each case above, the value of 'cubes' is |
In each case above, the value of 'cubes' is |
||
1 8 27 64 125 |
1 8 27 64 125 |
||
Line 2,262: | Line 3,002: | ||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
Line 2,270: | Line 3,010: | ||
;; the usual functional `map' |
;; the usual functional `map' |
||
(vector-map sqr #(1 2 3 4 5)) |
(vector-map sqr #(1 2 3 4 5)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
{{works with|Rakudo|2015.10-11}} |
|||
<syntaxhighlight lang="raku" line>sub function { 2 * $^x + 3 }; |
|||
my @array = 1 .. 5; |
|||
# via map function |
|||
.say for map &function, @array; |
|||
# via map method |
|||
.say for @array.map(&function); |
|||
# via for loop |
|||
for @array { |
|||
say function($_); |
|||
} |
|||
# via the "hyper" metaoperator and method indirection |
|||
say @array».&function; |
|||
# we neither need a variable for the array nor for the function |
|||
say [1,2,3]>>.&({ $^x + 1}); |
|||
</syntaxhighlight> |
|||
=={{header|Raven}}== |
=={{header|Raven}}== |
||
< |
<syntaxhighlight lang="raven"># To print the squared elements |
||
[1 2 3 4 5] each dup * print</ |
[1 2 3 4 5] each dup * print</syntaxhighlight> |
||
< |
<syntaxhighlight lang="raven"># To obtain a new array |
||
group [1 2 3 4 5] each |
group [1 2 3 4 5] each |
||
dup * |
dup * |
||
list</ |
list</syntaxhighlight> |
||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang="rebol">REBOL [ |
||
Title: "Array Callback" |
Title: "Array Callback" |
||
Date: 2010-01-04 |
|||
Author: oofoe |
|||
URL: http://rosettacode.org/wiki/Apply_a_callback_to_an_Array |
URL: http://rosettacode.org/wiki/Apply_a_callback_to_an_Array |
||
] |
] |
||
Line 2,309: | Line 3,072: | ||
print [crlf "Applying native function with 'map':"] |
print [crlf "Applying native function with 'map':"] |
||
assert [[2 4 6] = map :square-root [4 16 36]]</ |
assert [[2 4 6] = map :square-root [4 16 36]]</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 2,322: | Line 3,085: | ||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
Using the '''array'''' library to multiply each value in an array by 10 and display the results: |
|||
Retro provides a variety of array words. Using these to multiply each value in an array by 10 and display the results: |
|||
<syntaxhighlight lang="retro">{ #1 #2 #3 #4 #5 } [ #10 * ] a:map [ n:put sp ] a:for-each</syntaxhighlight> |
|||
Retro also provides '''^array'apply''' for use when you don't want to alter the contents of the array: |
|||
<lang Retro>[ "Hello" "World" "Foo" ] ^array'fromQuote [ "%s " puts ] ^array'apply</lang> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program applies a callback to an array (using factorials for a demonstration).*/ |
||
numeric digits 100 /*be able to display some huge numbers.*/ |
|||
a.=; b.=; a.0 = 0 |
|||
parse arg # . /*obtain an optional value from the CL.*/ |
|||
a.= /*initialize the array A to all nulls*/ |
|||
if #=='' | #=="," then #= 12 /*Not assigned? Then use default value*/ |
|||
a. |
do j=0 to #; a.j= j /*assign the integer J ───► A.j */ |
||
end /*j*/ /*array A will have N values: 0 ──► #*/ |
|||
a.6 = 6 |
|||
call listA 'before callback' /*display A array before the callback*/ |
|||
a |
say /*display a blank line for readability.*/ |
||
say ' ··· applying callback to array A ···' /*display what is about to happen to B.*/ |
|||
a |
say /*display a blank line for readability.*/ |
||
call bangit 'a' /*factorialize (the values) of A array.*/ |
|||
call listAB 'before' |
|||
/* store the results ───► array B.*/ |
|||
call listA ' after callback' /*display A array after the callback.*/ |
|||
call listAB ' after' |
|||
exit /*stick a fork in it, we're all done. */ |
exit 0 /*stick a fork in it, we're all done. */ |
||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
/*────────────────────────────────────────────────────────────────────────────*/ |
|||
bangit: do |
bangit: do v=0; $= value(arg(1)'.'v); if $=='' then return /*No value? Then return*/ |
||
call value arg( |
call value arg(1)'.'v, fact($) /*assign a value (a factorial) to array*/ |
||
end /*i*/ |
end /*i*/ |
||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
/*────────────────────────────────────────────────────────────────────────────*/ |
|||
fact: procedure; !=1; do |
fact: procedure; arg x; != 1; do f=2 to x; != !*f; end; /*f*/; return ! |
||
listA: do k=0 while a.k\==''; say arg(1) 'a.'k"=" a.k; end /*k*/; return</syntaxhighlight> |
|||
/*────────────────────────────────────────────────────────────────────────────*/ |
|||
{{out|output|text= when using the default input:}} |
|||
listAB: do j=0 while a.j\==''; say arg(1) 'a.'j"="a.j; end /*j*/; say |
|||
do k=0 while b.k\==''; say arg(1) 'b.'k"="b.k; end /*k*/ |
|||
return</lang> |
|||
{{Out}} |
|||
<pre> |
<pre> |
||
before a.0=0 |
before callback a.0= 0 |
||
before a.1=1 |
before callback a.1= 1 |
||
before a.2=2 |
before callback a.2= 2 |
||
before a.3=3 |
before callback a.3= 3 |
||
before a.4=4 |
before callback a.4= 4 |
||
before a.5=5 |
before callback a.5= 5 |
||
before a.6=6 |
before callback a.6= 6 |
||
before a.7=7 |
before callback a.7= 7 |
||
before a.8=8 |
before callback a.8= 8 |
||
before a.9=9 |
before callback a.9= 9 |
||
before a.10=10 |
before callback a.10= 10 |
||
before callback a.11= 11 |
|||
before callback a.12= 12 |
|||
··· applying callback to array A ··· |
|||
after a.0=0 |
|||
after a.1=1 |
|||
after a.2=2 |
|||
after a.3=3 |
|||
after a.4=4 |
|||
after a.5=5 |
|||
after a.6=6 |
|||
after a.7=7 |
|||
after a.8=8 |
|||
after a.9=9 |
|||
after a.10=10 |
|||
after |
after callback a.0= 1 |
||
after |
after callback a.1= 1 |
||
after |
after callback a.2= 2 |
||
after |
after callback a.3= 6 |
||
after |
after callback a.4= 24 |
||
after |
after callback a.5= 120 |
||
after |
after callback a.6= 720 |
||
after |
after callback a.7= 5040 |
||
after |
after callback a.8= 40320 |
||
after |
after callback a.9= 362880 |
||
after |
after callback a.10= 3628800 |
||
after callback a.11= 39916800 |
|||
after callback a.12= 479001600 |
|||
</pre> |
</pre> |
||
=={{header|Ring}}== |
|||
<syntaxhighlight lang="ring"> |
|||
for x in [1,2,3,4,5] |
|||
x = x*x |
|||
next |
|||
</syntaxhighlight> |
|||
=={{header|RLaB}}== |
=={{header|RLaB}}== |
||
Line 2,410: | Line 3,168: | ||
Consider an example: |
Consider an example: |
||
<syntaxhighlight lang="rlab"> |
|||
<lang RLaB> |
|||
>> x = rand(2,4) |
>> x = rand(2,4) |
||
0.707213207 0.275298961 0.396757763 0.232312312 |
0.707213207 0.275298961 0.396757763 0.232312312 |
||
Line 2,417: | Line 3,175: | ||
0.649717845 0.271834652 0.386430003 0.230228332 |
0.649717845 0.271834652 0.386430003 0.230228332 |
||
0.213952984 0.205601224 0.536006923 0.617916954 |
0.213952984 0.205601224 0.536006923 0.617916954 |
||
</syntaxhighlight> |
|||
</lang> |
|||
This can be done on entry-by-entry basis, but one has to keep in mind that the |
This can be done on entry-by-entry basis, but one has to keep in mind that the |
||
'for' or 'while' loops are slow in interpreted languages, and RLaB is no exception. |
'for' or 'while' loops are slow in interpreted languages, and RLaB is no exception. |
||
<syntaxhighlight lang="rlab"> |
|||
<lang RLaB> |
|||
x = rand(2,4); |
x = rand(2,4); |
||
y = zeros(2,4); |
y = zeros(2,4); |
||
Line 2,432: | Line 3,190: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Line 2,439: | Line 3,197: | ||
function 'members' which returns a string vector with the names of the elements of the list. |
function 'members' which returns a string vector with the names of the elements of the list. |
||
<syntaxhighlight lang="rlab"> |
|||
<lang RLaB> |
|||
x = <<>>; |
x = <<>>; |
||
for (i in 1:9) |
for (i in 1:9) |
||
Line 2,451: | Line 3,209: | ||
y.[i] = sin( x.[i] ); |
y.[i] = sin( x.[i] ); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header| |
=={{header|RPL}}== |
||
{{works with|Halcyon Calc|4.2.7}} |
|||
<lang ring> |
|||
≪ → array func |
|||
for x in [1,2,3,4,5] |
|||
≪ array 0 CON |
|||
1 array SIZE FOR j |
|||
next |
|||
j array j GET func EVAL PUT |
|||
</lang> |
|||
NEXT |
|||
≫ ≫ |
|||
´MAP’ STO |
|||
[1,2,3,4,5,6,7,8,9] ≪ SQ ≫ MAP |
|||
{{out}} |
|||
<pre> |
|||
1: [ 1 4 9 16 25 36 49 64 81 ] |
|||
</pre> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
You could use a traditional "for i in arr" approach like below: |
You could use a traditional "for i in arr" approach like below: |
||
< |
<syntaxhighlight lang="ruby">for i in [1,2,3,4,5] do |
||
puts i**2 |
puts i**2 |
||
end</ |
end</syntaxhighlight> |
||
Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk) |
Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk) |
||
< |
<syntaxhighlight lang="ruby">[1,2,3,4,5].each{ |i| puts i**2 }</syntaxhighlight> |
||
To create a new array of each value squared |
To create a new array of each value squared |
||
< |
<syntaxhighlight lang="ruby">[1,2,3,4,5].map{ |i| i**2 }</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">fn echo(n: &i32) { |
||
println!("{}", n); |
println!("{}", n); |
||
} |
} |
||
Line 2,482: | Line 3,249: | ||
a = [1, 2, 3, 4, 5]; |
a = [1, 2, 3, 4, 5]; |
||
let _: Vec<_> = a.into_iter().map(echo).collect(); |
let _: Vec<_> = a.into_iter().map(echo).collect(); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Salmon}}== |
=={{header|Salmon}}== |
||
Line 2,488: | Line 3,255: | ||
These examples apply the square function to a list of the numbers from 0 through 9 to produce a new list of their squares, then iterate over the resulting list and print the squares. |
These examples apply the square function to a list of the numbers from 0 through 9 to produce a new list of their squares, then iterate over the resulting list and print the squares. |
||
< |
<syntaxhighlight lang="salmon">function apply(list, ageless to_apply) |
||
(comprehend(x; list) (to_apply(x))); |
(comprehend(x; list) (to_apply(x))); |
||
Line 2,494: | Line 3,261: | ||
iterate(x; apply([0...9], square)) |
iterate(x; apply([0...9], square)) |
||
x!;</ |
x!;</syntaxhighlight> |
||
With short identifiers: |
With short identifiers: |
||
< |
<syntaxhighlight lang="salmon">include "short.salm"; |
||
fun apply(list, ageless to_apply) |
fun apply(list, ageless to_apply) |
||
Line 2,506: | Line 3,273: | ||
iter(x; apply([0...9], square)) |
iter(x; apply([0...9], square)) |
||
x!;</ |
x!;</syntaxhighlight> |
||
With the numbers given as a list of individual elements: |
With the numbers given as a list of individual elements: |
||
< |
<syntaxhighlight lang="salmon">function apply(list, to_apply) |
||
(comprehend(x; list) (to_apply(x))); |
(comprehend(x; list) (to_apply(x))); |
||
Line 2,516: | Line 3,283: | ||
iterate(x; apply([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], square)) |
iterate(x; apply([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], square)) |
||
x!;</ |
x!;</syntaxhighlight> |
||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
< |
<syntaxhighlight lang="sather">class MAIN is |
||
do_something(i:INT):INT is |
do_something(i:INT):INT is |
||
return i * i; |
return i * i; |
||
Line 2,530: | Line 3,297: | ||
loop #OUT + a.elt! + "\n"; end; |
loop #OUT + a.elt! + "\n"; end; |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">val l = List(1,2,3,4) |
||
l.foreach {i => println(i)}</ |
l.foreach {i => println(i)}</syntaxhighlight> |
||
When the argument appears only once -as here, i appears only one in println(i) - it may be shortened to |
When the argument appears only once -as here, i appears only one in println(i) - it may be shortened to |
||
<lang |
<syntaxhighlight lang="scala">l.foreach(println(_))</syntaxhighlight> |
||
Same for an array |
Same for an array |
||
< |
<syntaxhighlight lang="scala">val a = Array(1,2,3,4) |
||
a.foreach {i => println(i)} |
a.foreach {i => println(i)} |
||
a.foreach(println(_)) '' // same as previous line''</ |
a.foreach(println(_)) '' // same as previous line''</syntaxhighlight> |
||
Or for an externally defined function: |
Or for an externally defined function: |
||
< |
<syntaxhighlight lang="scala">def doSomething(in: int) = {println("Doing something with "+in)} |
||
l.foreach(doSomething)</ |
l.foreach(doSomething)</syntaxhighlight> |
||
There is also a ''for'' syntax, which is internally rewritten to call foreach. A foreach method must be defined on ''a'' |
There is also a ''for'' syntax, which is internally rewritten to call foreach. A foreach method must be defined on ''a'' |
||
< |
<syntaxhighlight lang="scala">for(val i <- a) println(i)</syntaxhighlight> |
||
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) |
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) |
||
< |
<syntaxhighlight lang="scala">val squares = l.map{i => i * i} ''//squares is'' List(1,4,9,16)</syntaxhighlight> |
||
Or the equivalent ''for'' syntax, with the additional keyword ''yield'', map is called instead of foreach |
Or the equivalent ''for'' syntax, with the additional keyword ''yield'', map is called instead of foreach |
||
< |
<syntaxhighlight lang="scala">val squares = for (val i <- l) yield i * i</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">(define (square n) (* n n)) |
||
(define x #(1 2 3 4 5)) |
(define x #(1 2 3 4 5)) |
||
(map square (vector->list x))</ |
(map square (vector->list x))</syntaxhighlight> |
||
A single-line variation |
A single-line variation |
||
< |
<syntaxhighlight lang="scheme">(map (lambda (n) (* n n)) '(1 2 3 4 5))</syntaxhighlight> |
||
For completeness, the <tt>map</tt> function (which is R5RS standard) can be coded as follows: |
For completeness, the <tt>map</tt> function (which is R5RS standard) can be coded as follows: |
||
< |
<syntaxhighlight lang="scheme">(define (map f L) |
||
(if (null? L) |
(if (null? L) |
||
L |
L |
||
(cons (f (car L)) (map f (cdr L)))))</ |
(cons (f (car L)) (map f (cdr L)))))</syntaxhighlight> |
||
=={{header|SenseTalk}}== |
|||
<syntaxhighlight lang="sensetalk"> |
|||
put each item in [1,2,3,5,9,14,24] squared |
|||
put myFunc of each for each item of [1,2,3,5,9,14,24] |
|||
to handle myFunc of num |
|||
return 2*num + 1 |
|||
end myFunc</syntaxhighlight> |
|||
Output: |
|||
<syntaxhighlight lang="sensetalk">(1,4,9,25,81,196,576) |
|||
(3,5,7,11,19,29,49)</syntaxhighlight> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
Defining a callback function: |
|||
< |
<syntaxhighlight lang="ruby">func callback(i) { say i**2 }</syntaxhighlight> |
||
The function will get called for each element: |
|||
< |
<syntaxhighlight lang="ruby">[1,2,3,4].each(callback)</syntaxhighlight> |
||
Same as above, but with the function inlined: |
Same as above, but with the function inlined: |
||
< |
<syntaxhighlight lang="ruby">[1,2,3,4].each{|i| say i**2 }</syntaxhighlight> |
||
For creating a new array, we can use the Array.map method: |
|||
< |
<syntaxhighlight lang="ruby">[1,2,3,4,5].map{|i| i**2 }</syntaxhighlight> |
||
=={{header|Simula}}== |
|||
<syntaxhighlight lang="simula">BEGIN |
|||
! APPLIES A CALLBACK FUNCTION TO AN ARRAY ; |
|||
PROCEDURE APPLY(ARR, FUN); |
|||
REAL ARRAY ARR; |
|||
PROCEDURE FUN IS REAL PROCEDURE FUN(X); REAL X;; |
|||
BEGIN |
|||
INTEGER I; |
|||
FOR I := LOWERBOUND(ARR, 1) STEP 1 UNTIL UPPERBOUND(ARR, 1) DO |
|||
ARR(I) := FUN(ARR(I)); |
|||
END APPLY; |
|||
! CALLBACK ; |
|||
REAL PROCEDURE SQUARE(X); REAL X; SQUARE := X * X; |
|||
REAL ARRAY A(1:5); |
|||
INTEGER I; |
|||
FOR I := 1 STEP 1 UNTIL 5 DO A(I) := I; |
|||
APPLY(A, SQUARE); |
|||
FOR I := 1 STEP 1 UNTIL 5 DO OUTFIX(A(I), 2, 8); OUTIMAGE; |
|||
END.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1.00 4.00 9.00 16.00 25.00 |
|||
</pre> |
|||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang="slate">#( 1 2 3 4 5 ) collect: [| :n | n * n].</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang="smalltalk">#( 1 2.0 'three') do: [:each | each displayNl].</syntaxhighlight> |
||
You can tell symbols how to react to the <tt>value:</tt> message, and then write ²: |
|||
<syntaxhighlight lang="smalltalk">#( 1 2.0 'three') do: #displayNl.</syntaxhighlight> |
|||
2) actually most dialects already have it, and it is trivial to add, if it does not. |
|||
There is a huge number of additional enumeration messages implemented in Collection, from which Array inherits. Eg.: |
|||
<syntaxhighlight lang="smalltalk">#( 1 2 3 4 5 ) collect: [:n | n * n].</syntaxhighlight> |
|||
=={{header|Sparkling}}== |
=={{header|Sparkling}}== |
||
The <tt>foreach</tt> function calls the supplied callback on each element of the (possibly associative) array, passing it each key and the corresponding value: |
The <tt>foreach</tt> function calls the supplied callback on each element of the (possibly associative) array, passing it each key and the corresponding value: |
||
< |
<syntaxhighlight lang="sparkling">let numbers = { 1, 2, 3, 4 }; |
||
foreach(numbers, function(idx, num) { |
foreach(numbers, function(idx, num) { |
||
print(num); |
print(num); |
||
});</ |
});</syntaxhighlight> |
||
The <tt>map</tt> function applies the transform to each key-value pair and constructs a new array, of which the keys are the keys of the original array, and the corresponding values are the return values of each call to the transform function: |
The <tt>map</tt> function applies the transform to each key-value pair and constructs a new array, of which the keys are the keys of the original array, and the corresponding values are the return values of each call to the transform function: |
||
< |
<syntaxhighlight lang="sparkling">let dict = { "foo": 42, "bar": 13, "baz": 37 }; |
||
let doubled = map(dict, function(key, val) { |
let doubled = map(dict, function(key, val) { |
||
return val * 2; |
return val * 2; |
||
});</ |
});</syntaxhighlight> |
||
=={{header|SQL PL}}== |
|||
{{works with|Db2 LUW}} version 9.7 or higher. |
|||
With SQL PL: |
|||
<syntaxhighlight lang="sql pl"> |
|||
--#SET TERMINATOR @ |
|||
SET SERVEROUTPUT ON @ |
|||
BEGIN |
|||
DECLARE TYPE NUMBERS AS SMALLINT ARRAY[5]; |
|||
DECLARE NUMBERS NUMBERS; |
|||
DECLARE I SMALLINT; |
|||
SET I = 1; |
|||
WHILE (I <= 5) DO |
|||
SET NUMBERS[I] = I; |
|||
SET I = I + 1; |
|||
END WHILE; |
|||
BEGIN |
|||
DECLARE PROCEDURE PRINT_SQUARE ( |
|||
IN VALUE SMALLINT |
|||
) |
|||
BEGIN |
|||
CALL DBMS_OUTPUT.PUT(VALUE * VALUE || ' '); |
|||
END; |
|||
SET I = 1; |
|||
WHILE (I <= 5) DO |
|||
CALL PRINT_SQUARE(NUMBERS[I]); |
|||
SET I = I + 1; |
|||
END WHILE; |
|||
CALL DBMS_OUTPUT.PUT_LINE(''); |
|||
END; |
|||
END @ |
|||
</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
db2 -td@ |
|||
db2 => BEGIN |
|||
... |
|||
db2 (cont.) => END @ |
|||
DB20000I The SQL command completed successfully. |
|||
1 4 9 16 25 |
|||
</pre> |
|||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
<syntaxhighlight lang="standard ml"> |
|||
<lang Standard ML> |
|||
map f l |
map f l |
||
</syntaxhighlight> |
|||
</lang> |
|||
i.e. |
i.e. |
||
<syntaxhighlight lang="standard ml"> |
|||
<lang Standard ML> |
|||
map (fn x=>x+1) [1,2,3];; (* [2,3,4] *) |
map (fn x=>x+1) [1,2,3];; (* [2,3,4] *) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Stata}}== |
|||
There is no 'map' function in Mata, but it's easy to implement. Notice that you can only pass functions that are written in Mata, no builtin ones. For instance, the trigonometric functions (cos, sin) or the exponential are builtin. To pass a builtin function to another function, one needs to write a wrapper in Mata. See also Stata help about '''[https://www.stata.com/help.cgi?m2_pointers pointers]''' and '''[https://www.stata.com/help.cgi?m2_ftof passing functions to functions]'''. There are two versions of the function: one to return a numeric array, another to return a string array. |
|||
<syntaxhighlight lang="stata">function map(f,a) { |
|||
nr = rows(a) |
|||
nc = cols(a) |
|||
b = J(nr,nc,.) |
|||
for (i=1;i<=nr;i++) { |
|||
for (j=1;j<=nc;j++) b[i,j] = (*f)(a[i,j]) |
|||
} |
|||
return(b) |
|||
} |
|||
function maps(f,a) { |
|||
nr = rows(a) |
|||
nc = cols(a) |
|||
b = J(nr,nc,"") |
|||
for (i=1;i<=nr;i++) { |
|||
for (j=1;j<=nc;j++) b[i,j] = (*f)(a[i,j]) |
|||
} |
|||
return(b) |
|||
} |
|||
function square(x) { |
|||
return(x*x) |
|||
}</syntaxhighlight> |
|||
'''Output''' |
|||
<pre>: map(&square(),(1,2,3\4,5,6)) |
|||
1 2 3 |
|||
+----------------+ |
|||
1 | 1 4 9 | |
|||
2 | 16 25 36 | |
|||
+----------------+</pre> |
|||
=={{header|SuperCollider}}== |
=={{header|SuperCollider}}== |
||
Actually, there is a builtin <tt>squared</tt> operator: |
Actually, there is a builtin <tt>squared</tt> operator: |
||
< |
<syntaxhighlight lang="supercollider">[1, 2, 3].squared // returns [1, 4, 9]</syntaxhighlight> |
||
Anything that is a <tt>Collection</tt> can be used with <tt>collect</tt>: |
Anything that is a <tt>Collection</tt> can be used with <tt>collect</tt>: |
||
< |
<syntaxhighlight lang="supercollider">[1, 2, 3].collect { |x| x * x }</syntaxhighlight> |
||
[[List Comprehension#SuperCollider|List comprehension]] combined with a higher-order function can also be used: |
[[List Comprehension#SuperCollider|List comprehension]] combined with a higher-order function can also be used: |
||
< |
<syntaxhighlight lang="supercollider">var square = { |x| x * x }; |
||
var map = { |fn, xs| |
|||
arg x; |
|||
x*x; |
|||
}; |
|||
var map = { |
|||
arg fn, xs; |
|||
all {: fn.value(x), x <- xs }; |
all {: fn.value(x), x <- xs }; |
||
}; |
}; |
||
map.value(square,[1,2,3]);</ |
map.value(square, [1, 2, 3]);</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">func square(n: Int) -> Int { |
||
return n * n |
return n * n |
||
} |
} |
||
Line 2,640: | Line 3,533: | ||
let squares1b = numbers.map { $0 * $0 } // map method on array with anonymous function and unnamed parameters |
let squares1b = numbers.map { $0 * $0 } // map method on array with anonymous function and unnamed parameters |
||
let isquares1 = numbers.lazy.map(square) // lazy sequence</ |
let isquares1 = numbers.lazy.map(square) // lazy sequence</syntaxhighlight> |
||
=={{header|Tailspin}}== |
|||
<syntaxhighlight lang="tailspin"> |
|||
def numbers: [1,3,7,10]; |
|||
templates cube |
|||
$ * $ * $ ! |
|||
end cube |
|||
// Using inline array templates (which also allows access to index by $i) |
|||
$numbers -> \[i]($ * $i !\) -> !OUT::write |
|||
$numbers -> \[i]($ * $ !\) -> !OUT::write |
|||
$numbers -> \[i]($ -> cube !\) -> !OUT::write |
|||
// Using array literal and deconstructor |
|||
[ $numbers... -> $ * $ ] -> !OUT::write |
|||
[ $numbers... -> cube ] -> !OUT::write |
|||
</syntaxhighlight> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
If I wanted to call "<tt>myfunc</tt>" on each element of <tt>dat</tt> and <tt>dat</tt> were a list: |
If I wanted to call "<tt>myfunc</tt>" on each element of <tt>dat</tt> and <tt>dat</tt> were a list: |
||
< |
<syntaxhighlight lang="tcl">foreach var $dat { |
||
myfunc $var |
myfunc $var |
||
}</ |
}</syntaxhighlight> |
||
This does not retain any of the values returned by <tt>myfunc</tt>. |
This does not retain any of the values returned by <tt>myfunc</tt>. |
||
if <tt>dat</tt> were an (associative) array, however: |
if <tt>dat</tt> were an (associative) array, however: |
||
< |
<syntaxhighlight lang="tcl">foreach name [array names dat] { |
||
myfunc $dat($name) |
myfunc $dat($name) |
||
}</ |
}</syntaxhighlight> |
||
More functional, with a simple <code>map</code> function: |
More functional, with a simple <code>map</code> function: |
||
< |
<syntaxhighlight lang="tcl">proc map {f list} { |
||
set res {} |
set res {} |
||
foreach e $list {lappend res [$f $e]} |
foreach e $list {lappend res [$f $e]} |
||
Line 2,664: | Line 3,575: | ||
% map square {1 2 3 4 5} |
% map square {1 2 3 4 5} |
||
1 4 9 16 25</ |
1 4 9 16 25</syntaxhighlight> |
||
=={{header|TI-89 BASIC}}== |
=={{header|TI-89 BASIC}}== |
||
< |
<syntaxhighlight lang="ti89b">© For no return value |
||
Define foreach(fe_cname,fe_list) = Prgm |
Define foreach(fe_cname,fe_list) = Prgm |
||
Local fe_i |
Local fe_i |
||
Line 2,684: | Line 3,595: | ||
foreach("callback", {1,2,3,4,5}) |
foreach("callback", {1,2,3,4,5}) |
||
Disp map("√", {1,2,3,4,5})</ |
Disp map("√", {1,2,3,4,5})</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 2,698: | Line 3,609: | ||
JavaScript alike: |
JavaScript alike: |
||
< |
<syntaxhighlight lang="javascript">var a = [1, 2, 3, 4, 5]; |
||
a.map(function(v) { return v * v; }) |
a.map(function(v) { return v * v; }) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Using short form of lambda notation: |
Using short form of lambda notation: |
||
< |
<syntaxhighlight lang="javascript">var a = [1, 2, 3, 4, 5]; |
||
a.map( :v: v*v ); |
a.map( :v: v*v ); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Toka}}== |
=={{header|Toka}}== |
||
< |
<syntaxhighlight lang="toka">( array count function -- ) |
||
{ |
{ |
||
value| array fn | |
value| array fn | |
||
Line 2,725: | Line 3,636: | ||
( Add 1 to each item in the array ) |
( Add 1 to each item in the array ) |
||
a 5 [ 1 + ] map-array</ |
a 5 [ 1 + ] map-array</syntaxhighlight> |
||
=={{header|TorqueScript}}== |
=={{header|TorqueScript}}== |
||
Line 2,733: | Line 3,644: | ||
Callbacks: |
Callbacks: |
||
<syntaxhighlight lang="torquescript"> |
|||
<lang TorqueScript> |
|||
function map(%array,%arrayCount,%function) |
function map(%array,%arrayCount,%function) |
||
{ |
{ |
||
Line 2,742: | Line 3,653: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Now to set up an array: |
Now to set up an array: |
||
<syntaxhighlight lang="torquescript"> |
|||
<lang TorqueScript> |
|||
$array[0] = "Hello."; |
$array[0] = "Hello."; |
||
$array[1] = "Hi."; |
$array[1] = "Hi."; |
||
$array[2] = "How are you?"; |
$array[2] = "How are you?"; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Now to call the function correctly: |
Now to call the function correctly: |
||
<syntaxhighlight lang="torquescript"> |
|||
<lang TorqueScript> |
|||
map("$array",3,"echo"); |
map("$array",3,"echo"); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Which should result in: |
Which should result in: |
||
<syntaxhighlight lang="torquescript"> |
|||
<lang TorqueScript> |
|||
=> Hello. |
=> Hello. |
||
Line 2,766: | Line 3,677: | ||
=> How are you? |
=> How are you? |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|TXR}}== |
=={{header|TXR}}== |
||
Line 2,772: | Line 3,683: | ||
Print 1 through 10 out of a vector, using <code>prinl</code> the callback, right from the system shell command prompt: |
Print 1 through 10 out of a vector, using <code>prinl</code> the callback, right from the system shell command prompt: |
||
< |
<syntaxhighlight lang="bash">$ txr -e '[mapdo prinl #(1 2 3 4 5 6 7 8 9 10)]' |
||
1 |
1 |
||
2 |
2 |
||
Line 2,782: | Line 3,693: | ||
8 |
8 |
||
9 |
9 |
||
10</ |
10</syntaxhighlight> |
||
<code>mapdo</code> is like <code>mapcar</code> but doesn't accumulate a list, suitable for imperative programming situations when the function is invoked to perform a side effect. |
<code>mapdo</code> is like <code>mapcar</code> but doesn't accumulate a list, suitable for imperative programming situations when the function is invoked to perform a side effect. |
||
Line 2,790: | Line 3,701: | ||
=={{header|uBasic/4tH}}== |
=={{header|uBasic/4tH}}== |
||
We cannot transfer the array address, since uBasic/4tH has only got one, but we can transfer the function pointer and size. |
We cannot transfer the array address, since uBasic/4tH has only got one, but we can transfer the function pointer and size. |
||
<lang>S = 5 ' Size of the array |
<syntaxhighlight lang="text">S = 5 ' Size of the array |
||
For x = 0 To S - 1 ' Initialize array |
For x = 0 To S - 1 ' Initialize array |
||
Line 2,851: | Line 3,762: | ||
Push 10000+((Pop()*-(Pop()/2))/10000) |
Push 10000+((Pop()*-(Pop()/2))/10000) |
||
If a@ Then Push -Pop() ' Result is directly transferred |
If a@ Then Push -Pop() ' Result is directly transferred |
||
Return ' through the stack</ |
Return ' through the stack</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>SQRT(1) = 1.0000 |
<pre>SQRT(1) = 1.0000 |
||
Line 2,866: | Line 3,777: | ||
0 OK, 0:514</pre> |
0 OK, 0:514</pre> |
||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|Bourne Shell}} |
{{works with|Bourne Shell}} |
||
< |
<syntaxhighlight lang="bash">map() { |
||
map_command=$1 |
map_command=$1 |
||
shift |
shift |
||
Line 2,874: | Line 3,786: | ||
} |
} |
||
list=1:2:3 |
list=1:2:3 |
||
(IFS=:; map echo $list)</ |
(IFS=:; map echo $list)</syntaxhighlight> |
||
{{works with|ksh93}} |
{{works with|ksh93}} |
||
{{works with|pdksh}} |
{{works with|pdksh}} |
||
{{works with|zsh}} |
{{works with|zsh}} |
||
< |
<syntaxhighlight lang="bash">map() { |
||
typeset command=$1 |
typeset command=$1 |
||
shift |
shift |
||
Line 2,885: | Line 3,797: | ||
} |
} |
||
set -A ary 1 2 3 |
set -A ary 1 2 3 |
||
map print "${ary[@]}"</ |
map print "${ary[@]}"</syntaxhighlight> |
||
{{works with|zsh}} |
{{works with|zsh}} |
||
< |
<syntaxhighlight lang="bash">map(){for i ($*[2,-1]) $1 $i} |
||
a=(1 2 3) |
a=(1 2 3) |
||
map print $a</ |
map print $a</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
The * is a built-in map operator. |
The * is a built-in map operator. |
||
This example shows a map of the successor function over a list of natural numbers. |
This example shows a map of the successor function over a list of natural numbers. |
||
< |
<syntaxhighlight lang="ursala">#import nat |
||
#cast %nL |
#cast %nL |
||
demo = successor* <325,32,67,1,3,7,315></ |
demo = successor* <325,32,67,1,3,7,315></syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 2,907: | Line 3,819: | ||
=={{header|V}}== |
=={{header|V}}== |
||
apply squaring (dup *) to each member of collection |
apply squaring (dup *) to each member of collection |
||
< |
<syntaxhighlight lang="v">[1 2 3 4] [dup *] map</syntaxhighlight> |
||
=={{header|VBA}}== |
|||
<syntaxhighlight lang="vb"> |
|||
Option Explicit |
|||
Sub Main() |
|||
Dim arr, i |
|||
'init |
|||
arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) |
|||
'Loop and apply a function (Fibonacci) to each element |
|||
For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next |
|||
'return |
|||
Debug.Print Join(arr, ", ") |
|||
End Sub |
|||
Private Function Fibonacci(N) As Variant |
|||
If N <= 1 Then |
|||
Fibonacci = N |
|||
Else |
|||
Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2) |
|||
End If |
|||
End Function</syntaxhighlight> |
|||
{{out}} |
|||
<pre>0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55</pre> |
|||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
Line 2,914: | Line 3,852: | ||
=====Implementation===== |
=====Implementation===== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
class callback |
class callback |
||
dim sRule |
dim sRule |
||
Line 2,931: | Line 3,869: | ||
end function |
end function |
||
end class |
end class |
||
</syntaxhighlight> |
|||
</lang> |
|||
=====Invocation===== |
=====Invocation===== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
dim a1 |
dim a1 |
||
dim cb |
dim cb |
||
Line 2,948: | Line 3,886: | ||
cb.applyto a1 |
cb.applyto a1 |
||
wscript.echo join( a1, ", " ) |
wscript.echo join( a1, ", " ) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 2,961: | Line 3,899: | ||
The result of evaluating the string will be the new value. |
The result of evaluating the string will be the new value. |
||
The list/dictionary is modified in place. |
The list/dictionary is modified in place. |
||
< |
<syntaxhighlight lang="vim">echo map([10, 20, 30], 'v:val * v:val') |
||
echo map([10, 20, 30], '"Element " . v:key . " = " . v:val') |
echo map([10, 20, 30], '"Element " . v:key . " = " . v:val') |
||
echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:val)') |
echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:val)') |
||
echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:key)')</ |
echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:key)')</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 2,971: | Line 3,909: | ||
{'a': 'FOO', 'b': 'BAR', 'c': 'BAZ'} |
{'a': 'FOO', 'b': 'BAR', 'c': 'BAZ'} |
||
{'a': 'A', 'b': 'B', 'c': 'C'}</pre> |
{'a': 'A', 'b': 'B', 'c': 'C'}</pre> |
||
=={{header|Visual Basic .NET}}== |
|||
'''Compiler:''' >= Visual Studio 2008 |
|||
The .NET framework has got us covered. |
|||
System.Array.ForEach(T(), Action(Of T)) maps a non-value-returning callback, |
|||
System.Linq.Enumerable.Select(Of TSource,TResult)(IEnumerable(Of TSource), Func(Of TSource, TResult)) provides a way to lazily map a function, resulting in an IEnumerable(Of T), |
|||
and System.Linq.Enumerable.ToArray(Of TSource)(IEnumerable(Of TSource)) eagerly converts the enumerable to an array. |
|||
<syntaxhighlight lang="vbnet">Module Program |
|||
Function OneMoreThan(i As Integer) As Integer |
|||
Return i + 1 |
|||
End Function |
|||
Sub Main() |
|||
Dim source As Integer() = {1, 2, 3} |
|||
' Create a delegate from an existing method. |
|||
Dim resultEnumerable1 = source.Select(AddressOf OneMoreThan) |
|||
' The above is just syntax sugar for this; extension methods can be called as if they were instance methods of the first parameter. |
|||
resultEnumerable1 = Enumerable.Select(source, AddressOf OneMoreThan) |
|||
' Or use an anonymous delegate. |
|||
Dim resultEnumerable2 = source.Select(Function(i) i + 1) |
|||
' The sequences are the same. |
|||
Console.WriteLine(Enumerable.SequenceEqual(resultEnumerable1, resultEnumerable2)) |
|||
Dim resultArr As Integer() = resultEnumerable1.ToArray() |
|||
Array.ForEach(resultArr, AddressOf Console.WriteLine) |
|||
End Sub |
|||
End Module</syntaxhighlight> |
|||
{{out}} |
|||
<pre>True |
|||
2 |
|||
3 |
|||
4</pre> |
|||
=={{header|Vorpal}}== |
=={{header|Vorpal}}== |
||
Given and array, A, and a function, F, mapping F over the elements of A is simple: |
Given and array, A, and a function, F, mapping F over the elements of A is simple: |
||
<lang |
<syntaxhighlight lang="vorpal">A.map(F)</syntaxhighlight> |
||
If F takes 2 arguments, x and , then simply pass them to map. |
If F takes 2 arguments, x and , then simply pass them to map. |
||
They will be passed to F when as it is applied to each element of A. |
They will be passed to F when as it is applied to each element of A. |
||
< |
<syntaxhighlight lang="vorpal">A.map(F, x, y)</syntaxhighlight> |
||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
< |
<syntaxhighlight lang="wart">map prn '(1 2 3 4 5)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 2,989: | Line 3,970: | ||
5</pre> |
5</pre> |
||
=={{header|WDTE}}== |
|||
<syntaxhighlight lang="wdte">let a => import 'arrays'; |
|||
let s => import 'stream'; |
|||
let example => [3; 5; 2]; |
|||
let double => a.stream example |
|||
-> s.map (* 2) |
|||
-> s.collect |
|||
;</syntaxhighlight> |
|||
In WDTE, mapping can be accomplished using the <code>stream</code> module. Streams are essentially lazy iterators. The <code>arrays</code> module provides a function for creating a stream from an array, and then the <code>stream</code> module's functions can be used to perform a map operation. <code>collect</code> runs the iteration, collecting the elements yielded in a new array. |
|||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="wren">var arr = [1, 2, 3, 4, 5] |
||
arr = arr.map { |x| x * 2 }.toList |
arr = arr.map { |x| x * 2 }.toList |
||
arr = arr.map(Fn.new {|x| x / 2}).toList |
arr = arr.map(Fn.new { |x| x / 2 }).toList |
||
arr.each {|x| System.print(x) } |
arr.each { |x| System.print(x) }</syntaxhighlight> |
||
</lang> |
|||
{{out}} |
|||
<pre> |
|||
1 |
|||
2 |
|||
3 |
|||
4 |
|||
5 |
|||
</pre> |
|||
=={{header|XBS}}== |
|||
<syntaxhighlight lang="xbs">func map(arr:array,callback:function){ |
|||
set newArr:array = []; |
|||
foreach(k,v as arr){ |
|||
newArr[k]=callback(v,k,arr); |
|||
} |
|||
send newArr; |
|||
} |
|||
set arr:array = [1,2,3,4,5]; |
|||
set result:array = map(arr,func(v){ |
|||
send v*2; |
|||
}); |
|||
log(arr.join(", ")); |
|||
log(result.join(", "));</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5 |
|||
2, 4, 6, 8, 10 |
|||
</pre> |
|||
=={{header|Yabasic}}== |
|||
<syntaxhighlight lang="yabasic">sub map(f$, t()) |
|||
local i |
|||
for i = 1 to arraysize(t(), 1) |
|||
t(i) = execute(f$, t(i)) |
|||
next i |
|||
end sub |
|||
sub add1(x) |
|||
return x + 1 |
|||
end sub |
|||
sub square(x) |
|||
return x * x |
|||
end sub |
|||
dim t(10) |
|||
for i = 1 to 10 |
|||
t(i) = i |
|||
print t(i), "\t"; |
|||
next i |
|||
print |
|||
//map("add1", t()) |
|||
map("square", t()) |
|||
for i = 1 to 10 |
|||
print t(i), "\t"; |
|||
next i |
|||
print</syntaxhighlight> |
|||
=={{header|Yacas}}== |
=={{header|Yacas}}== |
||
< |
<syntaxhighlight lang="yacas">Sin /@ {1, 2, 3, 4} |
||
MapSingle(Sin, {1,2,3,4}) |
MapSingle(Sin, {1,2,3,4}) |
||
MapSingle({{x}, x^2}, {1,2,3,4}) |
MapSingle({{x}, x^2}, {1,2,3,4}) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Z80 Assembly}}== |
|||
<syntaxhighlight lang="z80">Array: |
|||
byte &01,&02,&03,&04,&05 |
|||
Array_End: |
|||
foo: |
|||
ld hl,Array |
|||
ld b,Array_End-Array ;ld b,5 |
|||
bar: |
|||
inc (hl) |
|||
inc (hl) |
|||
inc (hl) |
|||
inc hl ;next entry in array |
|||
djnz bar</syntaxhighlight> |
|||
{{out}} |
|||
The program above doesn't show the new values but here they are: |
|||
<pre> |
|||
&04,&05,&06,&07,&08 |
|||
</pre> |
|||
=={{header|Zig}}== |
|||
<syntaxhighlight lang="zig">pub fn main() !void { |
|||
var array = [_]i32{1, 2, 3}; |
|||
apply(@TypeOf(array[0]), array[0..], func); |
|||
} |
|||
fn apply(comptime T: type, a: []T, f: fn(T) void) void { |
|||
for (a) |item| { |
|||
f(item); |
|||
} |
|||
} |
|||
fn func(a: i32) void { |
|||
const std = @import("std"); |
|||
std.debug.print("{d}\n", .{a-1}); |
|||
}</syntaxhighlight> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">L(1,2,3,4,5).apply('+(5))</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
L(6,7,8,9,10) |
L(6,7,8,9,10) |
||
</pre> |
|||
=={{header|zonnon}}== |
|||
<syntaxhighlight lang="zonnon"> |
|||
module Main; |
|||
type |
|||
Callback = procedure (integer): integer; |
|||
Vector = array {math} * of integer; |
|||
procedure Power(i:integer):integer; |
|||
begin |
|||
return i*i; |
|||
end Power; |
|||
procedure Map(x: Vector;p: Callback): Vector; |
|||
var |
|||
i: integer; |
|||
r: Vector; |
|||
begin |
|||
r := new Vector(len(x)); |
|||
for i := 0 to len(x) - 1 do |
|||
r[i] := p(i); |
|||
end; |
|||
return r |
|||
end Map; |
|||
procedure Write(x: Vector); |
|||
var |
|||
i: integer; |
|||
begin |
|||
for i := 0 to len(x) - 1 do |
|||
write(x[i]:4) |
|||
end; |
|||
writeln |
|||
end Write; |
|||
var |
|||
x,y: Vector; |
|||
begin |
|||
x := [1,2,3,4,5]; |
|||
Write(Map(x,Power)) |
|||
end Main. |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> |
|||
0 1 4 9 16 |
|||
</pre> |
</pre> |
||
=={{header|ZX Spectrum Basic}}== |
=={{header|ZX Spectrum Basic}}== |
||
< |
<syntaxhighlight lang="zxbasic">10 LET a$="x+x" |
||
20 LET b$="x*x" |
20 LET b$="x*x" |
||
30 LET c$="x+x^2" |
30 LET c$="x+x^2" |
||
Line 3,023: | Line 4,165: | ||
190 STOP |
190 STOP |
||
200 DATA 2,5,6,10,100 |
200 DATA 2,5,6,10,100 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{omit from|gnuplot}} |
{{omit from|gnuplot}} |
Latest revision as of 11:52, 13 June 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Take a combined set of elements and apply a function to each element.
11l
V array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
V arrsq = array.map(i -> i * i)
print(arrsq)
- Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
6502 Assembly
For this example, assume both the source array and the destination have a size of 86 elements (memory offsets base+0x00 to base+0x55.) This was implemented in easy6502.
define SRC_LO $00
define SRC_HI $01
define DEST_LO $02
define DEST_HI $03
define temp $04 ;temp storage used by foo
;some prep work since easy6502 doesn't allow you to define arbitrary bytes before runtime.
SET_TABLE:
TXA
STA $1000,X
INX
BNE SET_TABLE
;stores the identity table at memory address $1000-$10FF
CLEAR_TABLE:
LDA #0
STA $1200,X
INX
BNE CLEAR_TABLE
;fills the range $1200-$12FF with zeroes.
LDA #$10
STA SRC_HI
LDA #$00
STA SRC_LO
;store memory address $1000 in zero page
LDA #$12
STA DEST_HI
LDA #$00
STA DEST_LO
;store memory address $1200 in zero page
loop:
LDA (SRC_LO),y ;load accumulator from memory address $1000+y
JSR foo ;multiplies accumulator by 3.
STA (DEST_LO),y ;store accumulator in memory address $1200+y
INY
CPY #$56 ;alternatively you can store a size variable and check that here instead.
BCC loop
BRK
foo:
STA temp
ASL ;double accumulator
CLC
ADC temp ;2a + a = 3a
RTS
- Output:
1200: 00 03 06 09 0c 0f 12 15 18 1b 1e 21 24 27 2a 2d 1210: 30 33 36 39 3c 3f 42 45 48 4b 4e 51 54 57 5a 5d 1220: 60 63 66 69 6c 6f 72 75 78 7b 7e 81 84 87 8a 8d 1230: 90 93 96 99 9c 9f a2 a5 a8 ab ae b1 b4 b7 ba bd 1240: c0 c3 c6 c9 cc cf d2 d5 d8 db de e1 e4 e7 ea ed 1250: f0 f3 f6 f9 fc ff
68000 Assembly
The following assumes all code/data is stored/executed in RAM and is therefore mutable.
LEA MyArray,A0
MOVE.W #(MyArray_End-MyArray)-1,D7 ;Len(MyArray)-1
MOVEQ #0,D0 ;sanitize D0-D2 to ensure nothing from any previous work will affect our math.
MOVEQ #0,D1
MOVEQ #0,D2
loop:
MOVE.B (A0),D0
MOVE.B D0,D1
MOVE.B D0,D2
MULU D1,D2
MOVE.B D2,(A0)+
dbra d7,loop
jmp * ;halt the CPU
MyArray:
DC.B 1,2,3,4,5,6,7,8,9,10
MyArray_End:
8th
The builtin word "a:map" does this:
[ 1 , 2, 3 ]
' n:sqr
a:map
That results in the array [1,4,9]
ACL2
ACL2 does not have first-class functions; this is close, however:
(defun apply-to-each (xs)
(if (endp xs)
nil
(cons (fn-to-apply (first xs))
(sq-each (rest xs)))))
(defun fn-to-apply (x)
(* x x))
ActionScript
package
{
public class ArrayCallback
{
public function main():void
{
var nums:Array = new Array(1, 2, 3);
nums.map(function(n:Number, index:int, arr:Array):void { trace(n * n * n); });
// You can also pass a function reference
nums.map(cube);
}
private function cube(n:Number, index:int, arr:Array):void
{
trace(n * n * n);
}
}
}
Ada
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;
Aime
void
map(list l, void (*fp)(object))
{
l.ucall(fp, 0);
}
void
out(object o)
{
o_(o, "\n");
}
integer
main(void)
{
list(0, 1, 2, 3).map(out);
return 0;
}
ALGOL 68
PROC call back proc = (INT location, INT value)VOID:
(
printf(($"array["g"] = "gl$, location, value))
);
PROC map = (REF[]INT array, PROC (INT,INT)VOID call back)VOID:
(
FOR i FROM LWB array TO UPB array DO
call back(i, array[i])
OD
);
main:
(
[4]INT array := ( 1, 4, 9, 16 );
map(array, call back proc)
)
- Output:
array[ +1] = +1 array[ +2] = +4 array[ +3] = +9 array[ +4] = +16
ALGOL W
begin
procedure printSquare ( integer value x ) ; writeon( i_w := 1, s_w := 0, " ", x * x );
% applys f to each element of a from lb to ub (inclusive) %
procedure applyI ( procedure f; integer array a ( * ); integer value lb, ub ) ;
for i := lb until ub do f( a( i ) );
% test applyI %
begin
integer array a ( 1 :: 3 );
a( 1 ) := 1; a( 2 ) := 2; a( 3 ) := 3;
applyI( printSquare, a, 1, 3 )
end
end.
APL
By default functions in APL work on arrays as it is an array oriented language. Some examples:
- 1 2 3
¯1 ¯2 ¯3
2 * 1 2 3 4
2 4 8 16
2 × ⍳4
2 4 6 8
3 * 3 3 ⍴ ⍳9
3 9 27
81 243 729
2187 6561 19683
AppleScript
on callback for arg
-- Returns a string like "arc has 3 letters"
arg & " has " & (count arg) & " letters"
end callback
set alist to {"arc", "be", "circle"}
repeat with aref in alist
-- Passes a reference to some item in alist
-- to callback, then speaks the return value.
say (callback for aref)
end repeat
If the callback would set arg's contents to "something"
, then alist
would be mutated.
For a more general implementation of map(function, list), foldl(function, startValue, list), and filter(predicate, list), we could write:
on run
set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
{map(square, xs), ¬
filter(even, xs), ¬
foldl(add, 0, xs)}
--> {{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}, {2, 4, 6, 8, 10}, 55}
end run
-- square :: Num -> Num -> Num
on square(x)
x * x
end square
-- add :: Num -> Num -> Num
on add(a, b)
a + b
end add
-- even :: Int -> Bool
on even(x)
0 = x mod 2
end even
-- GENERIC HIGHER ORDER FUNCTIONS
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set v to item i of xs
if |λ|(v, i, xs) then set end of lst to v
end repeat
return lst
end tell
end filter
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
- Output:
{{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}, {2, 4, 6, 8, 10}, 55}
Arturo
arr: [1 2 3 4 5]
print map arr => [2*&]
- Output:
2 4 6 8 10
AutoHotkey
map("callback", "3,4,5")
callback(array){
Loop, Parse, array, `,
MsgBox % (2 * A_LoopField)
}
map(callback, array){
%callback%(array)
}
AWK
$ awk 'func psqr(x){print x,x*x}BEGIN{split("1 2 3 4 5",a);for(i in a)psqr(a[i])}'
4 16
5 25
1 1
2 4
3 9
Babel
Let us define a squaring operator:
sq { dup * } <
Now, we apply the sq operator over a list and display the result using the lsnum utility:
( 0 1 1 2 3 5 8 13 21 34 ) { sq ! } over ! lsnum !
- Output:
( 0 1 1 4 9 25 64 169 441 1156 )
BBC BASIC
DIM a(4)
a() = 1, 2, 3, 4, 5
PROCmap(a(), FNsqrt())
FOR i = 0 TO 4
PRINT a(i)
NEXT
END
DEF FNsqrt(n) = SQR(n)
DEF PROCmap(array(), RETURN func%)
LOCAL I%
FOR I% = 0 TO DIM(array(),1)
array(I%) = FN(^func%)(array(I%))
NEXT
ENDPROC
- Output:
1 1.41421356 1.73205081 2 2.23606798
Binary Lambda Calculus
In the lambda calculus, we can map over a list as in https://github.com/tromp/AIT/blob/master/lists/map.lam, which gives the following BLC program to negate every bit of input:
010001101000000101100000000001011000000101111111010110010111111101111110111010
BQN
Square ← ט
array ← 2‿3‿5‿7‿11‿13
Square¨ array
The use of the ¨ modifier is the general approach, but actually not necessary with arithmetic functions.
- Output:
⟨ 4 9 25 49 121 169 ⟩
Bracmat
( ( callbackFunction1
= location value
. !arg:(?location,?value)
& out$(str$(array[ !location "] = " !!value))
)
& ( callbackFunction2
= location value
. !arg:(?location,?value)
& !!value^2:?!value
)
& ( mapar
= arr len callback i
. !arg:(?arr,?len,?callback)
& 0:?i
& whl
' ( !i:<!len
& !callback$(!i,!i$!arr)
& 1+!i:?i
)
)
& tbl$(array,4)
& 1:?(0$array)
& 2:?(1$array)
& 3:?(2$array)
& 4:?(3$array)
& mapar$(array,4,callbackFunction1)
& mapar$(array,4,callbackFunction2)
& mapar$(array,4,callbackFunction1)
);
- Output:
array[0] = 1 array[1] = 2 array[2] = 3 array[3] = 4 array[0] = 1 array[1] = 4 array[2] = 9 array[3] = 16
Brat
#Print out each element in array
[:a :b :c :d :e].each { element |
p element
}
Alternatively:
[:a :b :c :d :e].each ->p
C
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#
This version uses the C# 3 lambda notation.
int[] intArray = { 1, 2, 3, 4, 5 };
// Simplest method: LINQ, functional
int[] squares1 = intArray.Select(x => x * x).ToArray();
// Slightly fancier: LINQ, query expression
int[] squares2 = (from x in intArray
select x * x).ToArray();
// Or, if you only want to call a function on each element, just use foreach
foreach (var i in intArray)
Console.WriteLine(i * i);
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++
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
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
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
C++11
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
int main() {
std::vector<int> intVec(10);
std::iota(std::begin(intVec), std::end(intVec), 1 ); // Fill the vector
std::transform(std::begin(intVec) , std::end(intVec), std::begin(intVec),
[](int i) { return i * i ; } ); // Transform it with closures
std::copy(std::begin(intVec), end(intVec) ,
std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
return 0;
}
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
Clio
Math operations
[1 2 3 4] * 2 + 1 -> print
Quick functions
[1 2 3 4] -> * n: n * 2 + 1 -> print
Anonymous function
[1 2 3 4]
-> * fn n:
n * 2 + 1
-> print
Named function
fn double-plus-one n:
n * 2 + 1
[1 2 3 4] -> * double-plus-one -> print
Clojure
;; apply a named function, inc
(map inc [1 2 3 4])
;; apply a function
(map (fn [x] (* x x)) [1 2 3 4])
;; shortcut syntax for a function
(map #(* % %) [1 2 3 4])
CLU
% This procedure will call a given procedure with each element
% of the given array. Thanks to CLU's type parameterization,
% it will work for any type of element.
apply_to_all = proc [T: type] (a: array[T], f: proctype(int,T))
for i: int in array[T]$indexes(a) do
f(i, a[i])
end
end apply_to_all
% Callbacks for both string and int
show_int = proc (i, val: int)
po: stream := stream$primary_output()
stream$putl(po, "array[" || int$unparse(i) || "] = " || int$unparse(val));
end show_int
show_string = proc (i: int, val: string)
po: stream := stream$primary_output()
stream$putl(po, "array[" || int$unparse(i) || "] = " || val);
end show_string
% Here's how to use them
start_up = proc ()
po: stream := stream$primary_output()
ints: array[int] := array[int]$[2, 3, 5, 7, 11]
strings: array[string] := array[string]$
["enemy", "lasagna", "robust", "below", "wax"]
stream$putl(po, "Ints: ")
apply_to_all[int](ints, show_int)
stream$putl(po, "\nStrings: ")
apply_to_all[string](strings, show_string)
end start_up
- Output:
Ints: array[1] = 2 array[2] = 3 array[3] = 5 array[4] = 7 array[5] = 11 Strings: array[1] = enemy array[2] = lasagna array[3] = robust array[4] = below array[5] = wax
COBOL
Basic implementation of a map function:
>>SOURCE FORMAT IS FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. map.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 i USAGE IS INDEX.
01 table-size CONSTANT AS 30.
LINKAGE SECTION.
01 table-param.
03 table-values USAGE IS FLOAT-LONG, OCCURS table-size TIMES.
01 func-ptr USAGE IS PROGRAM-POINTER.
PROCEDURE DIVISION USING BY REFERENCE table-param, BY VALUE func-ptr.
PERFORM VARYING i FROM 1 BY 1 UNTIL i IS GREATER THAN table-size
CALL func-ptr USING BY REFERENCE table-values(i)
END-PERFORM
GOBACK.
END PROGRAM map.
CoffeeScript
map = (arr, f) -> (f(e) for e in arr)
arr = [1, 2, 3, 4, 5]
f = (x) -> x * x
console.log map arr, f # prints [1, 4, 9, 16, 25]
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*)
Component Pascal
BlackBox Component Builder
MODULE Callback;
IMPORT StdLog;
TYPE
Callback = PROCEDURE (x: INTEGER;OUT doubled: INTEGER);
Callback2 = PROCEDURE (x: INTEGER): INTEGER;
PROCEDURE Apply(proc: Callback; VAR x: ARRAY OF INTEGER);
VAR
i: INTEGER;
BEGIN
FOR i := 0 TO LEN(x) - 1 DO;
proc(x[i],x[i]);
END
END Apply;
PROCEDURE Apply2(func: Callback2; VAR x: ARRAY OF INTEGER);
VAR
i: INTEGER;
BEGIN
FOR i := 0 TO LEN(x) - 1 DO;
x[i] := func(x[i]);
END
END Apply2;
PROCEDURE Double(x: INTEGER; OUT y: INTEGER);
BEGIN
y := x * x;
END Double;
PROCEDURE Double2(x: INTEGER): INTEGER;
BEGIN
RETURN x * x
END Double2;
PROCEDURE Do*;
VAR
i: INTEGER;
ary: ARRAY 10 OF INTEGER;
BEGIN
FOR i := 0 TO LEN(ary) - 1 DO ary[i] := i END;
Apply(Double,ary);
FOR i := 0 TO LEN(ary) - 1 DO
StdLog.Int(ary[i]);StdLog.Ln
END;
StdLog.Ln;
Apply2(Double2,ary);
FOR i := 0 TO LEN(ary) - 1 DO
StdLog.Int(ary[i]);StdLog.Ln
END
END Do;
END Callback.
Execute: ^Q Callback.Do
- Output:
0 1 4 9 16 25 36 49 64 81 0 1 16 81 256 625 1296 2401 4096 6561
Crystal
Calling with a block
values = [1, 2, 3]
new_values = values.map do |number|
number * 2
end
puts new_values #=> [2, 4, 6]
Calling with a function/method
values = [1, 2, 3]
def double(number)
number * 2
end
# the `->double(Int32)` syntax creates a proc from a function/method. argument types must be specified.
# the `&proc` syntax passes a proc as a block.
# combining the two passes a function/method as a block
new_values = values.map &->double(Int32)
puts new_values #=> [2, 4, 6]
D
import std.stdio, std.algorithm;
void main() {
auto items = [1, 2, 3, 4, 5];
auto m = items.map!(x => x + 5)();
writeln(m);
}
- Output:
[6, 7, 8, 9, 10]
Delphi
// Declare the callback function
procedure callback(const AInt:Integer);
begin
WriteLn(AInt);
end;
const
// Declare a static array
myArray:Array[0..4] of Integer=(1,4,6,8,7);
var
// Declare interator variable
i:Integer;
begin
// Iterate the array and apply callback
for i:=0 to length(myArray)-1 do
callback(myArray[i]);
end.
Dyalect
func Array.Select(pred) {
let ys = []
for x in this when pred(x) {
ys.Add(x)
}
return ys
}
var arr = [1, 2, 3, 4, 5]
var squares = arr.Select(x => x * x)
print(squares)
Déjà Vu
There is a map
builtin that does just this.
!. map @++ [ 1 4 8 ]
#implemented roughly like this:
#map f lst:
# ]
# for i in lst:
# f i
# [
- Output:
[ 2 5 9 ]
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 built-in 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))
EchoLisp
(vector-map sqrt #(0 4 16 49))
→ #( 0 2 4 7)
;; or
(map exp #(0 1 2))
→ #( 1 2.718281828459045 7.38905609893065)
;; or
(for/vector ([elem #(2 3 4)] [i (in-naturals)]) (printf "v[%d] = %a" i elem) (* elem elem))
v[0] = 2
v[1] = 3
v[2] = 4
→ #( 4 9 16)
Efene
square = fn (N) {
N * N
}
# list comprehension
squares1 = fn (Numbers) {
[square(N) for N in Numbers]
}
# functional form
squares2a = fn (Numbers) {
lists.map(fn square:1, Numbers)
}
# functional form with lambda
squares2b = fn (Numbers) {
lists.map(fn (N) { N * N }, Numbers)
}
# no need for a function
squares3 = fn (Numbers) {
[N * N for N in Numbers]
}
@public
run = fn () {
Numbers = [1, 3, 5, 7]
io.format("squares1 : ~p~n", [squares1(Numbers)])
io.format("squares2a: ~p~n", [squares2a(Numbers)])
io.format("squares2b: ~p~n", [squares2b(Numbers)])
io.format("squares3 : ~p~n", [squares3(Numbers)])
}
EGL
delegate callback( i int ) returns( int ) end
program ApplyCallbackToArray
function main()
values int[] = [ 1, 2, 3, 4, 5 ];
func callback = square;
for ( i int to values.getSize() )
values[ i ] = func( values[ i ] );
end
for ( i int to values.getSize() )
SysLib.writeStdout( values[ i ] );
end
end
function square( i int ) returns( int )
return( i * i );
end
end
Elena
ELENA 6.x :
import system'routines;
PrintSecondPower(n){ console.writeLine(n * n) }
public program()
{
new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.forEach(PrintSecondPower)
}
Elixir
Enum.map([1, 2, 3], fn(n) -> n * 2 end)
Enum.map [1, 2, 3], &(&1 * 2)
- Output:
[2, 4, 6]
Erlang
A list would be more commonly used in Erlang rather than an array.
1> L = [1,2,3].
[1,2,3]
You can use lists:foreach/2 if you just want to apply the callback to each element of the list.
2> lists:foreach(fun(X) -> io:format("~w ",[X]) end, L).
1 2 3 ok
Or you can use lists:map/2 if you want to create a new list with the result of the callback on each element.
3> lists:map(fun(X) -> X + 1 end, L).
[2,3,4]
Or you can use lists:foldl/3 if you want to accumulate the result of the callback on each element into one value.
4> lists:foldl(fun(X, Sum) -> X + Sum end, 0, L).
6
ERRE
PROGRAM CALLBACK
!
! for rosettacode.org
!
DIM A[5]
FUNCTION CBACK(X)
CBACK=2*X-1
END FUNCTION
PROCEDURE PROCMAP(ZETA,DUMMY(X)->OUTP)
OUTP=DUMMY(ZETA)
END PROCEDURE
BEGIN
A[1]=1 A[2]=2 A[3]=3 A[4]=4 A[5]=5
FOR I%=1 TO 5 DO
PROCMAP(A[I%],CBACK(X)->OUTP)
PRINT(OUTP;)
END FOR
PRINT
END PROGRAM
This example shows how to pass a function to a procedure.
- Output:
1 3 5 7 9
Euphoria
function apply_to_all(sequence s, integer f)
-- apply a function to all elements of a sequence
sequence result
result = {}
for i = 1 to length(s) do
-- we can call add1() here although it comes later in the program
result = append(result, call_func(f, {s[i]}))
end for
return result
end function
function add1(atom x)
return x + 1
end function
-- add1() is visible here, so we can ask for its routine id
? apply_to_all({1, 2, 3}, routine_id("add1"))
-- displays {2,3,4}
This is also "Example 2" in the Euphoria documentation for routine_id()
.
Note that this example will not work for multi-dimensional sequences.
F#
Apply a named function to each member of the array. The result is a new array of the same size as the input.
let evenp x = x % 2 = 0
let result = Array.map evenp [| 1; 2; 3; 4; 5; 6 |]
The same can be done using anonymous functions, this time squaring the members of the input array.
let result = Array.map (fun x -> x * x) [|1; 2; 3; 4; 5|]
Use iter if the applied function does not return a value.
Array.iter (fun x -> printfn "%d" x) [|1; 2; 3; 4; 5|]
Factor
Print each element squared:
{ 1 2 3 4 } [ sq . ] each
Collect return values:
{ 1 2 3 4 } [ sq ] map
Fantom
In Fantom, functions can be passed to a collection iterator, such as 'each'. 'map' is used similarly, and the results are collected into a list.
class Main
{
public static Void main ()
{
[1,2,3,4,5].each |Int i| { echo (i) }
Int[] result := [1,2,3,4,5].map |Int i->Int| { return i * i }
echo (result)
}
}
- Output:
1 2 3 4 5 [1, 4, 9, 16, 25]
FBSL
User-defined mapping function:
#APPTYPE CONSOLE
FOREACH DIM e IN MyMap(Add42, {1, 2, 3})
PRINT e, " ";
NEXT
PAUSE
FUNCTION MyMap(f, a)
DIM ret[]
FOREACH DIM e IN a
ret[] = f(e)
NEXT
RETURN ret
END FUNCTION
FUNCTION Add42(n): RETURN n + 42: END FUNCTION
- Output:
43 44 45 Press any key to continue...
Standard MAP() function:
#APPTYPE CONSOLE
DIM languages[] = {{"English", {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}}, _
{"French", {"un", "deux", "trois", "quatre", "cinq", "six", "sept", "huit", "neuf", "dix"}}}
MAP(SpeakALanguage, languages)
PAUSE
SUB NameANumber(lang, nb, number)
PRINT "The number ", nb, " is called ", STRENC(number), " in ", lang
END SUB
SUB SpeakALanguage(lang)
MAP(NameANumber, lang[0], 1 TO 10, lang[1])
PRINT LPAD("", 40, "-")
END SUB
- Output:
The number 1 is called "one" in English The number 2 is called "two" in English The number 3 is called "three" in English The number 4 is called "four" in English The number 5 is called "five" in English The number 6 is called "six" in English The number 7 is called "seven" in English The number 8 is called "eight" in English The number 9 is called "nine" in English The number 10 is called "ten" in English ---------------------------------------- The number 1 is called "un" in French The number 2 is called "deux" in French The number 3 is called "trois" in French The number 4 is called "quatre" in French The number 5 is called "cinq" in French The number 6 is called "six" in French The number 7 is called "sept" in French The number 8 is called "huit" in French The number 9 is called "neuf" in French The number 10 is called "dix" in French ---------------------------------------- Press any key to continue...
Fe
(= map (fn (f lst)
(let res (cons nil nil))
(let tail res)
(while lst
(setcdr tail (cons (f (car lst)) nil))
(= lst (cdr lst))
(= tail (cdr tail)))
(cdr res)))
(print (map (fn (x) (* x x)) '(1 2 3 4 5 6 7 8 9 10)))
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
Elemental functions.
module arrCallback
contains
elemental function cube( x )
implicit none
real :: cube
real, intent(in) :: x
cube = x * x * x
end function cube
end module arrCallback
program testAC
use arrCallback
implicit none
integer :: i, j
real, dimension(3,4) :: b, &
a = reshape( (/ ((10 * i + j, i = 1, 3), j = 1, 4) /), (/ 3,4 /) )
do i = 1, 3
write(*,*) a(i,:)
end do
b = cube( a ) ! Applies CUBE to every member of a,
! and stores each result in the equivalent element of b
do i = 1, 3
write(*,*) b(i,:)
end do
end program testAC
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
{square * . [id, id]}
& square: <1,2,3,4,5>
FreeBASIC
' FB 1.05.0 Win64
Sub PrintEx(n As Integer)
Print n, n * n, n * n * n
End Sub
Sub Proc(a() As Integer, callback As Sub(n As Integer))
For i As Integer = LBound(a) To UBound(a)
callback(i)
Next
End Sub
Dim a(1 To 10) As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Print " n", "n^2", "n^3"
Print " -", "---", "---"
Proc(a(), @PrintEx)
Print
Print "Press any key to quit the program"
Sleep
- Output:
n n^2 n^3 - --- --- 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000
Frink
f = {|x| x^2} // Anonymous function to square input
a = [1,2,3,5,7]
println[map[f, a]]
FunL
[1, 2, 3].foreach( println )
[1, 2, 3].foreach( a -> println(2a) )
- Output:
1 2 3 2 4 6
Futhark
map f l
e.g.
map (\x->x+1) [1,2,3] -- [2,3,4]
or equivalently
map (+1) [1,2,3] -- [2,3,4]
FutureBasic
include "NSLog.incl"
void local fn Callback( n as NSInteger )
NSLog( @"Square root of %ld = %f", n, sqr(n) )
end fn
void local fn DoIt
NSUInteger i, count
CFArrayRef array = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10]
count = len(array)
for i = 0 to count -1
fn Callback( fn NumberIntegerValue( array[i] ) )
next
end fn
fn DoIt
HandleEvents
Another option is to enumerate the array.
include "NSLog.incl"
void local fn Callback( array as CFArrayRef, obj as CFTypeRef )
long value = intVal(obj)
NSLog( @"Square root of %ld = %f", value, sqr(value) )
end fn
void local fn DoIt
CFArrayRef array = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10]
ArrayEnumerateObjects( array, @fn Callback, NULL )
end fn
fn DoIt
HandleEvents
- Output:
Square root of 1 = 1.000000 Square root of 2 = 1.414214 Square root of 3 = 1.732051 Square root of 4 = 2.000000 Square root of 5 = 2.236068 Square root of 6 = 2.449490 Square root of 7 = 2.645751 Square root of 8 = 2.828427 Square root of 9 = 3.000000 Square root of 10 = 3.162278
Fōrmulæ
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in its website.
In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.
Solution
Most programming languages define a high-order map function. In Fōrmulæ, there is arraization (by analogy with summation). In the following expression, the "big" curly braces resembles the "big" sigma of a summation:
The elements of the array are not required to be of the same type:
GAP
a := [1 .. 4];
b := ShallowCopy(a);
# Apply and replace values
Apply(a, n -> n*n);
a;
# [ 1, 4, 9, 16 ]
# Apply and don't change values
List(b, n -> n*n);
# [ 1, 4, 9, 16 ]
# Apply and don't return anything (only side effects)
Perform(b, Display);
1
2
3
4
b;
# [ 1 .. 4 ]
Go
The task was originally written with a Ruby example, so here are Go versions of the current Ruby examples.
Perhaps in contrast to Ruby, it is idiomatic in Go to use the for statement:
package main
import "fmt"
func main() {
for _, i := range []int{1, 2, 3, 4, 5} {
fmt.Println(i * i)
}
}
Alternatively though, an array-like type can be defined and callback-style methods can be defined on it to apply a function to the elements.
package main
import "fmt"
type intSlice []int
func (s intSlice) each(f func(int)) {
for _, i := range s {
f(i)
}
}
func (s intSlice) Map(f func(int) int) intSlice {
r := make(intSlice, len(s))
for j, i := range s {
r[j] = f(i)
}
return r
}
func main() {
s := intSlice{1, 2, 3, 4, 5}
s.each(func(i int) {
fmt.Println(i * i)
})
fmt.Println(s.Map(func(i int) int {
return i * i
}))
}
- Output:
1 4 9 16 25 [1 4 9 16 25]
Groovy
Print each value in a list
[1,2,3,4].each { println it }
Create a new list containing the squares of another list
[1,2,3,4].collect { it * it }
Haskell
List
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]
More directly
[1 .. 10] >>= pure . (^ 2)
Or with one less layer of monadic wrapping
(^ 2) <$> [1..10]
Using function composition to create a function that will print the squares of a list
let printSquares = mapM_ (print.square)
printSquares values
Array
import Data.Array (Array, listArray)
square :: Int -> Int
square x = x * x
values :: Array Int Int
values = listArray (1, 10) [1 .. 10]
main :: IO ()
main = print $ fmap square values
- Output:
array (1,10) [(1,1),(2,4),(3,9),(4,16),(5,25),(6,36),(7,49),(8,64),(9,81),(10,100)]
Guish
# applies add2 (adds 2) to each element
add2 = {
return add(@1, 2)
}
l = {1, 2, 3, 4, 5, 6, 7}
puts each(add2, flat(@l))
Icon and Unicon
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 if a is an n-dimensional array
Insitux
; apply a named function
(map inc [1 2 3 4])
; apply a parameterised closure
(map (fn x (+ x 1)) [1 2 3 4])
; apply a non-parameterised closure
(map #(+ % 1) [1 2 3 4])
; apply an explicit partial closure
(map @(+ 1) [1 2 3 4])
; apply an implicit partial closure
(map (+ 1) [1 2 3 4])
Io
list(1,2,3,4,5) map(squared)
J
Solution:
"_1
Example:
callback =: *:
array =: 1 2 3 4 5
callback"_1 array
1 4 9 16 25
But note that this is a trivial example since *: 1 2 3 4 5
would get the same result. Then again, this is something of a trivial exercise in J since all of J is designed around the idea of applying functions usefully to arrays.
Jakt
fn map<T, U>(anon array: [T], function: fn(anon x: T) -> U) throws -> [U] {
mut result: [U] = []
result.ensure_capacity(array.size())
for item in array {
result.push(value: function(item))
}
return result
}
fn main() {
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let array_squared = map(array, function: fn(anon n: i64) => n * n)
println("{}", array_squared)
}
- Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Java
Up to Java 7, you have to define an interface for each type of function you want to use.
The IntConsumer
performs an action (which doesn't return anything) on an array of ints,
while the IntToInt
is used to replace the array values.
public class ArrayCallback7 {
interface IntConsumer {
void run(int x);
}
interface IntToInt {
int run(int x);
}
static void forEach(int[] arr, IntConsumer consumer) {
for (int i : arr) {
consumer.run(i);
}
}
static void update(int[] arr, IntToInt mapper) {
for (int i = 0; i < arr.length; i++) {
arr[i] = mapper.run(arr[i]);
}
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
forEach(numbers, new IntConsumer() {
public void run(int x) {
System.out.println(x);
}
});
update(numbers, new IntToInt() {
@Override
public int run(int x) {
return x * x;
}
});
forEach(numbers, new IntConsumer() {
public void run(int x) {
System.out.println(x);
}
});
}
}
Using Java 8 streams:
import java.util.Arrays;
public class ArrayCallback {
public static void main(String[] args) {
int[] myIntArray = {1, 2, 3, 4, 5};
int sum = Arrays.stream(myIntArray)
.map(x -> {
int cube = x * x * x;
System.out.println(cube);
return cube;
})
.reduce(0, (left, right) -> left + right); // <-- could substitute .sum() for .reduce(...) here.
System.out.println("sum: " + sum);
}
}
JavaScript
ES3
function map(a, func) {
var ret = [];
for (var i = 0; i < a.length; i++) {
ret[i] = func(a[i]);
}
return ret;
}
map([1, 2, 3, 4, 5], function(v) { return v * v; });
ES5
[1, 2, 3, 4, 5].map(function(v) { return v * v; });
ES6
[1, 2, 3, 4, 5].map(v => v * v);
The result is always:
[1, 4, 9, 16, 25]
Joy
[1 2 3 4 5] [dup *] map.
jq
# Illustration of map/1 using the builtin filter: exp
map(exp) # exponentiate each item in the input list
# A compound expression can be specified as the argument to map, e.g.
map( (. * .) + sqrt ) # x*x + sqrt(x)
# The compound expression can also be a composition of filters, e.g.
map( sqrt|floor ) # the floor of the sqrt
# Array comprehension
reduce .[] as $n ([]; . + [ exp ])
# Elementwise operation
[.[] + 1 ] # add 1 to each element of the input array
Here is a transcript illustrating how the last of these jq expressions can be evaluated:
$ jq -c ' [.[] + 1 ]'
[0, 1 , 10]
[1,2,11]
Jsish
/* Apply callback, in Jsish using array.map() */
;[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; });
/*
=!EXPECTSTART!=
[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; }) ==> [ 1, 4, 9, 16, 25 ]
=!EXPECTEND!=
*/
- Output:
prompt$ jsish -u applyCallback.jsi [PASS] applyCallback.jsi
Julia
numbers = [1, 3, 5, 7]
@show [n ^ 2 for n in numbers] # list comprehension
square(x) = x ^ 2; @show map(square, numbers) # functional form
@show map(x -> x ^ 2, numbers) # functional form with anonymous function
@show [n * n for n in numbers] # no need for a function,
@show numbers .* numbers # element-wise operation
@show numbers .^ 2 # includes .+, .-, ./, comparison, and bitwise operations as well
Kotlin
fun main(args: Array<String>) {
val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // build
val function = { i: Int -> i * i } // function to apply
val list = array.map { function(it) } // process each item
println(list) // print results
}
- Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Klingphix
include ..\Utilitys.tlhy
( 1 2 3 4 ) [dup *] map
pstack
" " input
- Output:
((1, 4, 9, 16))
Lambdatalk
{A.map {lambda {:x} {* :x :x}} {A.new 1 2 3 4 5 6 7 8 9 10}}
-> [1,4,9,16,25,36,49,64,81,100]
Lang
&arr = fn.arrayGenerateFrom(fn.inc, 10)
fn.println(&arr)
fn.arrayMap(&arr, fn.combC(fn.pow, 2))
fn.println(&arr)
- Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Lang5
: square(*) dup * ;
[1 2 3 4 5] square . "\n" .
[1 2 3 4 5] 'square apply . "\n" .
langur
writeln map(fn{^2}, 1..10)
- Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Lasso
define cube(n::integer) => #n*#n*#n
local(
mynumbers = array(1, 2, 3, 4, 5),
mycube = array
)
#mynumbers -> foreach => {
#mycube -> insert(cube(#1))
}
#mycube
-> array(1, 8, 27, 64, 125)
Lisaac
+ a : ARRAY(INTEGER);
+ b : {INTEGER;};
a := ARRAY(INTEGER).create 1 to 3;
1.to 3 do { i : INTEGER;
a.put i to i;
};
b := { arg : INTEGER;
(arg * arg).print;
'\n'.print;
};
a.foreach b;
Logo
to square :x
output :x * :x
end
show map "square [1 2 3 4 5] ; [1 4 9 16 25]
show map [? * ?] [1 2 3 4 5] ; [1 4 9 16 25]
foreach [1 2 3 4 5] [print square ?] ; 1 4 9 16 25, one per line
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 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. However, remember that hash table do not have an implicit ordering on their elements, like arrays do, so pairs() is not guaranteed to return the elements in the same order as ipairs()
M2000 Interpreter
a=(1,2,3,4,5)
b=lambda->{
push number**2
}
Print a#map(b) ' 1 4 9 16 25
Print a#map(b, b) ' 1 16 81 256 625
b=lambda (z) ->{
=lambda z ->{
push number**z
}
}
Print a#map(b(2)) ' 1 4 9 16 25
Print a#map(b(3)) ' 1 8 27 64 125
\\ second example
a=(1,2,3,4,5)
class s {sum=0}
\\ s is a pointer to an instance of s()
s->s()
c=lambda s -> {
push number+number
s=>sum=stackitem() ' peek the value from stack
}
\\ c passed by value to fold(), but has a pointer to s
Print a#fold(c, 100)=115
Print s=>sum=115
M4
define(`foreach', `pushdef(`$1')_foreach($@)popdef(`$1')')dnl
define(`_arg1', `$1')dnl
define(`_foreach', `ifelse(`$2', `()', `',
`define(`$1', _arg1$2)$3`'$0(`$1', (shift$2), `$3')')')dnl
dnl
define(`apply',`foreach(`x',$1,`$2(x)')')dnl
dnl
define(`z',`eval(`$1*2') ')dnl
apply(`(1,2,3)',`z')
- Output:
2 4 6
Maple
For lists and sets, which in Maple are immutable, a new object is returned. Either the built-in procedure map, or the short syntax of a trailing tilde (~) on the applied operator may be used.
> map( sqrt, [ 1.1, 3.2, 5.7 ] );
[1.048808848, 1.788854382, 2.387467277]
> map( x -> x + 1, { 1, 3, 5 } );
{2, 4, 6}
> sqrt~( [ 1.1, 3.2, 5.7 ] );
[1.048808848, 1.788854382, 2.387467277]
> (x -> x + 1)~( { 1, 3, 5 } );
{2, 4, 6}
For Arrays (Vectors, Matrices, etc.) both map and trailing tilde also work, and by default create a new object, leaving the input Array unchanged.
> a := Array( [ 1.1, 3.2, 5.7 ] );
a := [1.1, 3.2, 5.7]
> sqrt~( a );
[1.048808848, 1.788854382, 2.387467277]
> a;
[1.1, 3.2, 5.7]
> map( sqrt, a );
[1.048808848, 1.788854382, 2.387467277]
> a;
[1.1, 3.2, 5.7]
However, since these are mutable data structures in Maple, it is possible to use map to modify its input according to the applied procedure.
> map[inplace]( sqrt, a );
[1.048808848, 1.788854382, 2.387467277]
> a;
[1.048808848, 1.788854382, 2.387467277]
The Array a has been modified.
It is also possible to pass additional arguments to the mapped procedure.
> map( `+`, [ 1, 2, 3 ], 3 );
[4, 5, 6]
Passing additional arguments *before* the arguments from the mapped data structure is achieved using map2, or the more general map[n] procedure.
> map2( `-`, 5, [ 1, 2, 3 ] );
[4, 3, 2]
> map[2]( `/`, 5, [ 1, 2, 3 ] );
[5, 5/2, 5/3]
Mathematica //Wolfram Language
(#*#)& /@ {1, 2, 3, 4}
Map[Function[#*#], {1, 2, 3, 4}]
Map[((#*#)&,{1,2,3,4}]
Map[Function[w,w*w],{1,2,3,4}]
MATLAB
There are two types of arrays in MATLAB: arrays and cell arrays. MATLAB includes two functions, one for each of these data types, that accomplish the specification for this task. For arrays, we use "arrayfun()"; for cell arrays we use "cellfun()".
Example:
For both of these function the first argument is a function handle for the function we would like to apply to each element. The second argument is the array whose elements are modified by the function. The function can be any function, including user defined functions.
>> array = [1 2 3 4 5]
array =
1 2 3 4 5
>> arrayfun(@sin,array)
ans =
Columns 1 through 4
0.841470984807897 0.909297426825682 0.141120008059867 -0.756802495307928
Column 5
-0.958924274663138
>> cellarray = {1,2,3,4,5}
cellarray =
[1] [2] [3] [4] [5]
>> cellfun(@tan,cellarray)
ans =
Columns 1 through 4
1.557407724654902 -2.185039863261519 -0.142546543074278 1.157821282349578
Column 5
-3.380515006246586
Maxima
/* for lists or sets */
map(sin, [1, 2, 3, 4]);
map(sin, {1, 2, 3, 4});
/* for matrices */
matrixmap(sin, matrix([1, 2], [2, 4]));
min
(1 2 3 4 5) (sqrt puts) foreach ; print each square root
(1 2 3 4 5) 'sqrt map ; collect return values
Modula-3
MODULE Callback EXPORTS Main;
IMPORT IO, Fmt;
TYPE CallBack = PROCEDURE (a: CARDINAL; b: INTEGER);
Values = REF ARRAY OF INTEGER;
VAR sample := ARRAY [1..5] OF INTEGER {5, 4, 3, 2, 1};
callback := Display;
PROCEDURE Display(loc: CARDINAL; val: INTEGER) =
BEGIN
IO.Put("array[" & Fmt.Int(loc) & "] = " & Fmt.Int(val * val) & "\n");
END Display;
PROCEDURE Map(VAR values: ARRAY OF INTEGER; size: CARDINAL; worker: CallBack) =
VAR lvalues := NEW(Values, size);
BEGIN
FOR i := FIRST(lvalues^) TO LAST(lvalues^) DO
worker(i, values[i]);
END;
END Map;
BEGIN
Map(sample, NUMBER(sample), callback);
END Callback.
Nanoquery
// create a list of numbers 1-10
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
// display the list as it is
println numbers
// square each element in the list
for i in range(1, len(numbers) - 1)
numbers[i] = numbers[i] * numbers[i]
end
// display the squared list
println numbers
- Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Nemerle
The Nemerle.Collections namespace defines the methods Iter() (if the function applied is void) and Map() (if the function applied returns a value).
def seg = array[1, 2, 3, 5, 8, 13];
def squares = seq.Map(x => x*x);
NetLogo
;; NetLogo “anonymous procedures”
;; stored in a variable, just to show it can be done.
let callback [ [ x ] x * x ]
show (map callback [ 1 2 3 4 5 ])
NewLISP
> (map (fn (x) (* x x)) '(1 2 3 4))
(1 4 9 16)
NGS
{
[1, 2, 3, 4, 5].map(F(x) x*x)
}
Nial
each (* [first, first] ) 1 2 3 4
=1 4 9 16
Nim
from std/sequtils import apply
let arr = @[1,2,3,4]
arr.apply proc(some: int) = echo(some, " squared = ", some*some)
- Output:
1 squared = 1 2 squared = 4 3 squared = 9 4 squared = 16
Nutt
module main
imports native.io.output.say
operator |> (arr:Array,f:Procedure):Array==>{f(x) of x |-> arr}
say({0,1,2,3,4,5}|>a==>a+2)//|{2,3,4,5,6,7}
end
Oberon-2
MODULE ApplyCallBack;
IMPORT
Out := NPCT:Console;
TYPE
Fun = PROCEDURE (x: LONGINT): LONGINT;
Ptr2Ary = POINTER TO ARRAY OF LONGINT;
VAR
a: ARRAY 5 OF LONGINT;
x: ARRAY 3 OF LONGINT;
r: Ptr2Ary;
PROCEDURE Min(x,y: LONGINT): LONGINT;
BEGIN
IF x <= y THEN RETURN x ELSE RETURN y END;
END Min;
PROCEDURE Init(VAR a: ARRAY OF LONGINT);
BEGIN
a[0] := 0;
a[1] := 1;
a[2] := 2;
a[3] := 3;
a[4] := 4;
END Init;
PROCEDURE Fun1(x: LONGINT): LONGINT;
BEGIN
RETURN x * 2
END Fun1;
PROCEDURE Fun2(x: LONGINT): LONGINT;
BEGIN
RETURN x DIV 2;
END Fun2;
PROCEDURE Fun3(x: LONGINT): LONGINT;
BEGIN
RETURN x + 3;
END Fun3;
PROCEDURE Map(F: Fun; VAR x: ARRAY OF LONGINT);
VAR
i: LONGINT;
BEGIN
FOR i := 0 TO LEN(x) - 1 DO
x[i] := F(x[i])
END
END Map;
PROCEDURE Map2(F: Fun; a: ARRAY OF LONGINT; VAR r: ARRAY OF LONGINT);
VAR
i,l: LONGINT;
BEGIN
l := Min(LEN(a),LEN(x));
FOR i := 0 TO l - 1 DO
r[i] := F(a[i])
END
END Map2;
PROCEDURE Map3(F: Fun; a: ARRAY OF LONGINT): Ptr2Ary;
VAR
r: Ptr2Ary;
i: LONGINT;
BEGIN
NEW(r,LEN(a));
FOR i := 0 TO LEN(a) - 1 DO
r[i] := F(a[i]);
END;
RETURN r
END Map3;
PROCEDURE Show(a: ARRAY OF LONGINT);
VAR
i: LONGINT;
BEGIN
FOR i := 0 TO LEN(a) - 1 DO
Out.Int(a[i],4)
END;
Out.Ln
END Show;
BEGIN
Init(a);Map(Fun1,a);Show(a);
Init(a);Map2(Fun2,a,x);Show(x);
Init(a);r := Map3(Fun3,a);Show(r^);
END ApplyCallBack.
- Output:
0 2 4 6 8 0 0 1 3 4 5 6 7
Objeck
use Structure;
bundle Default {
class Test {
function : Main(args : String[]) ~ Nil {
Run();
}
function : native : Run() ~ Nil {
values := IntVector->New([1, 2, 3, 4, 5]);
squares := values->Apply(Square(Int) ~ Int);
each(i : squares) {
squares->Get(i)->PrintLine();
};
}
function : Square(value : Int) ~ Int {
return value * value;
}
}
}
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;;
Or with lists (which are more typical in OCaml):
let values = [1;2;3;4;5;6;7;8;9;10];;
List.map square values;;
Use iter if the applied function does not return a value.
Array.iter (fun x -> Printf.printf "%d" x) [|1; 2; 3; 4; 5|];;
List.iter (fun x -> Printf.printf "%d" x) [1; 2; 3; 4; 5];;
with partial application we can also write:
Array.iter (Printf.printf "%d") [|1; 2; 3; 4; 5|];;
List.iter (Printf.printf "%d") [1; 2; 3; 4; 5];;
Octave
Almost all the built-in can operate on each element of a vector or matrix; e.g. sin([pi/2, pi, 2*pi]) computes the function sin on pi/2, pi and 2*pi (returning a vector). If a function does not accept vectors/matrices as arguments, the arrayfun can be used.
function e = f(x, y)
e = x^2 + exp(-1/(y+1));
endfunction
% f([2,3], [1,4]) gives and error, but
arrayfun(@f, [2, 3], [1,4])
% works
(The function f can be rewritten so that it can accept vectors as argument simply changing operators to their dot relatives: e = x.^2 + exp(-1 ./ (y.+1))
)
Odin
package main
import "core:slice"
import "core:fmt"
squared :: proc(x: int) -> int {
return x * x
}
main :: proc() {
arr := []int{1, 2, 3, 4, 5}
res := slice.mapper(arr, squared)
fmt.println(res) // prints: [1, 4, 9, 16, 25]
}
Oforth
apply allows to perform a function on all elements of a list :
0 #+ [ 1, 2, 3, 4, 5 ] apply
map regroups all results into a new list :
#sq [ 1, 2, 3, 4, 5 ] map
Ol
Apply custom callback (lambda) to every element of list.
(for-each
(lambda (element)
(display element))
'(1 2 3 4 5))
; ==> 12345
ooRexx
ooRexx doesn't directly support callbacks on array items, but this is pretty easy to implement using Routine objects.
start = .array~of("Rick", "Mike", "David", "Mark")
new = map(start, .routines~reversit)
call map new, .routines~sayit
-- a function to perform an iterated callback over an array
-- using the provided function. Returns an array containing
-- each function result
::routine map
use strict arg array, function
resultArray = .array~new(array~items)
do item over array
resultArray~append(function~call(item))
end
return resultArray
::routine reversit
use arg string
return string~reverse
::routine sayit
use arg string
say string
return .true -- called as a function, so a result is required
- Output:
kciR ekiM divaD kraM
Order
Both sequences and tuples support the usual map operation seen in many functional languages. Sequences also support 8seq_for_each
, and a few variations, which returns 8nil
.
#include <order/interpreter.h>
ORDER_PP( 8tuple_map(8fn(8X, 8times(8X, 8X)), 8tuple(1, 2, 3, 4, 5)) )
// -> (1,4,9,16,25)
ORDER_PP( 8seq_map(8fn(8X, 8times(8X, 8X)), 8seq(1, 2, 3, 4, 5)) )
// -> (1)(4)(9)(16)(25)
ORDER_PP( 8seq_for_each(8fn(8X, 8print(8X 8comma)), 8seq(1, 2, 3, 4, 5)) )
// prints 1,2,3,4,5, and returns 8nil
Oz
declare
fun{Square A}
A*A
end
Lst = [1 2 3 4 5]
%% apply a PROCEDURE to every element
{ForAll Lst Show}
%% apply a FUNCTION to every element
Result = {Map Lst Square}
{Show Result}
PARI/GP
callback(n)=n+n;
apply(callback, [1,2,3,4,5])
This should be contrasted with call
:
call(callback, [1,2,3,4,5])
which is equivalent to callback(1, 2, 3, 4, 5)
rather than [callback(1), callback(2), callback(3), callback(4), callback(5)]
.
Pascal
See Delphi
PascalABC.NET
begin
var a := Arr(1..10);
a := a.Select(x -> x * x).ToArray;
a.ForEach(x -> Print(x));
end.
- Output:
1 4 9 16 25 36 49 64 81 100
Perl
# create array
my @a = (1, 2, 3, 4, 5);
# create callback function
sub mycallback {
return 2 * shift;
}
# use array indexing
for (my $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)
# filter an array
my @e = grep { $_ % 2 == 0 } @a; # @e is now (2, 4)
Phix
requires("0.8.2") function add1(integer x) return x + 1 end function ?apply({1,2,3},add1)
- Output:
{2,3,4}
There are in fact three ways to invoke apply:
The oldest/original, as above, is apply(s,fn), where fn is invoked length(s) times with a single parameter of s[i].
apply(false,fn,s) likewise invokes fn length(s) times, but each time with length(s[i]) parameters.
apply(true,sprintf,{{"%d"},s}), the third way, invokes sprintf length(s) times with two parameters, being "%d" and each s[i].
This last way scans it's third argument looking for a (consistent) longest length to determine how many times to invoke sprintf,
uses the length of it's third argument to determine how many parameters each call will get, and
uses the same value on every call for any atom or length 1 elements, such as that {"%d"}.
Phixmonti
/# Rosetta Code problem: http://rosettacode.org/wiki/Apply_a_callback_to_an_array
by Galileo, 05/2022 #/
include ..\Utilitys.pmt
def ++
1 +
enddef
def square
dup *
enddef
( 1 2 3 ) dup
getid ++ map swap
getid square map
pstack
- Output:
[[2, 3, 4], [1, 4, 9]] === Press any key to exit ===
PHP
function cube($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
Picat
Picat doesn't support anonymous (lambda) functions so the function must be defined in the program to be used by - say - map/2. There are - however - quite a few ways without proper lambdas, using map/2, apply/2, or list comprehensions.
go =>
L = 1..10,
% Using map/2 in different ways
println(L.map(fun)),
println(map(L,fun)),
println(map(fun,L)),
% List comprehensions
println([fun(I) : I in L]),
% Using apply/2
println([apply(fun,I) : I in L]),
% And using list comprehension with the function directly.
println([I*I : I in L]),
nl.
% Some function
fun(X) = X*X.
This variant is inspired by the Prolog solution (using assert/1 to define a predicate) and shows the integration with Picat's underlying B-Prolog engine.
Picat does not support assert/1 directly, so one have to do the assert/1 in the bp module space (the module/space for the B-Prolog engine). To call the defined predicate, one must prepend the predicate name with "bp.".
Note that fun2/2 is not a function so map/2 or apply/2 cannot be used here.
go2 =>
L = 1..10,
% Define the predicate _in the bp space_.
bp.assert( $(fun2(X,Y) :- Y is X*X) ),
% Use bp.fun2 to call the function.
println([B : A in L, bp.fun2(A,B)]),
nl.
Using this technique one can do quite much "real" Prolog stuff even though Picat doesn't support it directly. However, one should be careful with this approach since it can sometimes be confusing and it doesn't work in all cases.
PicoLisp
: (mapc println (1 2 3 4 5)) # Print numbers
1
2
3
4
5
-> 5
: (mapcar '((N) (* N N)) (1 2 3 4 5)) # Calculate squares
-> (1 4 9 16 25)
: (mapcar ** (1 2 3 4 5) (2 .)) # Same, using a circular list
-> (1 4 9 16 25)
: (mapcar if '(T NIL T NIL) '(1 2 3 4) '(5 6 7 8)) # Conditional function
-> (1 6 3 8)
Pike
int cube(int n)
{
return n*n*n;
}
array(int) a = ({ 1,2,3,4,5 });
array(int) b = cube(a[*]); // automap operator
array(int) c = map(a, cube); // conventional map function
PL/I
declare x(5) initial (1,3,5,7,8);
x = sqrt(x);
x = sin(x);
PL/SQL
PL/SQL doesn't have callbacks, though we can pass around an object and use its method to simulate one. Further, this callback method can be defined in an abstract class that the mapping function will expect.
-- Let's create a generic class with one method to be used as an interface:
create or replace
TYPE callback AS OBJECT (
-- A class needs at least one member even though we don't use it
-- There's no generic OBJECT type, so let's call it NUMBER
dummy NUMBER,
-- Here's our function, and since PL/SQL doesn't have generics,
-- let's use type NUMBER for our params
MEMBER FUNCTION exec(n number) RETURN number
) NOT FINAL not instantiable;
/
-- Now let's inherit from that, defining a class with one method. We'll have ours square a number.
-- We can pass this class into any function that takes type callback:
CREATE OR REPLACE TYPE CB_SQUARE under callback (
OVERRIDING MEMBER FUNCTION exec(n NUMBER) RETURN NUMBER
)
/
CREATE OR REPLACE
TYPE BODY CB_SQUARE AS
OVERRIDING MEMBER FUNCTION exec(n NUMBER) RETURN NUMBER IS
BEGIN
RETURN n * n;
END exec;
END;
/
-- And a package to hold our test
CREATE OR REPLACE
PACKAGE PKG_CALLBACK AS
myCallback cb_square;
TYPE intTable IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
ints intTable;
i PLS_INTEGER;
procedure test_callback;
END PKG_CALLBACK;
/
CREATE OR REPLACE PACKAGE BODY PKG_CALLBACK AS
-- Our generic mapping function that takes a "method" and a collection
-- Note that it takes the generic callback type
-- that doesn't know anything about squaring
procedure do_callback(myCallback IN callback, ints IN OUT intTable) IS
i PLS_INTEGER;
myInt NUMBER;
begin
for i in 1 .. ints.count loop
myInt := ints(i);
-- PL/SQL call's the child's method
ints(i) := myCallback.exec(myInt);
END LOOP;
end do_callback;
procedure test_callback IS
BEGIN
myCallback := cb_square(null);
FOR i IN 1..5 LOOP
ints(i) := i;
END LOOP;
do_callback(myCallback, ints);
i := ints.FIRST;
WHILE i IS NOT NULL LOOP
DBMS_OUTPUT.put_line(ints(i));
i := ints.next(i);
END LOOP;
END test_callback;
END PKG_CALLBACK;
/
BEGIN
PKG_CALLBACK.TEST_CALLBACK();
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.
PostScript
The forall
operator applies a procedure to each element of an array, a packed array or a string.
[1 2 3 4 5] { dup mul = } forall
In this case the respective square numbers for the elements are printed.
To create a new array from the results above code can simply be wrapped in []
:
[ [1 2 3 4 5] { dup mul } forall ]
[1 2 3 4 5] {dup *} map
PowerShell
This can be done in PowerShell with the ForEach-Object
cmdlet which applies a scriptblock to each element of an array:
1..5 | ForEach-Object { $_ * $_ }
To recreate a map function, found in other languages the same method applies:
function map ([array] $a, [scriptblock] $s) {
$a | ForEach-Object $s
}
map (1..5) { $_ * $_ }
Prolog
Prolog doesn't have arrays, but we can do it with lists. This can be done in the console mode.
?- assert((fun(X, Y) :- Y is 2 * X)).
true.
?- maplist(fun, [1,2,3,4,5], L).
L = [2,4,6,8,10].
PureBasic
Procedure Cube(Array param.i(1))
Protected n.i
For n = 0 To ArraySize(param())
Debug Str(param(n)) + "^3 = " + Str(param(n) * param(n) * param(n))
Next
EndProcedure
Dim AnArray.i(4)
For n = 0 To ArraySize(AnArray())
AnArray(n) = Random(99)
Next
Cube(AnArray())
Python
def square(n):
return n * n
numbers = [1, 3, 5, 7]
squares1 = [square(n) for n in numbers] # list comprehension
squares2a = map(square, numbers) # functional form
squares2b = map(lambda x: x*x, numbers) # functional form with `lambda`
squares3 = [n * n for n in numbers] # no need for a function,
# anonymous or otherwise
isquares1 = (n * n for n in numbers) # iterator, lazy
import itertools
isquares2 = itertools.imap(square, numbers) # iterator, lazy
To print squares of integers in the range from 0 to 9, type:
print " ".join(str(n * n) for n in range(10))
Or:
print " ".join(map(str, map(square, range(10))))
Result:
0 1 4 9 16 25 36 49 64 81
QB64
'Task
'Take a combined set of elements and apply a function to each element.
'UDT
Type Friend
Names As String * 8
Surnames As String * 8
Age As Integer
End Type
Dim Friends(1 To 6) As Friend
Restore
FillArray
SearchForAdult Friends(), LBound(friends), UBound(friends)
End
Data "John","Beoz",13,"Will","Strange",22
Data "Arthur","Boile",16,"Peter","Smith",21
Data "Tom","Parker",14,"Tim","Wesson",24
Sub FillArray
Shared Friends() As Friend
Dim indeX As Integer
For indeX = LBound(friends) To UBound(friends) Step 1
Read Friends(indeX).Names, Friends(indeX).Surnames, Friends(indeX).Age
Next
End Sub
Sub SearchForAdult (F() As Friend, Min As Integer, Max As Integer)
Dim Index As Integer
Print "Friends with more than 18 years old"
For Index = Min To Max Step 1
If F(Index).Age > 18 Then Print F(Index).Names; " "; F(Index).Surnames; " "; F(Index).Age
Next Index
End Sub
Quackery
As a dialogue in the Quackery shell (REPL), applying the word cubed
to the nest [ 1 2 3 4 5 6 7 8 9 10 ]
, first treating the nest as a list, then as an array.
/O> [ 3 ** ] is cubed ( n --> n )
...
Stack empty.
/O> ' [ 1 2 3 4 5 6 7 8 9 10 ]
... [] swap witheach
... [ cubed join ]
...
Stack: [ 1 8 27 64 125 216 343 512 729 1000 ]
/O> drop
...
Stack empty.
/O> ' [ 1 2 3 4 5 6 7 8 9 10 ]
... dup witheach
... [ cubed swap i^ poke ]
...
Stack: [ 1 8 27 64 125 216 343 512 729 1000 ]
R
Many functions can take advantage of implicit vectorisation, e.g.
cube <- function(x) x*x*x
elements <- 1:5
cubes <- cube(elements)
Explicit looping over array elements is also possible.
cubes <- numeric(5)
for(i in seq_along(cubes))
{
cubes[i] <- cube(elements[i])
}
Loop syntax can often simplified using the *apply family of functions.
elements2 <- list(1,2,3,4,5)
cubes <- sapply(elements2, cube)
In each case above, the value of 'cubes' is
1 8 27 64 125
Racket
#lang racket
;; using the `for/vector' comprehension form
(for/vector ([i #(1 2 3 4 5)]) (sqr i))
;; the usual functional `map'
(vector-map sqr #(1 2 3 4 5))
Raku
(formerly Perl 6)
sub function { 2 * $^x + 3 };
my @array = 1 .. 5;
# via map function
.say for map &function, @array;
# via map method
.say for @array.map(&function);
# via for loop
for @array {
say function($_);
}
# via the "hyper" metaoperator and method indirection
say @array».&function;
# we neither need a variable for the array nor for the function
say [1,2,3]>>.&({ $^x + 1});
Raven
# To print the squared elements
[1 2 3 4 5] each dup * print
# To obtain a new array
group [1 2 3 4 5] each
dup *
list
REBOL
REBOL [
Title: "Array Callback"
URL: http://rosettacode.org/wiki/Apply_a_callback_to_an_Array
]
map: func [
"Apply a function across an array."
f [native! function!] "Function to apply to each element of array."
a [block!] "Array to process."
/local x
][x: copy [] forall a [append x do [f a/1]] x]
square: func [x][x * x]
; Tests:
assert: func [code][print [either do code [" ok"]["FAIL"] mold code]]
print "Simple loop, modify in place:"
assert [[1 100 81] = (a: [1 10 9] forall a [a/1: square a/1] a)]
print [crlf "Functional style with 'map':"]
assert [[4 16 36] = map :square [2 4 6]]
print [crlf "Applying native function with 'map':"]
assert [[2 4 6] = map :square-root [4 16 36]]
- Output:
Simple loop, modify in place: ok [[1 100 81] = (a: [1 100 81] forall a [a/1: square a/1] a)] Functional style with 'map': ok [[4 16 36] = map :square [2 4 6]] Applying native function with 'map': ok [[2 4 6] = map :square-root [4 16 36]]
Retro
Retro provides a variety of array words. Using these to multiply each value in an array by 10 and display the results:
{ #1 #2 #3 #4 #5 } [ #10 * ] a:map [ n:put sp ] a:for-each
REXX
/*REXX program applies a callback to an array (using factorials for a demonstration).*/
numeric digits 100 /*be able to display some huge numbers.*/
parse arg # . /*obtain an optional value from the CL.*/
a.= /*initialize the array A to all nulls*/
if #=='' | #=="," then #= 12 /*Not assigned? Then use default value*/
do j=0 to #; a.j= j /*assign the integer J ───► A.j */
end /*j*/ /*array A will have N values: 0 ──► #*/
call listA 'before callback' /*display A array before the callback*/
say /*display a blank line for readability.*/
say ' ··· applying callback to array A ···' /*display what is about to happen to B.*/
say /*display a blank line for readability.*/
call bangit 'a' /*factorialize (the values) of A array.*/
/* store the results ───► array B.*/
call listA ' after callback' /*display A array after the callback.*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
bangit: do v=0; $= value(arg(1)'.'v); if $=='' then return /*No value? Then return*/
call value arg(1)'.'v, fact($) /*assign a value (a factorial) to array*/
end /*i*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
fact: procedure; arg x; != 1; do f=2 to x; != !*f; end; /*f*/; return !
listA: do k=0 while a.k\==''; say arg(1) 'a.'k"=" a.k; end /*k*/; return
- output when using the default input:
before callback a.0= 0 before callback a.1= 1 before callback a.2= 2 before callback a.3= 3 before callback a.4= 4 before callback a.5= 5 before callback a.6= 6 before callback a.7= 7 before callback a.8= 8 before callback a.9= 9 before callback a.10= 10 before callback a.11= 11 before callback a.12= 12 ··· applying callback to array A ··· after callback a.0= 1 after callback a.1= 1 after callback a.2= 2 after callback a.3= 6 after callback a.4= 24 after callback a.5= 120 after callback a.6= 720 after callback a.7= 5040 after callback a.8= 40320 after callback a.9= 362880 after callback a.10= 3628800 after callback a.11= 39916800 after callback a.12= 479001600
Ring
for x in [1,2,3,4,5]
x = x*x
next
RLaB
RLaB has two type of arrays: 'standard' or 1-dimensional, that can be a row- or a column-vectory; and, 'associative' which are called lists. For standard array its entry identifier (index) is an integer in range 1:N where N is the size of the array. For associative array its entry identifier is a string consisting of printable ASCII characters.
All scalar mathematical functions are 'matrix-optimized' meaning that if the argument to a function is a matrix, then the return value of the function is a matrix of the same size as the input argument, where the function is applied to the individual entries of the matrix. Consider an example:
>> x = rand(2,4)
0.707213207 0.275298961 0.396757763 0.232312312
0.215619868 0.207078017 0.565700032 0.666090571
>> sin(x)
0.649717845 0.271834652 0.386430003 0.230228332
0.213952984 0.205601224 0.536006923 0.617916954
This can be done on entry-by-entry basis, but one has to keep in mind that the 'for' or 'while' loops are slow in interpreted languages, and RLaB is no exception.
x = rand(2,4);
y = zeros(2,4);
for (i in 1:2)
{
for (j in 1:4)
{
y[i;j] = sin( x[i;j] );
}
}
The functions can take lists as arguments, but then it has to be specified within the body
of the function what to do with the list elements. Given a list call it 'x' there is a RLaB
function 'members' which returns a string vector with the names of the elements of the list.
x = <<>>;
for (i in 1:9)
{
x.[i] = rand();
}
y = <<>>;
for (i in members(x))
{
y.[i] = sin( x.[i] );
}
RPL
≪ → array func ≪ array 0 CON 1 array SIZE FOR j j array j GET func EVAL PUT NEXT ≫ ≫ ´MAP’ STO
[1,2,3,4,5,6,7,8,9] ≪ SQ ≫ MAP
- Output:
1: [ 1 4 9 16 25 36 49 64 81 ]
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 }
Rust
fn echo(n: &i32) {
println!("{}", n);
}
fn main() {
let a: [i32; 5];
a = [1, 2, 3, 4, 5];
let _: Vec<_> = a.into_iter().map(echo).collect();
}
Salmon
These examples apply the square function to a list of the numbers from 0 through 9 to produce a new list of their squares, then iterate over the resulting list and print the squares.
function apply(list, ageless to_apply)
(comprehend(x; list) (to_apply(x)));
function square(x) (x*x);
iterate(x; apply([0...9], square))
x!;
With short identifiers:
include "short.salm";
fun apply(list, ageless to_apply)
(comp(x; list) (to_apply(x)));
fun square(x) (x*x);
iter(x; apply([0...9], square))
x!;
With the numbers given as a list of individual elements:
function apply(list, to_apply)
(comprehend(x; list) (to_apply(x)));
function square(x) (x*x);
iterate(x; apply([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], square))
x!;
Sather
class MAIN is
do_something(i:INT):INT is
return i * i;
end;
main is
a:ARRAY{INT} := |1, 2, 3, 4, 5|;
-- we use an anonymous closure to apply our do_something "callback"
a.map(bind(do_something(_)));
loop #OUT + a.elt! + "\n"; end;
end;
end;
Scala
val l = List(1,2,3,4)
l.foreach {i => println(i)}
When the argument appears only once -as here, i appears only one in println(i) - it may be shortened to
l.foreach(println(_))
Same for an array
val a = Array(1,2,3,4)
a.foreach {i => println(i)}
a.foreach(println(_)) '' // same as previous line''
Or for an externally defined function:
def doSomething(in: int) = {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 defined on a
for(val i <- a) 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} ''//squares is'' 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 (vector->list x))
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)))))
SenseTalk
put each item in [1,2,3,5,9,14,24] squared
put myFunc of each for each item of [1,2,3,5,9,14,24]
to handle myFunc of num
return 2*num + 1
end myFunc
Output:
(1,4,9,25,81,196,576)
(3,5,7,11,19,29,49)
Sidef
Defining a callback function:
func callback(i) { say i**2 }
The function will get called for each element:
[1,2,3,4].each(callback)
Same as above, but with the function inlined:
[1,2,3,4].each{|i| say i**2 }
For creating a new array, we can use the Array.map method:
[1,2,3,4,5].map{|i| i**2 }
Simula
BEGIN
! APPLIES A CALLBACK FUNCTION TO AN ARRAY ;
PROCEDURE APPLY(ARR, FUN);
REAL ARRAY ARR;
PROCEDURE FUN IS REAL PROCEDURE FUN(X); REAL X;;
BEGIN
INTEGER I;
FOR I := LOWERBOUND(ARR, 1) STEP 1 UNTIL UPPERBOUND(ARR, 1) DO
ARR(I) := FUN(ARR(I));
END APPLY;
! CALLBACK ;
REAL PROCEDURE SQUARE(X); REAL X; SQUARE := X * X;
REAL ARRAY A(1:5);
INTEGER I;
FOR I := 1 STEP 1 UNTIL 5 DO A(I) := I;
APPLY(A, SQUARE);
FOR I := 1 STEP 1 UNTIL 5 DO OUTFIX(A(I), 2, 8); OUTIMAGE;
END.
- Output:
1.00 4.00 9.00 16.00 25.00
Slate
#( 1 2 3 4 5 ) collect: [| :n | n * n].
Smalltalk
#( 1 2.0 'three') do: [:each | each displayNl].
You can tell symbols how to react to the value: message, and then write ²:
#( 1 2.0 'three') do: #displayNl.
2) actually most dialects already have it, and it is trivial to add, if it does not.
There is a huge number of additional enumeration messages implemented in Collection, from which Array inherits. Eg.:
#( 1 2 3 4 5 ) collect: [:n | n * n].
Sparkling
The foreach function calls the supplied callback on each element of the (possibly associative) array, passing it each key and the corresponding value:
let numbers = { 1, 2, 3, 4 };
foreach(numbers, function(idx, num) {
print(num);
});
The map function applies the transform to each key-value pair and constructs a new array, of which the keys are the keys of the original array, and the corresponding values are the return values of each call to the transform function:
let dict = { "foo": 42, "bar": 13, "baz": 37 };
let doubled = map(dict, function(key, val) {
return val * 2;
});
SQL PL
version 9.7 or higher.
With SQL PL:
--#SET TERMINATOR @
SET SERVEROUTPUT ON @
BEGIN
DECLARE TYPE NUMBERS AS SMALLINT ARRAY[5];
DECLARE NUMBERS NUMBERS;
DECLARE I SMALLINT;
SET I = 1;
WHILE (I <= 5) DO
SET NUMBERS[I] = I;
SET I = I + 1;
END WHILE;
BEGIN
DECLARE PROCEDURE PRINT_SQUARE (
IN VALUE SMALLINT
)
BEGIN
CALL DBMS_OUTPUT.PUT(VALUE * VALUE || ' ');
END;
SET I = 1;
WHILE (I <= 5) DO
CALL PRINT_SQUARE(NUMBERS[I]);
SET I = I + 1;
END WHILE;
CALL DBMS_OUTPUT.PUT_LINE('');
END;
END @
Output:
db2 -td@ db2 => BEGIN ... db2 (cont.) => END @ DB20000I The SQL command completed successfully. 1 4 9 16 25
Standard ML
map f l
i.e.
map (fn x=>x+1) [1,2,3];; (* [2,3,4] *)
Stata
There is no 'map' function in Mata, but it's easy to implement. Notice that you can only pass functions that are written in Mata, no builtin ones. For instance, the trigonometric functions (cos, sin) or the exponential are builtin. To pass a builtin function to another function, one needs to write a wrapper in Mata. See also Stata help about pointers and passing functions to functions. There are two versions of the function: one to return a numeric array, another to return a string array.
function map(f,a) {
nr = rows(a)
nc = cols(a)
b = J(nr,nc,.)
for (i=1;i<=nr;i++) {
for (j=1;j<=nc;j++) b[i,j] = (*f)(a[i,j])
}
return(b)
}
function maps(f,a) {
nr = rows(a)
nc = cols(a)
b = J(nr,nc,"")
for (i=1;i<=nr;i++) {
for (j=1;j<=nc;j++) b[i,j] = (*f)(a[i,j])
}
return(b)
}
function square(x) {
return(x*x)
}
Output
: map(&square(),(1,2,3\4,5,6)) 1 2 3 +----------------+ 1 | 1 4 9 | 2 | 16 25 36 | +----------------+
SuperCollider
Actually, there is a builtin squared operator:
[1, 2, 3].squared // returns [1, 4, 9]
Anything that is a Collection can be used with collect:
[1, 2, 3].collect { |x| x * x }
List comprehension combined with a higher-order function can also be used:
var square = { |x| x * x };
var map = { |fn, xs|
all {: fn.value(x), x <- xs };
};
map.value(square, [1, 2, 3]);
Swift
func square(n: Int) -> Int {
return n * n
}
let numbers = [1, 3, 5, 7]
let squares1a = numbers.map(square) // map method on array
let squares1b = numbers.map {x in x*x} // map method on array with anonymous function
let squares1b = numbers.map { $0 * $0 } // map method on array with anonymous function and unnamed parameters
let isquares1 = numbers.lazy.map(square) // lazy sequence
Tailspin
def numbers: [1,3,7,10];
templates cube
$ * $ * $ !
end cube
// Using inline array templates (which also allows access to index by $i)
$numbers -> \[i]($ * $i !\) -> !OUT::write
$numbers -> \[i]($ * $ !\) -> !OUT::write
$numbers -> \[i]($ -> cube !\) -> !OUT::write
// Using array literal and deconstructor
[ $numbers... -> $ * $ ] -> !OUT::write
[ $numbers... -> cube ] -> !OUT::write
Tcl
If I wanted to call "myfunc" on each element of dat and dat were a list:
foreach var $dat {
myfunc $var
}
This does not retain any of the values returned by myfunc.
if dat were an (associative) array, however:
foreach name [array names dat] {
myfunc $dat($name)
}
More functional, with a simple map
function:
proc map {f list} {
set res {}
foreach e $list {lappend res [$f $e]}
return $res
}
proc square x {expr {$x*$x}}
% map square {1 2 3 4 5}
1 4 9 16 25
TI-89 BASIC
© For no return value
Define foreach(fe_cname,fe_list) = Prgm
Local fe_i
For fe_i,1,dim(fe_list)
#fe_cname(fe_list[fe_i])
EndFor
EndPrgm
© For a list of results
Define map(map_cnam,map_list) = seq(#map_cnam(map_list[map_i]),map_i,1,dim(map_list))
Define callback(elem) = Prgm
Disp elem
EndPrgm
foreach("callback", {1,2,3,4,5})
Disp map("√", {1,2,3,4,5})
- Output:
TIScript
JavaScript alike:
var a = [1, 2, 3, 4, 5];
a.map(function(v) { return v * v; })
Using short form of lambda notation:
var a = [1, 2, 3, 4, 5];
a.map( :v: v*v );
Toka
( array count function -- )
{
value| array fn |
[ i array ] is I
[ to fn swap to array 0 swap [ I array.get :stack fn invoke I array.put ] countedLoop ]
} is map-array
( Build an array )
5 cells is-array a
10 0 a array.put
11 1 a array.put
12 2 a array.put
13 3 a array.put
14 4 a array.put
( Add 1 to each item in the array )
a 5 [ 1 + ] map-array
TorqueScript
--Elm 03:41, 18 June 2012 (UTC)
Callbacks:
function map(%array,%arrayCount,%function)
{
for(%i=0;%i<%arrayCount;%i++)
{
eval("%a = "@%array@"["@%i@"];");
eval(""@%function@"("@%a@");");
}
}
Now to set up an array:
$array[0] = "Hello.";
$array[1] = "Hi.";
$array[2] = "How are you?";
Now to call the function correctly:
map("$array",3,"echo");
Which should result in:
=> Hello.
=> Hi.
=> How are you?
TXR
Print 1 through 10 out of a vector, using prinl
the callback, right from the system shell command prompt:
$ txr -e '[mapdo prinl #(1 2 3 4 5 6 7 8 9 10)]'
1
2
3
4
5
6
7
8
9
10
mapdo
is like mapcar
but doesn't accumulate a list, suitable for imperative programming situations when the function is invoked to perform a side effect.
TXR extends Lisp list processing primitives to work with vectors and strings also, which is why mapdo
cheerfully traverses a vector.
uBasic/4tH
We cannot transfer the array address, since uBasic/4tH has only got one, but we can transfer the function pointer and size.
S = 5 ' Size of the array
For x = 0 To S - 1 ' Initialize array
@(x) = x + 1
Next
Proc _MapArray (_SquareRoot, S) ' Call mapping procedure
For x = 0 To S - 1 ' Print results
Print "SQRT(";x+1;") = ";Using "#.####";@(x)
Next
For x = 0 To S - 1 ' Reinitialize array
@(x) = x + 1
Next
Proc _MapArray (_Cosine, S) ' Call mapping procedure
Print : For x = 0 To S - 1 ' Print results
Print "COS(";x+1;") = ";Using "#.####";@(x)
Next
End
_MapArray Param(2) ' Param(1) = function
Local (1) ' Param(2) = array size
For c@ = 0 To b@ - 1
@(c@) = FUNC(a@(@(c@)))
Next
Return
_SquareRoot Param (1) ' This is an integer SQR subroutine
Local (2)
b@ = (10^(4*2)) * a@ ' Output is scaled by 10^4
a@ = b@
Do
c@ = (a@ + (b@ / a@))/2
Until (Abs(a@ - c@) < 2)
a@ = c@
Loop
Return (c@)
_Cosine Param(1) ' This is an integer COS subroutine
Push Abs((a@*10000)%62832) ' Output is scaled by 10^4
If Tos()>31416 Then Push 62832-Pop()
Let a@=Tos()>15708
If a@ Then Push 31416-Pop()
Push Tos()
Push (Pop()*Pop())/10000
Push 10000+((10000*-(Tos()/56))/10000)
Push 10000+((Pop()*-(Tos()/30))/10000)
Push 10000+((Pop()*-(Tos()/12))/10000)
Push 10000+((Pop()*-(Pop()/2))/10000)
If a@ Then Push -Pop() ' Result is directly transferred
Return ' through the stack
- Output:
SQRT(1) = 1.0000 SQRT(2) = 1.4142 SQRT(3) = 1.7320 SQRT(4) = 2.0000 SQRT(5) = 2.2360 COS(1) = 0.5403 COS(2) = -0.4162 COS(3) = -0.9901 COS(4) = -0.6537 COS(5) = 0.2837 0 OK, 0:514
UNIX Shell
map() {
map_command=$1
shift
for i do "$map_command" "$i"; done
}
list=1:2:3
(IFS=:; map echo $list)
map() {
typeset command=$1
shift
for i do "$command" "$i"; done
}
set -A ary 1 2 3
map print "${ary[@]}"
map(){for i ($*[2,-1]) $1 $i}
a=(1 2 3)
map print $a
Ursala
The * is a built-in map operator. This example shows a map of the successor function over a list of natural numbers.
#import nat
#cast %nL
demo = successor* <325,32,67,1,3,7,315>
- Output:
<326,33,68,2,4,8,316>
V
apply squaring (dup *) to each member of collection
[1 2 3 4] [dup *] map
VBA
Option Explicit
Sub Main()
Dim arr, i
'init
arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
'Loop and apply a function (Fibonacci) to each element
For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next
'return
Debug.Print Join(arr, ", ")
End Sub
Private Function Fibonacci(N) As Variant
If N <= 1 Then
Fibonacci = N
Else
Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)
End If
End Function
- Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
VBScript
I really have my doubts as to whether this really counts as a callback. I used the same thing in the solution to Amb.
Implementation
class callback
dim sRule
public property let rule( x )
sRule = x
end property
public default function applyTo(a)
dim p1
for i = lbound( a ) to ubound( a )
p1 = a( i )
a( i ) = eval( sRule )
next
applyTo = a
end function
end class
Invocation
dim a1
dim cb
set cb = new callback
cb.rule = "ucase(p1)"
a1 = split("my dog has fleas", " " )
cb.applyTo a1
wscript.echo join( a1, " " )
cb.rule = "p1 ^ p1"
a1 = array(1,2,3,4,5,6,7,8,9,10)
cb.applyto a1
wscript.echo join( a1, ", " )
- Output:
MY DOG HAS FLEAS 1, 4, 27, 256, 3125, 46656, 823543, 16777216, 387420489, 10000000000
Vim Script
map()
works with lists and dictionaries.
The second argument is an expression string where v:val
is replaced by the current value and v:key
by the current key (for lists the key is the index).
The result of evaluating the string will be the new value.
The list/dictionary is modified in place.
echo map([10, 20, 30], 'v:val * v:val')
echo map([10, 20, 30], '"Element " . v:key . " = " . v:val')
echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:val)')
echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:key)')
- Output:
[100, 400, 900] ['Element 0 = 10', 'Element 1 = 20', 'Element 2 = 30'] {'a': 'FOO', 'b': 'BAR', 'c': 'BAZ'} {'a': 'A', 'b': 'B', 'c': 'C'}
Visual Basic .NET
Compiler: >= Visual Studio 2008
The .NET framework has got us covered.
System.Array.ForEach(T(), Action(Of T)) maps a non-value-returning callback,
System.Linq.Enumerable.Select(Of TSource,TResult)(IEnumerable(Of TSource), Func(Of TSource, TResult)) provides a way to lazily map a function, resulting in an IEnumerable(Of T),
and System.Linq.Enumerable.ToArray(Of TSource)(IEnumerable(Of TSource)) eagerly converts the enumerable to an array.
Module Program
Function OneMoreThan(i As Integer) As Integer
Return i + 1
End Function
Sub Main()
Dim source As Integer() = {1, 2, 3}
' Create a delegate from an existing method.
Dim resultEnumerable1 = source.Select(AddressOf OneMoreThan)
' The above is just syntax sugar for this; extension methods can be called as if they were instance methods of the first parameter.
resultEnumerable1 = Enumerable.Select(source, AddressOf OneMoreThan)
' Or use an anonymous delegate.
Dim resultEnumerable2 = source.Select(Function(i) i + 1)
' The sequences are the same.
Console.WriteLine(Enumerable.SequenceEqual(resultEnumerable1, resultEnumerable2))
Dim resultArr As Integer() = resultEnumerable1.ToArray()
Array.ForEach(resultArr, AddressOf Console.WriteLine)
End Sub
End Module
- Output:
True 2 3 4
Vorpal
Given and array, A, and a function, F, mapping F over the elements of A is simple:
A.map(F)
If F takes 2 arguments, x and , then simply pass them to map. They will be passed to F when as it is applied to each element of A.
A.map(F, x, y)
Wart
map prn '(1 2 3 4 5)
- Output:
1 2 3 4 5
WDTE
let a => import 'arrays';
let s => import 'stream';
let example => [3; 5; 2];
let double => a.stream example
-> s.map (* 2)
-> s.collect
;
In WDTE, mapping can be accomplished using the stream
module. Streams are essentially lazy iterators. The arrays
module provides a function for creating a stream from an array, and then the stream
module's functions can be used to perform a map operation. collect
runs the iteration, collecting the elements yielded in a new array.
Wren
var arr = [1, 2, 3, 4, 5]
arr = arr.map { |x| x * 2 }.toList
arr = arr.map(Fn.new { |x| x / 2 }).toList
arr.each { |x| System.print(x) }
- Output:
1 2 3 4 5
XBS
func map(arr:array,callback:function){
set newArr:array = [];
foreach(k,v as arr){
newArr[k]=callback(v,k,arr);
}
send newArr;
}
set arr:array = [1,2,3,4,5];
set result:array = map(arr,func(v){
send v*2;
});
log(arr.join(", "));
log(result.join(", "));
- Output:
1, 2, 3, 4, 5 2, 4, 6, 8, 10
Yabasic
sub map(f$, t())
local i
for i = 1 to arraysize(t(), 1)
t(i) = execute(f$, t(i))
next i
end sub
sub add1(x)
return x + 1
end sub
sub square(x)
return x * x
end sub
dim t(10)
for i = 1 to 10
t(i) = i
print t(i), "\t";
next i
print
//map("add1", t())
map("square", t())
for i = 1 to 10
print t(i), "\t";
next i
print
Yacas
Sin /@ {1, 2, 3, 4}
MapSingle(Sin, {1,2,3,4})
MapSingle({{x}, x^2}, {1,2,3,4})
Z80 Assembly
Array:
byte &01,&02,&03,&04,&05
Array_End:
foo:
ld hl,Array
ld b,Array_End-Array ;ld b,5
bar:
inc (hl)
inc (hl)
inc (hl)
inc hl ;next entry in array
djnz bar
- Output:
The program above doesn't show the new values but here they are:
&04,&05,&06,&07,&08
Zig
pub fn main() !void {
var array = [_]i32{1, 2, 3};
apply(@TypeOf(array[0]), array[0..], func);
}
fn apply(comptime T: type, a: []T, f: fn(T) void) void {
for (a) |item| {
f(item);
}
}
fn func(a: i32) void {
const std = @import("std");
std.debug.print("{d}\n", .{a-1});
}
zkl
L(1,2,3,4,5).apply('+(5))
- Output:
L(6,7,8,9,10)
zonnon
module Main;
type
Callback = procedure (integer): integer;
Vector = array {math} * of integer;
procedure Power(i:integer):integer;
begin
return i*i;
end Power;
procedure Map(x: Vector;p: Callback): Vector;
var
i: integer;
r: Vector;
begin
r := new Vector(len(x));
for i := 0 to len(x) - 1 do
r[i] := p(i);
end;
return r
end Map;
procedure Write(x: Vector);
var
i: integer;
begin
for i := 0 to len(x) - 1 do
write(x[i]:4)
end;
writeln
end Write;
var
x,y: Vector;
begin
x := [1,2,3,4,5];
Write(Map(x,Power))
end Main.
- Output:
0 1 4 9 16
ZX Spectrum Basic
10 LET a$="x+x"
20 LET b$="x*x"
30 LET c$="x+x^2"
40 LET f$=c$: REM Assign a$, b$ or c$
150 FOR i=1 TO 5
160 READ x
170 PRINT x;" = ";VAL f$
180 NEXT i
190 STOP
200 DATA 2,5,6,10,100
- Iteration
- Programming Tasks
- Basic language learning
- 11l
- 6502 Assembly
- 68000 Assembly
- 8th
- ACL2
- ActionScript
- Ada
- Aime
- ALGOL 68
- ALGOL W
- APL
- AppleScript
- Arturo
- AutoHotkey
- AWK
- Babel
- BBC BASIC
- Binary Lambda Calculus
- BQN
- Bracmat
- Brat
- C
- C sharp
- C++
- STL
- Boost
- Clean
- Clio
- Clojure
- CLU
- COBOL
- CoffeeScript
- Common Lisp
- Component Pascal
- Crystal
- D
- Delphi
- Dyalect
- Déjà Vu
- E
- EchoLisp
- Efene
- EGL
- Elena
- Elixir
- Erlang
- ERRE
- Euphoria
- F Sharp
- Factor
- Fantom
- FBSL
- Fe
- Forth
- Fortran
- FP
- FreeBASIC
- Frink
- FunL
- Futhark
- FutureBasic
- Fōrmulæ
- GAP
- Go
- Groovy
- Haskell
- Guish
- Icon
- Unicon
- IDL
- Insitux
- Io
- J
- Jakt
- Java
- JavaScript
- Joy
- Jq
- Jsish
- Julia
- Kotlin
- Klingphix
- Lambdatalk
- Lang
- Lang5
- Langur
- Lasso
- Lisaac
- Logo
- Lua
- M2000 Interpreter
- M4
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Maxima
- Min
- Modula-3
- Nanoquery
- Nemerle
- NetLogo
- NewLISP
- NGS
- Nial
- Nim
- Nutt
- Oberon-2
- Objeck
- OCaml
- Octave
- Odin
- Oforth
- Ol
- OoRexx
- Order
- Oz
- PARI/GP
- Pascal
- PascalABC.NET
- Perl
- Phix
- Phix/basics
- Phixmonti
- PHP
- Picat
- PicoLisp
- Pike
- PL/I
- PL/SQL
- Pop11
- PostScript
- Initlib
- PowerShell
- Prolog
- PureBasic
- Python
- QB64
- Quackery
- R
- Racket
- Raku
- Raven
- REBOL
- Retro
- REXX
- Ring
- RLaB
- RPL
- Ruby
- Rust
- Salmon
- Sather
- Scala
- Scheme
- SenseTalk
- Sidef
- Simula
- Slate
- Smalltalk
- Sparkling
- SQL PL
- Standard ML
- Stata
- SuperCollider
- Swift
- Tailspin
- Tcl
- TI-89 BASIC
- TIScript
- Toka
- TorqueScript
- TXR
- UBasic/4tH
- UNIX Shell
- Ursala
- V
- VBA
- VBScript
- Vim Script
- Visual Basic .NET
- Vorpal
- Wart
- WDTE
- Wren
- XBS
- Yabasic
- Yacas
- Z80 Assembly
- Zig
- Zkl
- Zonnon
- ZX Spectrum Basic
- Gnuplot/Omit
- LaTeX/Omit
- Make/Omit
- NSIS/Omit
- PlainTeX/Omit
- Pages with too many expensive parser function calls