Apply a callback to an array: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 8: Line 8:
=={{header|11l}}==
=={{header|11l}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang 11l>V array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
<syntaxhighlight lang=11l>V array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
V arrsq = array.map(i -> i * i)
V arrsq = array.map(i -> i * i)
print(arrsq)</lang>
print(arrsq)</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>
Line 17: Line 17:
For this example, assume both the source array and the destination have a size of 86 elements (memory offsets base+0x00 to base+0x55.)
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.
This was implemented in easy6502.
<lang 6502asm>define SRC_LO $00
<syntaxhighlight lang=6502asm>define SRC_LO $00
define SRC_HI $01
define SRC_HI $01


Line 70: Line 70:
CLC
CLC
ADC temp ;2a + a = 3a
ADC temp ;2a + a = 3a
RTS</lang>
RTS</syntaxhighlight>




Line 87: Line 87:
{{trans|11l}}
{{trans|11l}}
The following assumes all code/data is stored/executed in RAM and is therefore mutable.
The following assumes all code/data is stored/executed in RAM and is therefore mutable.
<lang 68000devpac>LEA MyArray,A0
<syntaxhighlight lang=68000devpac>LEA MyArray,A0
MOVE.W #(MyArray_End-MyArray)-1,D7 ;Len(MyArray)-1
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,D0 ;sanitize D0-D2 to ensure nothing from any previous work will affect our math.
Line 104: Line 104:
MyArray:
MyArray:
DC.B 1,2,3,4,5,6,7,8,9,10
DC.B 1,2,3,4,5,6,7,8,9,10
MyArray_End:</lang>
MyArray_End:</syntaxhighlight>




=={{header|8th}}==
=={{header|8th}}==
The builtin word "a:map" does this:
The builtin word "a:map" does this:
<lang forth>
<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 120: Line 120:
ACL2 does not have first-class functions; this is close, however:
ACL2 does not have first-class functions; this is close, however:


<lang lisp>(defun apply-to-each (xs)
<syntaxhighlight lang=lisp>(defun apply-to-each (xs)
(if (endp xs)
(if (endp xs)
nil
nil
Line 128: Line 128:
(defun fn-to-apply (x)
(defun fn-to-apply (x)
(* x x))
(* x x))
</syntaxhighlight>
</lang>


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang actionscript>package
<syntaxhighlight lang=actionscript>package
{
{
public class ArrayCallback
public class ArrayCallback
Line 149: Line 149:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
{{works with|GNAT|GPL 2005}}
{{works with|GNAT|GPL 2005}}
<lang ada>with Ada.Text_Io;
<syntaxhighlight lang=ada>with Ada.Text_Io;
with Ada.Integer_text_IO;
with Ada.Integer_text_IO;
Line 189: Line 189:
begin
begin
Map(Sample, Display'access);
Map(Sample, Display'access);
end Call_Back_Example;</lang>
end Call_Back_Example;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>void
<syntaxhighlight lang=aime>void
map(list l, void (*fp)(object))
map(list l, void (*fp)(object))
{
{
Line 210: Line 210:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 217: 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}}
<lang algol68> PROC call back proc = (INT location, INT value)VOID:
<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 233: 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)
)</lang>
)</syntaxhighlight>


{{Out}}
{{Out}}
Line 244: Line 244:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang=algolw>begin
procedure printSquare ( integer value x ) ; writeon( i_w := 1, s_w := 0, " ", x * x );
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) %
% applys f to each element of a from lb to ub (inclusive) %
Line 255: Line 255:
applyI( printSquare, a, 1, 3 )
applyI( printSquare, a, 1, 3 )
end
end
end.</lang>
end.</syntaxhighlight>


=={{header|APL}}==
=={{header|APL}}==
By default functions in APL work on arrays as it is an array oriented language. Some examples:
By default functions in APL work on arrays as it is an array oriented language. Some examples:


<lang APL> - 1 2 3
<syntaxhighlight lang=APL> - 1 2 3
¯1 ¯2 ¯3
¯1 ¯2 ¯3
2 * 1 2 3 4
2 * 1 2 3 4
Line 270: Line 270:
81 243 729
81 243 729
2187 6561 19683
2187 6561 19683
</syntaxhighlight>
</lang>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
<lang applescript>on callback for arg
<syntaxhighlight lang=applescript>on callback for arg
-- Returns a string like "arc has 3 letters"
-- Returns a string like "arc has 3 letters"
arg & " has " & (count arg) & " letters"
arg & " has " & (count arg) & " letters"
Line 283: Line 283:
-- to callback, then speaks the return value.
-- to callback, then speaks the return value.
say (callback for aref)
say (callback for aref)
end repeat</lang>
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.
Line 290: Line 290:
For a more general implementation of '''map(function, list)''', '''foldl(function, startValue, list)''', and '''filter(predicate, list)''', we could write:
For a more general implementation of '''map(function, list)''', '''foldl(function, startValue, list)''', and '''filter(predicate, list)''', we could write:


<lang applescript>on run
<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}
Line 367: Line 367:
return lst
return lst
end tell
end tell
end map</lang>
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}}==
=={{header|Arturo}}==
<lang rebol>arr: [1 2 3 4 5]
<syntaxhighlight lang=rebol>arr: [1 2 3 4 5]


print map arr => [2*&]</lang>
print map arr => [2*&]</syntaxhighlight>
{{out}}
{{out}}
Line 381: Line 381:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>map("callback", "3,4,5")
<syntaxhighlight lang=AutoHotkey>map("callback", "3,4,5")


callback(array){
callback(array){
Line 390: Line 390:
map(callback, array){
map(callback, array){
%callback%(array)
%callback%(array)
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<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])}'
<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</lang>
3 9</syntaxhighlight>


=={{header|Babel}}==
=={{header|Babel}}==
Line 404: Line 404:
Let us define a squaring operator:
Let us define a squaring operator:


<lang babel>sq { dup * } <</lang>
<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:


<lang babel>( 0 1 1 2 3 5 8 13 21 34 ) { sq ! } over ! lsnum !</lang>
<syntaxhighlight lang=babel>( 0 1 1 2 3 5 8 13 21 34 ) { sq ! } over ! lsnum !</syntaxhighlight>


{{Out}}
{{Out}}
Line 415: Line 415:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> DIM a(4)
<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 431: Line 431:
NEXT
NEXT
ENDPROC
ENDPROC
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 442: Line 442:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>( ( callbackFunction1
<syntaxhighlight lang=bracmat>( ( callbackFunction1
= location value
= location value
. !arg:(?location,?value)
. !arg:(?location,?value)
Line 470: Line 470:
& mapar$(array,4,callbackFunction2)
& mapar$(array,4,callbackFunction2)
& mapar$(array,4,callbackFunction1)
& mapar$(array,4,callbackFunction1)
);</lang>
);</syntaxhighlight>
{{Out}}
{{Out}}
<pre>array[0] = 1
<pre>array[0] = 1
Line 483: Line 483:
=={{header|Brat}}==
=={{header|Brat}}==


<lang brat>#Print out each element in array
<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
}</lang>
}</syntaxhighlight>


Alternatively:
Alternatively:


<lang brat>[:a :b :c :d :e].each ->p</lang>
<syntaxhighlight lang=brat>[:a :b :c :d :e].each ->p</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==


'''callback.h'''
'''callback.h'''
<lang c>#ifndef CALLBACK_H
<syntaxhighlight lang=c>#ifndef CALLBACK_H
#define CALLBACK_H
#define CALLBACK_H


Line 510: Line 510:
void map(int* array, int len, void(*callback)(int,int));
void map(int* array, int len, void(*callback)(int,int));


#endif</lang>
#endif</syntaxhighlight>


'''callback.c'''
'''callback.c'''
<lang c>#include <stdio.h>
<syntaxhighlight lang=c>#include <stdio.h>
#include "callback.h"
#include "callback.h"


Line 539: Line 539:
map(array, 4, callbackFunction);
map(array, 4, callbackFunction);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{Out}}
{{Out}}
Line 553: Line 553:
This version uses the C# 3 lambda notation.
This version uses the C# 3 lambda notation.


<lang csharp>int[] intArray = { 1, 2, 3, 4, 5 };
<syntaxhighlight lang=csharp>int[] intArray = { 1, 2, 3, 4, 5 };
// Simplest method: LINQ, functional
// Simplest method: LINQ, functional
int[] squares1 = intArray.Select(x => x * x).ToArray();
int[] squares1 = intArray.Select(x => x * x).ToArray();
Line 563: Line 563:
// Or, if you only want to call a function on each element, just use foreach
// Or, if you only want to call a function on each element, just use foreach
foreach (var i in intArray)
foreach (var i in intArray)
Console.WriteLine(i * i);</lang>
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}}
<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;


static class Program
static class Program
Line 601: Line 601:
Console.WriteLine(value * value);
Console.WriteLine(value * value);
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 607: Line 607:
{{works with|g++|4.1.1}}
{{works with|g++|4.1.1}}
===C-Style Array===
===C-Style Array===
<lang cpp>#include <iostream> //cout for printing
<syntaxhighlight lang=cpp>#include <iostream> //cout for printing
#include <algorithm> //for_each defined here
#include <algorithm> //for_each defined here


Line 622: Line 622:
return 0;
return 0;
}
}
//prints 1 4 9 16 25</lang>
//prints 1 4 9 16 25</syntaxhighlight>


===std::vector===
===std::vector===
{{libheader|STL}}
{{libheader|STL}}
<lang cpp>#include <iostream> // cout for printing
<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 647: Line 647:
return 0;
return 0;
}
}
//prints 1 4 9 16 25</lang>
//prints 1 4 9 16 25</syntaxhighlight>


More tricky with binary function
More tricky with binary function
<lang cpp>#include <iostream> // cout for printing
<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 673: Line 673:
return 0;
return 0;
}
}
//prints 1x 2x 3x 4x 5x</lang>
//prints 1x 2x 3x 4x 5x</syntaxhighlight>


===Boost.Lambda===
===Boost.Lambda===
{{libheader|Boost}}
{{libheader|Boost}}
<lang cpp>using namespace std;
<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</lang>
transform(ary.begin(), ary.end(), ostream_iterator<int>(cout, " "), _1 * _1); // square and output</syntaxhighlight>


===C++11===
===C++11===
<lang cpp>#include <vector>
<syntaxhighlight lang=cpp>#include <vector>
#include <iostream>
#include <iostream>
#include <algorithm>
#include <algorithm>
Line 699: Line 699:
std::cout << std::endl;
std::cout << std::endl;
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|Clean}}==
=={{header|Clean}}==
Line 705: Line 705:
Define a function and an initial (unboxed) array.
Define a function and an initial (unboxed) array.


<lang clean>square x = x * x
<syntaxhighlight lang=clean>square x = x * x


values :: {#Int}
values :: {#Int}
values = {x \\ x <- [1 .. 10]}</lang>
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).


<lang clean>mapArray f array = {f x \\ x <-: array}</lang>
<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.


<lang clean>Start :: {#Int}
<syntaxhighlight lang=clean>Start :: {#Int}
Start = mapArray square values</lang>
Start = mapArray square values</syntaxhighlight>


=={{header|Clio}}==
=={{header|Clio}}==
'''Math operations'''
'''Math operations'''
<lang clio>[1 2 3 4] * 2 + 1 -> print</lang>
<syntaxhighlight lang=clio>[1 2 3 4] * 2 + 1 -> print</syntaxhighlight>
'''Quick functions'''
'''Quick functions'''
<lang>[1 2 3 4] -> * n: n * 2 + 1 -> print</lang>
<lang>[1 2 3 4] -> * n: n * 2 + 1 -> print</syntaxhighlight>
'''Anonymous function'''
'''Anonymous function'''
<lang clio>[1 2 3 4]
<syntaxhighlight lang=clio>[1 2 3 4]
-> * fn n:
-> * fn n:
n * 2 + 1
n * 2 + 1
-> print</lang>
-> print</syntaxhighlight>
'''Named function'''
'''Named function'''
<lang clio>fn double-plus-one n:
<syntaxhighlight lang=clio>fn double-plus-one n:
n * 2 + 1
n * 2 + 1


[1 2 3 4] -> * double-plus-one -> print</lang>
[1 2 3 4] -> * double-plus-one -> print</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==


<lang lisp>;; apply a named function, inc
<syntaxhighlight lang=lisp>;; apply a named function, inc
(map inc [1 2 3 4])</lang>
(map inc [1 2 3 4])</syntaxhighlight>


<lang lisp>;; apply a function
<syntaxhighlight lang=lisp>;; apply a function
(map (fn [x] (* x x)) [1 2 3 4])</lang>
(map (fn [x] (* x x)) [1 2 3 4])</syntaxhighlight>


<lang lisp>;; shortcut syntax for a function
<syntaxhighlight lang=lisp>;; shortcut syntax for a function
(map #(* % %) [1 2 3 4])</lang>
(map #(* % %) [1 2 3 4])</syntaxhighlight>


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>% This procedure will call a given procedure with each element
<syntaxhighlight lang=clu>% This procedure will call a given procedure with each element
% of the given array. Thanks to CLU's type parameterization,
% of the given array. Thanks to CLU's type parameterization,
% it will work for any type of element.
% it will work for any type of element.
Line 780: Line 780:
stream$putl(po, "\nStrings: ")
stream$putl(po, "\nStrings: ")
apply_to_all[string](strings, show_string)
apply_to_all[string](strings, show_string)
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>Ints:
<pre>Ints:
Line 799: Line 799:


Basic implementation of a map function:
Basic implementation of a map function:
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang=cobol> IDENTIFICATION DIVISION.
PROGRAM-ID. Map.
PROGRAM-ID. Map.


Line 821: Line 821:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang 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 835: Line 835:
Imperative: print 1, 2, 3, 4 and 5:
Imperative: print 1, 2, 3, 4 and 5:


<lang lisp>(map nil #'print #(1 2 3 4 5))</lang>
<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:


<lang lisp>(defun square (x) (* x x))
<syntaxhighlight lang=lisp>(defun square (x) (* x x))
(map 'vector #'square #(1 2 3 4 5))</lang>
(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*:


<lang lisp>(defvar *a* (vector 1 2 3))
<syntaxhighlight lang=lisp>(defvar *a* (vector 1 2 3))
(map-into *a* #'1+ *a*)</lang>
(map-into *a* #'1+ *a*)</syntaxhighlight>


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
BlackBox Component Builder
BlackBox Component Builder
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE Callback;
MODULE Callback;
IMPORT StdLog;
IMPORT StdLog;
Line 904: Line 904:
END Do;
END Do;
END Callback.
END Callback.
</syntaxhighlight>
</lang>
Execute: ^Q Callback.Do<br/>
Execute: ^Q Callback.Do<br/>
{{Out}}
{{Out}}
Line 933: Line 933:
=={{header|Crystal}}==
=={{header|Crystal}}==
Calling with a block
Calling with a block
<lang ruby>values = [1, 2, 3]
<syntaxhighlight lang=ruby>values = [1, 2, 3]


new_values = values.map do |number|
new_values = values.map do |number|
Line 939: Line 939:
end
end


puts new_values #=> [2, 4, 6]</lang>
puts new_values #=> [2, 4, 6]</syntaxhighlight>


Calling with a function/method
Calling with a function/method
<lang ruby>values = [1, 2, 3]
<syntaxhighlight lang=ruby>values = [1, 2, 3]


def double(number)
def double(number)
Line 953: Line 953:
new_values = values.map &->double(Int32)
new_values = values.map &->double(Int32)


puts new_values #=> [2, 4, 6]</lang>
puts new_values #=> [2, 4, 6]</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.algorithm;
<syntaxhighlight lang=d>import std.stdio, std.algorithm;


void main() {
void main() {
Line 962: Line 962:
auto m = items.map!(x => x + 5)();
auto m = items.map!(x => x + 5)();
writeln(m);
writeln(m);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[6, 7, 8, 9, 10]</pre>
<pre>[6, 7, 8, 9, 10]</pre>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>
<syntaxhighlight lang=Delphi>
// Declare the callback function
// Declare the callback function
procedure callback(const AInt:Integer);
procedure callback(const AInt:Integer);
Line 985: Line 985:
callback(myArray[i]);
callback(myArray[i]);
end.
end.
</syntaxhighlight>
</lang>


=={{header|Dyalect}}==
=={{header|Dyalect}}==


<lang Dyalect>func Array.Select(pred) {
<syntaxhighlight lang=Dyalect>func Array.Select(pred) {
let ys = []
let ys = []
for x in this when pred(x) {
for x in this when pred(x) {
Line 1,000: Line 1,000:
var squares = arr.Select(x => x * x)
var squares = arr.Select(x => x * x)
print(squares)</lang>
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.
<lang dejavu>!. map @++ [ 1 4 8 ]
<syntaxhighlight lang=dejavu>!. map @++ [ 1 4 8 ]


#implemented roughly like this:
#implemented roughly like this:
Line 1,011: Line 1,011:
# for i in lst:
# for i in lst:
# f i
# f i
# [</lang>
# [</syntaxhighlight>
{{out}}
{{out}}
<pre>[ 2 5 9 ]</pre>
<pre>[ 2 5 9 ]</pre>
Line 1,017: Line 1,017:
=={{header|E}}==
=={{header|E}}==


<lang e>def array := [1,2,3,4,5]
<syntaxhighlight lang=e>def array := [1,2,3,4,5]
def square(value) {
def square(value) {
return value * value
return value * value
}</lang>
}</syntaxhighlight>


Example of builtin iteration:
Example of builtin iteration:


<lang e>def callback(index, value) {
<syntaxhighlight lang=e>def callback(index, value) {
println(`Item $index is $value.`)
println(`Item $index is $value.`)
}
}
array.iterate(callback)</lang>
array.iterate(callback)</syntaxhighlight>


There is no built-in map function '''yet'''.
There is no built-in map function '''yet'''.
Line 1,033: Line 1,033:
returning a plain list (which is usually an array in implementation).
returning a plain list (which is usually an array in implementation).


<lang e>def map(func, collection) {
<syntaxhighlight lang=e>def map(func, collection) {
def output := [].diverge()
def output := [].diverge()
for item in collection {
for item in collection {
Line 1,040: Line 1,040:
return output.snapshot()
return output.snapshot()
}
}
println(map(square, array))</lang>
println(map(square, array))</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<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 1,055: Line 1,055:
v[2] = 4
v[2] = 4
→ #( 4 9 16)
→ #( 4 9 16)
</syntaxhighlight>
</lang>


=={{header|Efene}}==
=={{header|Efene}}==


<lang efene>square = fn (N) {
<syntaxhighlight lang=efene>square = fn (N) {
N * N
N * N
}
}
Line 1,091: Line 1,091:
io.format("squares3 : ~p~n", [squares3(Numbers)])
io.format("squares3 : ~p~n", [squares3(Numbers)])
}
}
</syntaxhighlight>
</lang>


=={{header|EGL}}==
=={{header|EGL}}==
<lang EGL>delegate callback( i int ) returns( int ) end
<syntaxhighlight lang=EGL>delegate callback( i int ) returns( int ) end


program ApplyCallbackToArray
program ApplyCallbackToArray
Line 1,113: Line 1,113:
return( i * i );
return( i * i );
end
end
end</lang>
end</syntaxhighlight>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<lang elena>import system'routines;
<syntaxhighlight lang=elena>import system'routines;


PrintSecondPower(n){ console.writeLine(n * n) }
PrintSecondPower(n){ console.writeLine(n * n) }
Line 1,124: Line 1,124:
{
{
new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.forEach:PrintSecondPower
new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.forEach:PrintSecondPower
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang Elixir>
<syntaxhighlight lang=Elixir>
Enum.map([1, 2, 3], fn(n) -> n * 2 end)
Enum.map([1, 2, 3], fn(n) -> n * 2 end)
Enum.map [1, 2, 3], &(&1 * 2)
Enum.map [1, 2, 3], &(&1 * 2)
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 1,140: Line 1,140:
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.


<lang Erlang>
<syntaxhighlight 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.
Line 1,150: Line 1,150:
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.


<lang Erlang>
<syntaxhighlight 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.


<lang Erlang>
<syntaxhighlight 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}}==
Line 1,192: Line 1,192:
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 1,200: Line 1,200:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>function apply_to_all(sequence s, integer f)
<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 1,217: Line 1,217:
-- 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}</lang>
-- 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.
Line 1,223: Line 1,223:
=={{header|F_Sharp|F#}}==
=={{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.
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
<syntaxhighlight lang=fsharp>let evenp x = x % 2 = 0
let result = Array.map evenp [| 1; 2; 3; 4; 5; 6 |]</lang>
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.
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>
<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.
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>
<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:
<lang factor>{ 1 2 3 4 } [ sq . ] each</lang>
<syntaxhighlight lang=factor>{ 1 2 3 4 } [ sq . ] each</syntaxhighlight>


Collect return values:
Collect return values:
<lang factor>{ 1 2 3 4 } [ sq ] map</lang>
<syntaxhighlight lang=factor>{ 1 2 3 4 } [ sq ] map</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Line 1,241: Line 1,241:
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.


<lang fantom>
<syntaxhighlight lang=fantom>
class Main
class Main
{
{
Line 1,251: Line 1,251:
}
}
}
}
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 1,265: Line 1,265:
=={{header|FBSL}}==
=={{header|FBSL}}==
'''User-defined mapping function:'''
'''User-defined mapping function:'''
<lang qbasic>#APPTYPE CONSOLE
<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,281: Line 1,281:
END FUNCTION
END FUNCTION


FUNCTION Add42(n): RETURN n + 42: END FUNCTION</lang>
FUNCTION Add42(n): RETURN n + 42: END FUNCTION</syntaxhighlight>
{{Out}}
{{Out}}
<pre>43 44 45
<pre>43 44 45
Line 1,287: Line 1,287:


'''Standard MAP() function:'''
'''Standard MAP() function:'''
<lang qbasic>#APPTYPE CONSOLE
<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,303: Line 1,303:
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</lang>
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,333: Line 1,333:
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.


<lang forth>: map ( addr n fn -- )
<syntaxhighlight lang=forth>: map ( addr n fn -- )
-rot cells bounds do i @ over execute i ! cell +loop ;</lang>
-rot cells bounds do i @ over execute i ! cell +loop ;</syntaxhighlight>


{{Out|Example usage}}
{{Out|Example usage}}
<lang forth>create data 1 , 2 , 3 , 4 , 5 ,
<syntaxhighlight lang=forth>create data 1 , 2 , 3 , 4 , 5 ,
data 5 ' 1+ map \ adds one to each element of data</lang>
data 5 ' 1+ map \ adds one to each element of data</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 1,344: Line 1,344:


{{Works with |Fortran|ISO 95 and later}}
{{Works with |Fortran|ISO 95 and later}}
<lang fortran>module arrCallback
<syntaxhighlight lang=fortran>module arrCallback
contains
contains
elemental function cube( x )
elemental function cube( x )
Line 1,352: Line 1,352:
cube = x * x * x
cube = x * x * x
end function cube
end function cube
end module arrCallback</lang>
end module arrCallback</syntaxhighlight>


<lang fortran>program testAC
<syntaxhighlight lang=fortran>program testAC
use arrCallback
use arrCallback
implicit none
implicit none
Line 1,370: Line 1,370:
write(*,*) b(i,:)
write(*,*) b(i,:)
end do
end do
end program testAC</lang>
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}}
<lang fortran> program test
<syntaxhighlight lang=fortran> program test
C
C
C-- Declare array:
C-- Declare array:
Line 1,386: Line 1,386:
end do
end do
C
C
end</lang>
end</syntaxhighlight>


=={{header|FP}}==
=={{header|FP}}==
<lang fp>{square * . [id, id]}
<syntaxhighlight lang=fp>{square * . [id, id]}
& square: <1,2,3,4,5></lang>
& square: <1,2,3,4,5></syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang=freebasic>' FB 1.05.0 Win64


Sub PrintEx(n As Integer)
Sub PrintEx(n As Integer)
Line 1,411: Line 1,411:
Print
Print
Print "Press any key to quit the program"
Print "Press any key to quit the program"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,430: Line 1,430:


=={{header|Frink}}==
=={{header|Frink}}==
<lang 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|FunL}}==
=={{header|FunL}}==
<lang funl>[1, 2, 3].foreach( println )
<syntaxhighlight lang=funl>[1, 2, 3].foreach( println )


[1, 2, 3].foreach( a -> println(2a) )</lang>
[1, 2, 3].foreach( a -> println(2a) )</syntaxhighlight>


{{out}}
{{out}}
Line 1,453: Line 1,453:


=={{header|Futhark}}==
=={{header|Futhark}}==
<lang Futhark>
<syntaxhighlight lang=Futhark>
map f l
map f l
</syntaxhighlight>
</lang>
e.g.
e.g.
<lang Futhark>
<syntaxhighlight lang=Futhark>
map (\x->x+1) [1,2,3] -- [2,3,4]
map (\x->x+1) [1,2,3] -- [2,3,4]
</syntaxhighlight>
</lang>
or equivalently
or equivalently
<lang Futhark>
<syntaxhighlight lang=Futhark>
map (+1) [1,2,3] -- [2,3,4]
map (+1) [1,2,3] -- [2,3,4]
</syntaxhighlight>
</lang>


=={{header|Fōrmulæ}}==
=={{header|Fōrmulæ}}==
Line 1,474: Line 1,474:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>a := [1 .. 4];
<syntaxhighlight lang=gap>a := [1 .. 4];
b := ShallowCopy(a);
b := ShallowCopy(a);


Line 1,494: Line 1,494:


b;
b;
# [ 1 .. 4 ]</lang>
# [ 1 .. 4 ]</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
Line 1,501: Line 1,501:


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:
<lang go>package main
<syntaxhighlight lang=go>package main


import "fmt"
import "fmt"
Line 1,509: Line 1,509:
fmt.Println(i * i)
fmt.Println(i * i)
}
}
}</lang>
}</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.
<lang go>package main
<syntaxhighlight lang=go>package main


import "fmt"
import "fmt"
Line 1,542: Line 1,542:
return i * i
return i * i
}))
}))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,556: Line 1,556:


Print each value in a list
Print each value in a list
<lang groovy>[1,2,3,4].each { println it }</lang>
<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
<lang groovy>[1,2,3,4].collect { it * it }</lang>
<syntaxhighlight lang=groovy>[1,2,3,4].collect { it * it }</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
Line 1,565: Line 1,565:
===List===
===List===
{{works with|GHC}}
{{works with|GHC}}
<lang haskell>let square x = x*x
<syntaxhighlight lang=haskell>let square x = x*x
let values = [1..10]
let values = [1..10]
map square values</lang>
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
<lang haskell>[square x | x <- values]</lang>
<syntaxhighlight lang=haskell>[square x | x <- values]</syntaxhighlight>


More directly
More directly
<lang haskell>[1 .. 10] >>= pure . (^ 2)</lang>
<syntaxhighlight lang=haskell>[1 .. 10] >>= pure . (^ 2)</syntaxhighlight>


Or with one less layer of monadic wrapping
Or with one less layer of monadic wrapping
<lang haskell>(^ 2) <$> [1..10]</lang>
<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
<lang haskell>let printSquares = mapM_ (print.square)
<syntaxhighlight lang=haskell>let printSquares = mapM_ (print.square)
printSquares values</lang>
printSquares values</syntaxhighlight>


===Array===
===Array===
{{works with|GHC|7.10.3}}
{{works with|GHC|7.10.3}}
<lang haskell>import Data.Array (Array, listArray)
<syntaxhighlight lang=haskell>import Data.Array (Array, listArray)


square :: Int -> Int
square :: Int -> Int
Line 1,593: Line 1,593:


main :: IO ()
main :: IO ()
main = print $ fmap square values</lang>
main = print $ fmap square values</syntaxhighlight>
{{Out}}
{{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>
<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|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang icon>procedure main()
<syntaxhighlight lang=icon>procedure main()
local lst
local lst
lst := [10, 20, 30, 40]
lst := [10, 20, 30, 40]
Line 1,606: Line 1,606:
procedure callback(p,arg)
procedure callback(p,arg)
return p(" -> ", arg)
return p(" -> ", arg)
end</lang>
end</syntaxhighlight>


=={{header|IDL}}==
=={{header|IDL}}==
Line 1,612: Line 1,612:
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


<lang idl>b = a^3</lang>
<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|Io}}==
=={{header|Io}}==
<lang io>list(1,2,3,4,5) map(squared)</lang>
<syntaxhighlight lang=io>list(1,2,3,4,5) map(squared)</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==


'''Solution''':
'''Solution''':
<lang j> "_1</lang>
<syntaxhighlight lang=j> "_1</syntaxhighlight>


'''Example''':
'''Example''':
<lang j> callback =: *:
<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</lang>
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.
Line 1,639: Line 1,639:
while the <code>IntToInt</code> is used to replace the array values.
while the <code>IntToInt</code> is used to replace the array values.


<lang java>public class ArrayCallback7 {
<syntaxhighlight lang=java>public class ArrayCallback7 {


interface IntConsumer {
interface IntConsumer {
Line 1,683: Line 1,683:
});
});
}
}
}</lang>
}</syntaxhighlight>


Using Java 8 streams:
Using Java 8 streams:
{{works with|Java|8}}
{{works with|Java|8}}


<lang java>import java.util.Arrays;
<syntaxhighlight lang=java>import java.util.Arrays;


public class ArrayCallback {
public class ArrayCallback {
Line 1,704: Line 1,704:
System.out.println("sum: " + sum);
System.out.println("sum: " + sum);
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==


===ES3===
===ES3===
<lang javascript>function map(a, func) {
<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,717: Line 1,717:
}
}


map([1, 2, 3, 4, 5], function(v) { return v * v; });</lang>
map([1, 2, 3, 4, 5], function(v) { return v * v; });</syntaxhighlight>


===ES5===
===ES5===
<lang javascript>[1, 2, 3, 4, 5].map(function(v) { return v * v; });</lang>
<syntaxhighlight lang=javascript>[1, 2, 3, 4, 5].map(function(v) { return v * v; });</syntaxhighlight>


===ES6===
===ES6===
<lang javascript>[1, 2, 3, 4, 5].map(v => v * v);</lang>
<syntaxhighlight lang=javascript>[1, 2, 3, 4, 5].map(v => v * v);</syntaxhighlight>


The result is always:
The result is always:
Line 1,730: Line 1,730:


=={{header|Joy}}==
=={{header|Joy}}==
<lang joy>[1 2 3 4 5] [dup *] map.</lang>
<syntaxhighlight lang=joy>[1 2 3 4 5] [dup *] map.</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
<lang jq># Illustration of map/1 using the builtin filter: exp
<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,747: Line 1,747:
# Elementwise operation
# Elementwise operation
[.[] + 1 ] # add 1 to each element of the input array
[.[] + 1 ] # add 1 to each element of the input array
</lang>Here is a transcript illustrating how the last of these jq expressions can be evaluated:
</syntaxhighlight>Here is a transcript illustrating how the last of these jq expressions can be evaluated:
<lang jq>$ jq -c ' [.[] + 1 ]'
<syntaxhighlight lang=jq>$ jq -c ' [.[] + 1 ]'
[0, 1 , 10]
[0, 1 , 10]
[1,2,11]</lang>
[1,2,11]</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>/* Apply callback, in Jsish using array.map() */
<syntaxhighlight lang=javascript>/* Apply callback, in Jsish using array.map() */
;[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; });
;[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; });


Line 1,760: Line 1,760:
[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; }) ==> [ 1, 4, 9, 16, 25 ]
[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; }) ==> [ 1, 4, 9, 16, 25 ]
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 1,768: Line 1,768:
=={{header|Julia}}==
=={{header|Julia}}==
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}
<lang julia>numbers = [1, 3, 5, 7]
<syntaxhighlight lang=julia>numbers = [1, 3, 5, 7]


@show [n ^ 2 for n in numbers] # list comprehension
@show [n ^ 2 for n in numbers] # list comprehension
Line 1,775: Line 1,775:
@show [n * n for n in numbers] # no need for a function,
@show [n * n for n in numbers] # no need for a function,
@show numbers .* numbers # element-wise operation
@show numbers .* numbers # element-wise operation
@show numbers .^ 2 # includes .+, .-, ./, comparison, and bitwise operations as well</lang>
@show numbers .^ 2 # includes .+, .-, ./, comparison, and bitwise operations as well</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>fun main(args: Array<String>) {
<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
}</lang>
}</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}}==
=={{header|Klingphix}}==
<lang Klingphix>include ..\Utilitys.tlhy
<syntaxhighlight lang=Klingphix>include ..\Utilitys.tlhy


( 1 2 3 4 ) [dup *] map
( 1 2 3 4 ) [dup *] map
Line 1,794: Line 1,794:
pstack
pstack


" " input</lang>
" " input</syntaxhighlight>
{{out}}
{{out}}
<pre>((1, 4, 9, 16))</pre>
<pre>((1, 4, 9, 16))</pre>


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang Scheme>
<syntaxhighlight lang=Scheme>
{A.map {lambda {:x} {* :x :x}} {A.new 1 2 3 4 5 6 7 8 9 10}}
{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]
-> [1,4,9,16,25,36,49,64,81,100]
</syntaxhighlight>
</lang>


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang lang5>: square(*) dup * ;
<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" .</lang>
[1 2 3 4 5] 'square apply . "\n" .</syntaxhighlight>


=={{header|langur}}==
=={{header|langur}}==
<lang langur>writeln map f{^2}, 1..10</lang>
<syntaxhighlight lang=langur>writeln map f{^2}, 1..10</syntaxhighlight>


{{out}}
{{out}}
Line 1,816: Line 1,816:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>define cube(n::integer) => #n*#n*#n
<syntaxhighlight lang=Lasso>define cube(n::integer) => #n*#n*#n


local(
local(
Line 1,827: Line 1,827:
}
}


#mycube</lang>
#mycube</syntaxhighlight>
-> array(1, 8, 27, 64, 125)
-> array(1, 8, 27, 64, 125)


=={{header|Lisaac}}==
=={{header|Lisaac}}==
<lang Lisaac>+ a : ARRAY(INTEGER);
<syntaxhighlight lang=Lisaac>+ a : ARRAY(INTEGER);
+ b : {INTEGER;};
+ b : {INTEGER;};


Line 1,844: Line 1,844:
};
};


a.foreach b;</lang>
a.foreach b;</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to square :x
<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</lang>
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:
<lang lua>myArray = {1, 2, 3, 4, 5}</lang>
<syntaxhighlight lang=lua>myArray = {1, 2, 3, 4, 5}</syntaxhighlight>
A map function for this would be
A map function for this would be
<lang lua>map = function(f, data)
<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,865: Line 1,865:
end
end
return result
return result
end</lang>
end</syntaxhighlight>
Together with our array and a square function this yields:
Together with our array and a square function this yields:
<lang lua>myFunc = function(x) return x*x end
<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</lang>
--> 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,
Line 1,876: Line 1,876:


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<lang M2000 Interpreter>
<syntaxhighlight lang=M2000 Interpreter>
a=(1,2,3,4,5)
a=(1,2,3,4,5)
b=lambda->{
b=lambda->{
Line 1,904: Line 1,904:
Print s=>sum=115
Print s=>sum=115


</syntaxhighlight>
</lang>


=={{header|M4}}==
=={{header|M4}}==
<lang M4>define(`foreach', `pushdef(`$1')_foreach($@)popdef(`$1')')dnl
<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,915: Line 1,915:
dnl
dnl
define(`z',`eval(`$1*2') ')dnl
define(`z',`eval(`$1*2') ')dnl
apply(`(1,2,3)',`z')</lang>
apply(`(1,2,3)',`z')</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,925: Line 1,925:
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.
<lang Maple>
<syntaxhighlight 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,937: Line 1,937:
> (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.
<lang Maple>
<syntaxhighlight 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,954: Line 1,954:
> 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.
<lang Maple>
<syntaxhighlight lang=Maple>
> map[inplace]( sqrt, a );
> map[inplace]( sqrt, a );
[1.048808848, 1.788854382, 2.387467277]
[1.048808848, 1.788854382, 2.387467277]
Line 1,962: Line 1,962:
> 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.
<lang Maple>
<syntaxhighlight 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.
<lang Maple>
<syntaxhighlight lang=Maple>
> map2( `-`, 5, [ 1, 2, 3 ] );
> map2( `-`, 5, [ 1, 2, 3 ] );
[4, 3, 2]
[4, 3, 2]
Line 1,977: Line 1,977:
> 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}}//{{header|Wolfram Language}}==
=={{header|Mathematica}}//{{header|Wolfram Language}}==
<lang Mathematica>(#*#)& /@ {1, 2, 3, 4}
<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}]</lang>
Map[Function[w,w*w],{1,2,3,4}]</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
Line 1,989: Line 1,989:
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.
<lang MATLAB>>> array = [1 2 3 4 5]
<syntaxhighlight lang=MATLAB>>> array = [1 2 3 4 5]


array =
array =
Line 2,023: Line 2,023:
Column 5
Column 5


-3.380515006246586</lang>
-3.380515006246586</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>/* for lists or sets */
<syntaxhighlight lang=maxima>/* for lists or sets */


map(sin, [1, 2, 3, 4]);
map(sin, [1, 2, 3, 4]);
Line 2,033: Line 2,033:
/* for matrices */
/* for matrices */


matrixmap(sin, matrix([1, 2], [2, 4]));</lang>
matrixmap(sin, matrix([1, 2], [2, 4]));</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>(1 2 3 4 5) (sqrt puts) foreach ; print each square root
<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</lang>
(1 2 3 4 5) 'sqrt map ; collect return values</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>MODULE Callback EXPORTS Main;
<syntaxhighlight lang=modula3>MODULE Callback EXPORTS Main;


IMPORT IO, Fmt;
IMPORT IO, Fmt;
Line 2,066: Line 2,066:
BEGIN
BEGIN
Map(sample, NUMBER(sample), callback);
Map(sample, NUMBER(sample), callback);
END Callback.</lang>
END Callback.</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>// create a list of numbers 1-10
<syntaxhighlight lang=Nanoquery>// create a list of numbers 1-10
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Line 2,081: Line 2,081:
// display the squared list
// display the squared list
println numbers</lang>
println numbers</syntaxhighlight>
{{out}}
{{out}}
<pre>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
<pre>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Line 2,088: Line 2,088:
=={{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).
<lang Nemerle>def seg = array[1, 2, 3, 5, 8, 13];
<syntaxhighlight lang=Nemerle>def seg = array[1, 2, 3, 5, 8, 13];
def squares = seq.Map(x => x*x);</lang>
def squares = seq.Map(x => x*x);</syntaxhighlight>


=={{header|NetLogo}}==
=={{header|NetLogo}}==
<lang NetLogo>
<syntaxhighlight lang=NetLogo>
;; NetLogo “anonymous procedures”
;; NetLogo “anonymous procedures”
;; stored in a variable, just to show it can be done.
;; stored in a variable, just to show it can be done.
let callback [ [ x ] x * x ]
let callback [ [ x ] x * x ]
show (map callback [ 1 2 3 4 5 ])
show (map callback [ 1 2 3 4 5 ])
</syntaxhighlight>
</lang>


=={{header|NewLISP}}==
=={{header|NewLISP}}==


<lang NewLISP>> (map (fn (x) (* x x)) '(1 2 3 4))
<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}}==
<lang NGS>{
<syntaxhighlight lang=NGS>{
[1, 2, 3, 4, 5].map(F(x) x*x)
[1, 2, 3, 4, 5].map(F(x) x*x)
}</lang>
}</syntaxhighlight>


=={{header|Nial}}==
=={{header|Nial}}==


<lang nial>each (* [first, first] ) 1 2 3 4
<syntaxhighlight lang=nial>each (* [first, first] ) 1 2 3 4
=1 4 9 16</lang>
=1 4 9 16</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==


<lang nim>var arr = @[1,2,3,4]
<syntaxhighlight lang=nim>var arr = @[1,2,3,4]
arr.apply proc(some: var int) = echo(some, " squared = ", some*some)</lang>
arr.apply proc(some: var int) = echo(some, " squared = ", some*some)</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,128: Line 2,128:
=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
{{Works with|oo2x}}
{{Works with|oo2x}}
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE ApplyCallBack;
MODULE ApplyCallBack;
IMPORT
IMPORT
Line 2,217: Line 2,217:
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 2,226: Line 2,226:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang=objeck>
use Structure;
use Structure;


Line 2,248: Line 2,248:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
This function is part of the standard library:
This function is part of the standard library:


<lang ocaml>Array.map</lang>
<syntaxhighlight lang=ocaml>Array.map</syntaxhighlight>


Usage example:
Usage example:
<lang ocaml>let square x = x * x;;
<syntaxhighlight lang=ocaml>let square x = x * x;;
let values = Array.init 10 ((+) 1);;
let values = Array.init 10 ((+) 1);;
Array.map square values;;</lang>
Array.map square values;;</syntaxhighlight>


Or with lists (which are more typical in OCaml):
Or with lists (which are more typical in OCaml):
<lang ocaml>let values = [1;2;3;4;5;6;7;8;9;10];;
<syntaxhighlight lang=ocaml>let values = [1;2;3;4;5;6;7;8;9;10];;
List.map square values;;</lang>
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.


<lang ocaml>Array.iter (fun x -> Printf.printf "%d" x) [|1; 2; 3; 4; 5|];;</lang>
<syntaxhighlight lang=ocaml>Array.iter (fun x -> Printf.printf "%d" x) [|1; 2; 3; 4; 5|];;</syntaxhighlight>
<lang ocaml>List.iter (fun x -> Printf.printf "%d" x) [1; 2; 3; 4; 5];;</lang>
<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:


<lang ocaml>Array.iter (Printf.printf "%d") [|1; 2; 3; 4; 5|];;</lang>
<syntaxhighlight lang=ocaml>Array.iter (Printf.printf "%d") [|1; 2; 3; 4; 5|];;</syntaxhighlight>
<lang ocaml>List.iter (Printf.printf "%d") [1; 2; 3; 4; 5];;</lang>
<syntaxhighlight lang=ocaml>List.iter (Printf.printf "%d") [1; 2; 3; 4; 5];;</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==
Line 2,278: Line 2,278:
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.


<lang octave>function e = f(x, y)
<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 2,284: Line 2,284:
% 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</lang>
% 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>)
Line 2,290: Line 2,290:
=={{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 Oforth>0 #+ [ 1, 2, 3, 4, 5 ] apply</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 :
<lang Oforth>#sq [ 1, 2, 3, 4, 5 ] map</lang>
<syntaxhighlight lang=Oforth>#sq [ 1, 2, 3, 4, 5 ] map</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
Apply custom callback (lambda) to every element of list.
Apply custom callback (lambda) to every element of list.
<lang scheme>
<syntaxhighlight lang=scheme>
(for-each
(for-each
(lambda (element)
(lambda (element)
Line 2,303: Line 2,303:
'(1 2 3 4 5))
'(1 2 3 4 5))
; ==> 12345
; ==> 12345
</syntaxhighlight>
</lang>


=={{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.
<lang ooRexx>start = .array~of("Rick", "Mike", "David", "Mark")
<syntaxhighlight 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 2,330: Line 2,330:
use arg string
use arg string
say string
say string
return .true -- called as a function, so a result is required</lang>
return .true -- called as a function, so a result is required</syntaxhighlight>
{{out}}
{{out}}
<pre>kciR
<pre>kciR
Line 2,339: Line 2,339:
=={{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>.
<lang c>#include <order/interpreter.h>
<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 2,348: Line 2,348:


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</lang>
// prints 1,2,3,4,5, and returns 8nil</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang=oz>declare
fun{Square A}
fun{Square A}
A*A
A*A
Line 2,363: Line 2,363:
%% apply a FUNCTION to every element
%% apply a FUNCTION to every element
Result = {Map Lst Square}
Result = {Map Lst Square}
{Show Result}</lang>
{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}}
<lang parigp>callback(n)=n+n;
<syntaxhighlight lang=parigp>callback(n)=n+n;
apply(callback, [1,2,3,4,5])</lang>
apply(callback, [1,2,3,4,5])</syntaxhighlight>


This should be contrasted with <code>call</code>:
This should be contrasted with <code>call</code>:
<lang parigp>call(callback, [1,2,3,4,5])</lang>
<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>.


Line 2,378: Line 2,378:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl># create array
<syntaxhighlight lang=perl># create array
my @a = (1, 2, 3, 4, 5);
my @a = (1, 2, 3, 4, 5);


Line 2,407: Line 2,407:


# filter an array
# filter an array
my @e = grep { $_ % 2 == 0 } @a; # @e is now (2, 4)</lang>
my @e = grep { $_ % 2 == 0 } @a; # @e is now (2, 4)</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
<!--<lang Phix>(phixonline)-->
<!--<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: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"0.8.2"</span><span style="color: #0000FF;">)</span>
Line 2,419: Line 2,419:
<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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,433: Line 2,433:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>/# Rosetta Code problem: http://rosettacode.org/wiki/Apply_a_callback_to_an_array
<syntaxhighlight lang=Phixmonti>/# Rosetta Code problem: http://rosettacode.org/wiki/Apply_a_callback_to_an_array
by Galileo, 05/2022 #/
by Galileo, 05/2022 #/


Line 2,451: Line 2,451:
getid square map
getid square map


pstack</lang>
pstack</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,459: Line 2,459:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>function cube($n)
<syntaxhighlight lang=php>function cube($n)
{
{
return($n * $n * $n);
return($n * $n * $n);
Line 2,466: Line 2,466:
$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);</lang>
print_r($b);</syntaxhighlight>


=={{header|Picat}}==
=={{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.
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.
There are - however - quite a few ways without proper lambdas, using map/2, apply/2, or list comprehensions.
<lang Picat>go =>
<syntaxhighlight lang=Picat>go =>
L = 1..10,
L = 1..10,


Line 2,491: Line 2,491:
% Some function
% Some function
fun(X) = X*X.
fun(X) = X*X.
</syntaxhighlight>
</lang>


{{trans|Prolog}}
{{trans|Prolog}}
Line 2,499: Line 2,499:


Note that fun2/2 is not a function so map/2 or apply/2 cannot be used here.
Note that fun2/2 is not a function so map/2 or apply/2 cannot be used here.
<lang Picat>go2 =>
<syntaxhighlight lang=Picat>go2 =>
L = 1..10,
L = 1..10,


Line 2,508: Line 2,508:
println([B : A in L, bp.fun2(A,B)]),
println([B : A in L, bp.fun2(A,B)]),
nl.
nl.
</syntaxhighlight>
</lang>


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.
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}}==
<lang PicoLisp>: (mapc println (1 2 3 4 5)) # Print numbers
<syntaxhighlight lang=PicoLisp>: (mapc println (1 2 3 4 5)) # Print numbers
1
1
2
2
Line 2,528: Line 2,528:


: (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)</lang>
-> (1 6 3 8)</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang pike>int cube(int n)
<syntaxhighlight lang=pike>int cube(int n)
{
{
return n*n*n;
return n*n*n;
Line 2,538: Line 2,538:
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</lang>
array(int) c = map(a, cube); // conventional map function</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I> declare x(5) initial (1,3,5,7,8);
<syntaxhighlight lang=PL/I> declare x(5) initial (1,3,5,7,8);
x = sqrt(x);
x = sqrt(x);
x = sin(x);</lang>
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.
<lang plsql>-- Let's create a generic class with one method to be used as an interface:
<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,622: Line 2,622:
PKG_CALLBACK.TEST_CALLBACK();
PKG_CALLBACK.TEST_CALLBACK();
END;
END;
/</lang>
/</syntaxhighlight>


=={{header|Pop11}}==
=={{header|Pop11}}==


<lang pop11>;;; Define a procedure
<syntaxhighlight lang=pop11>;;; Define a procedure
define proc(x);
define proc(x);
printf(x*x, '%p,');
printf(x*x, '%p,');
Line 2,635: Line 2,635:


;;; Apply procedure to array
;;; Apply procedure to array
appdata(ar, proc);</lang>
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,641: Line 2,641:
=={{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.
<lang postscript>[1 2 3 4 5] { dup mul = } forall</lang>
<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>:
<lang postscript>[ [1 2 3 4 5] { dup mul } forall ]</lang>
<syntaxhighlight lang=postscript>[ [1 2 3 4 5] { dup mul } forall ]</syntaxhighlight>


{{libheader|initlib}}
{{libheader|initlib}}
<lang postscript>
<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:
<lang powershell>1..5 | ForEach-Object { $_ * $_ }</lang>
<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:
<lang powershell>function map ([array] $a, [scriptblock] $s) {
<syntaxhighlight lang=powershell>function map ([array] $a, [scriptblock] $s) {
$a | ForEach-Object $s
$a | ForEach-Object $s
}
}
map (1..5) { $_ * $_ }</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.
<lang Prolog> ?- assert((fun(X, Y) :- Y is 2 * X)).
<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}}==
<lang PureBasic>Procedure Cube(Array param.i(1))
<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,684: Line 2,684:
Next
Next


Cube(AnArray()) </lang>
Cube(AnArray()) </syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>def square(n):
<syntaxhighlight lang=python>def square(n):
return n * n
return n * n
Line 2,704: Line 2,704:


import itertools
import itertools
isquares2 = itertools.imap(square, numbers) # iterator, lazy</lang>
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:
<lang python>print " ".join(str(n * n) for n in range(10))</lang>
<syntaxhighlight lang=python>print " ".join(str(n * n) for n in range(10))</syntaxhighlight>
Or:
Or:
<lang python>print " ".join(map(str, map(square, range(10))))</lang>
<syntaxhighlight lang=python>print " ".join(map(str, map(square, range(10))))</syntaxhighlight>
Result:
Result:
<lang python>0 1 4 9 16 25 36 49 64 81</lang>
<syntaxhighlight lang=python>0 1 4 9 16 25 36 49 64 81</syntaxhighlight>


=={{header|QB64}}==
=={{header|QB64}}==
<lang QB64>
<syntaxhighlight lang=QB64>
'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.
Line 2,750: Line 2,750:
End Sub
End Sub


</syntaxhighlight>
</lang>


=={{header|Quackery}}==
=={{header|Quackery}}==
Line 2,756: Line 2,756:
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.
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.


<lang Quackery>/O> [ 3 ** ] is cubed ( n --> n )
<syntaxhighlight lang=Quackery>/O> [ 3 ** ] is cubed ( n --> n )
...
...


Line 2,778: Line 2,778:
...
...


Stack: [ 1 8 27 64 125 216 343 512 729 1000 ]</lang>
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.
<lang R>cube <- function(x) x*x*x
<syntaxhighlight lang=R>cube <- function(x) x*x*x
elements <- 1:5
elements <- 1:5
cubes <- cube(elements)</lang>
cubes <- cube(elements)</syntaxhighlight>
Explicit looping over array elements is also possible.
Explicit looping over array elements is also possible.
<lang R>cubes <- numeric(5)
<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])
}</lang>
}</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.
<lang R>elements2 <- list(1,2,3,4,5)
<syntaxhighlight lang=R>elements2 <- list(1,2,3,4,5)
cubes <- sapply(elements2, cube)</lang>
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,799: Line 2,799:
=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang=racket>
#lang racket
#lang racket


Line 2,807: Line 2,807:
;; 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}}==
=={{header|Raku}}==
Line 2,813: Line 2,813:
{{works with|Rakudo|2015.10-11}}
{{works with|Rakudo|2015.10-11}}


<lang perl6>sub function { 2 * $^x + 3 };
<syntaxhighlight lang=perl6>sub function { 2 * $^x + 3 };
my @array = 1 .. 5;
my @array = 1 .. 5;


Line 2,832: Line 2,832:
# we neither need a variable for the array nor for the function
# we neither need a variable for the array nor for the function
say [1,2,3]>>.&({ $^x + 1});
say [1,2,3]>>.&({ $^x + 1});
</syntaxhighlight>
</lang>


=={{header|Raven}}==
=={{header|Raven}}==
<lang raven># To print the squared elements
<syntaxhighlight lang=raven># To print the squared elements
[1 2 3 4 5] each dup * print</lang>
[1 2 3 4 5] each dup * print</syntaxhighlight>


<lang raven># To obtain a new array
<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</lang>
list</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>REBOL [
<syntaxhighlight lang=REBOL>REBOL [
Title: "Array Callback"
Title: "Array Callback"
URL: http://rosettacode.org/wiki/Apply_a_callback_to_an_Array
URL: http://rosettacode.org/wiki/Apply_a_callback_to_an_Array
Line 2,869: Line 2,869:


print [crlf "Applying native function with 'map':"]
print [crlf "Applying native function with 'map':"]
assert [[2 4 6] = map :square-root [4 16 36]]</lang>
assert [[2 4 6] = map :square-root [4 16 36]]</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,885: Line 2,885:
Retro provides a variety of array words. Using these 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:


<lang Retro>{ #1 #2 #3 #4 #5 } [ #10 * ] a:map [ n:put sp ] a:for-each</lang>
<syntaxhighlight lang=Retro>{ #1 #2 #3 #4 #5 } [ #10 * ] a:map [ n:put sp ] a:for-each</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program applies a callback to an array (using factorials for a demonstration).*/
<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.*/
numeric digits 100 /*be able to display some huge numbers.*/
parse arg # . /*obtain an optional value from the CL.*/
parse arg # . /*obtain an optional value from the CL.*/
Line 2,910: Line 2,910:
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
fact: procedure; arg x; != 1; do f=2 to x; != !*f; end; /*f*/; return !
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</lang>
listA: do k=0 while a.k\==''; say arg(1) 'a.'k"=" a.k; end /*k*/; return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}
<pre>
<pre>
Line 2,945: Line 2,945:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang=ring>
for x in [1,2,3,4,5]
for x in [1,2,3,4,5]
x = x*x
x = x*x
next
next
</syntaxhighlight>
</lang>


=={{header|RLaB}}==
=={{header|RLaB}}==
Line 2,965: Line 2,965:
Consider an example:
Consider an example:


<lang RLaB>
<syntaxhighlight 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,972: Line 2,972:
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.


<lang RLaB>
<syntaxhighlight lang=RLaB>
x = rand(2,4);
x = rand(2,4);
y = zeros(2,4);
y = zeros(2,4);
Line 2,987: Line 2,987:
}
}
}
}
</syntaxhighlight>
</lang>




Line 2,994: Line 2,994:
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.


<lang RLaB>
<syntaxhighlight lang=RLaB>
x = <<>>;
x = <<>>;
for (i in 1:9)
for (i in 1:9)
Line 3,006: Line 3,006:
y.[i] = sin( x.[i] );
y.[i] = sin( x.[i] );
}
}
</syntaxhighlight>
</lang>


=={{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:
<lang ruby>for i in [1,2,3,4,5] do
<syntaxhighlight lang=ruby>for i in [1,2,3,4,5] do
puts i**2
puts i**2
end</lang>
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)
<lang ruby>[1,2,3,4,5].each{ |i| puts i**2 }</lang>
<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
<lang ruby>[1,2,3,4,5].map{ |i| i**2 }</lang>
<syntaxhighlight lang=ruby>[1,2,3,4,5].map{ |i| i**2 }</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==


<lang rust>fn echo(n: &i32) {
<syntaxhighlight lang=rust>fn echo(n: &i32) {
println!("{}", n);
println!("{}", n);
}
}
Line 3,030: Line 3,030:
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();
}</lang>
}</syntaxhighlight>


=={{header|Salmon}}==
=={{header|Salmon}}==
Line 3,036: Line 3,036:
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.


<lang Salmon>function apply(list, ageless to_apply)
<syntaxhighlight lang=Salmon>function apply(list, ageless to_apply)
(comprehend(x; list) (to_apply(x)));
(comprehend(x; list) (to_apply(x)));


Line 3,042: Line 3,042:


iterate(x; apply([0...9], square))
iterate(x; apply([0...9], square))
x!;</lang>
x!;</syntaxhighlight>


With short identifiers:
With short identifiers:


<lang Salmon>include "short.salm";
<syntaxhighlight lang=Salmon>include "short.salm";


fun apply(list, ageless to_apply)
fun apply(list, ageless to_apply)
Line 3,054: Line 3,054:


iter(x; apply([0...9], square))
iter(x; apply([0...9], square))
x!;</lang>
x!;</syntaxhighlight>


With the numbers given as a list of individual elements:
With the numbers given as a list of individual elements:


<lang Salmon>function apply(list, to_apply)
<syntaxhighlight lang=Salmon>function apply(list, to_apply)
(comprehend(x; list) (to_apply(x)));
(comprehend(x; list) (to_apply(x)));


Line 3,064: Line 3,064:


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!;</lang>
x!;</syntaxhighlight>


=={{header|Sather}}==
=={{header|Sather}}==
<lang sather>class MAIN is
<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 3,078: Line 3,078:
loop #OUT + a.elt! + "\n"; end;
loop #OUT + a.elt! + "\n"; end;
end;
end;
end;</lang>
end;</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>val l = List(1,2,3,4)
<syntaxhighlight lang=scala>val l = List(1,2,3,4)
l.foreach {i => println(i)}</lang>
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 scala>l.foreach(println(_))</lang>
<syntaxhighlight lang=scala>l.foreach(println(_))</syntaxhighlight>
Same for an array
Same for an array
<lang scala>val a = Array(1,2,3,4)
<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''</lang>
a.foreach(println(_)) '' // same as previous line''</syntaxhighlight>


Or for an externally defined function:
Or for an externally defined function:
<lang scala>def doSomething(in: int) = {println("Doing something with "+in)}
<syntaxhighlight lang=scala>def doSomething(in: int) = {println("Doing something with "+in)}
l.foreach(doSomething)</lang>
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''
<lang scala>for(val i <- a) println(i)</lang>
<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)
<lang scala>val squares = l.map{i => i * i} ''//squares is'' List(1,4,9,16)</lang>
<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
<lang scala>val squares = for (val i <- l) yield i * i</lang>
<syntaxhighlight lang=scala>val squares = for (val i <- l) yield i * i</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define (square n) (* n n))
<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))</lang>
(map square (vector->list x))</syntaxhighlight>


A single-line variation
A single-line variation
<lang scheme>(map (lambda (n) (* n n)) '(1 2 3 4 5))</lang>
<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:
<lang scheme>(define (map f L)
<syntaxhighlight lang=scheme>(define (map f L)
(if (null? L)
(if (null? L)
L
L
(cons (f (car L)) (map f (cdr L)))))</lang>
(cons (f (car L)) (map f (cdr L)))))</syntaxhighlight>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>
<syntaxhighlight lang=sensetalk>
put each item in [1,2,3,5,9,14,24] squared
put each item in [1,2,3,5,9,14,24] squared


Line 3,126: Line 3,126:
to handle myFunc of num
to handle myFunc of num
return 2*num + 1
return 2*num + 1
end myFunc</lang>
end myFunc</syntaxhighlight>
Output:
Output:
<lang sensetalk>(1,4,9,25,81,196,576)
<syntaxhighlight lang=sensetalk>(1,4,9,25,81,196,576)
(3,5,7,11,19,29,49)</lang>
(3,5,7,11,19,29,49)</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
Defining a callback function:
Defining a callback function:
<lang ruby>func callback(i) { say i**2 }</lang>
<syntaxhighlight lang=ruby>func callback(i) { say i**2 }</syntaxhighlight>


The function will get called for each element:
The function will get called for each element:
<lang ruby>[1,2,3,4].each(callback)</lang>
<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:
<lang ruby>[1,2,3,4].each{|i| say i**2 }</lang>
<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:
For creating a new array, we can use the Array.map method:
<lang ruby>[1,2,3,4,5].map{|i| i**2 }</lang>
<syntaxhighlight lang=ruby>[1,2,3,4,5].map{|i| i**2 }</syntaxhighlight>


=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>BEGIN
<syntaxhighlight lang=simula>BEGIN


! APPLIES A CALLBACK FUNCTION TO AN ARRAY ;
! APPLIES A CALLBACK FUNCTION TO AN ARRAY ;
Line 3,166: Line 3,166:
FOR I := 1 STEP 1 UNTIL 5 DO OUTFIX(A(I), 2, 8); OUTIMAGE;
FOR I := 1 STEP 1 UNTIL 5 DO OUTFIX(A(I), 2, 8); OUTIMAGE;


END.</lang>
END.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,173: Line 3,173:


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>#( 1 2 3 4 5 ) collect: [| :n | n * n].</lang>
<syntaxhighlight lang=slate>#( 1 2 3 4 5 ) collect: [| :n | n * n].</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>#( 1 2.0 'three') do: [:each | each displayNl].</lang>
<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 &sup2;:
You can tell symbols how to react to the <tt>value:</tt> message, and then write &sup2;:
<lang smalltalk>#( 1 2.0 'three') do: #displayNl.</lang>
<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.
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.:
There is a huge number of additional enumeration messages implemented in Collection, from which Array inherits. Eg.:
<lang smalltalk>#( 1 2 3 4 5 ) collect: [:n | n * n].</lang>
<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:
<lang sparkling>let numbers = { 1, 2, 3, 4 };
<syntaxhighlight lang=sparkling>let numbers = { 1, 2, 3, 4 };
foreach(numbers, function(idx, num) {
foreach(numbers, function(idx, num) {
print(num);
print(num);
});</lang>
});</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:
<lang sparkling>let dict = { "foo": 42, "bar": 13, "baz": 37 };
<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;
});</lang>
});</syntaxhighlight>


=={{header|SQL PL}}==
=={{header|SQL PL}}==
{{works with|Db2 LUW}} version 9.7 or higher.
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
With SQL PL:
<lang sql pl>
<syntaxhighlight lang=sql pl>
--#SET TERMINATOR @
--#SET TERMINATOR @


Line 3,232: Line 3,232:
END;
END;
END @
END @
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,245: Line 3,245:


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang Standard ML>
<syntaxhighlight lang=Standard ML>
map f l
map f l
</syntaxhighlight>
</lang>
i.e.
i.e.
<lang Standard ML>
<syntaxhighlight 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}}==
=={{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.
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.


<lang stata>function map(f,a) {
<syntaxhighlight lang=stata>function map(f,a) {
nr = rows(a)
nr = rows(a)
nc = cols(a)
nc = cols(a)
Line 3,278: Line 3,278:
function square(x) {
function square(x) {
return(x*x)
return(x*x)
}</lang>
}</syntaxhighlight>


'''Output'''
'''Output'''
Line 3,291: Line 3,291:
=={{header|SuperCollider}}==
=={{header|SuperCollider}}==
Actually, there is a builtin <tt>squared</tt> operator:
Actually, there is a builtin <tt>squared</tt> operator:
<lang SuperCollider>[1, 2, 3].squared // returns [1, 4, 9]</lang>
<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>:
<lang SuperCollider>[1, 2, 3].collect { |x| x * x }</lang>
<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:
<lang SuperCollider>var square = { |x| x * x };
<syntaxhighlight lang=SuperCollider>var square = { |x| x * x };
var map = { |fn, xs|
var map = { |fn, xs|
all {: fn.value(x), x <- xs };
all {: fn.value(x), x <- xs };
};
};
map.value(square, [1, 2, 3]);</lang>
map.value(square, [1, 2, 3]);</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>func square(n: Int) -> Int {
<syntaxhighlight lang=swift>func square(n: Int) -> Int {
return n * n
return n * n
}
}
Line 3,314: Line 3,314:
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</lang>
let isquares1 = numbers.lazy.map(square) // lazy sequence</syntaxhighlight>


=={{header|Tailspin}}==
=={{header|Tailspin}}==
<lang tailspin>
<syntaxhighlight lang=tailspin>
def numbers: [1,3,7,10];
def numbers: [1,3,7,10];


Line 3,332: Line 3,332:
[ $numbers... -> $ * $ ] -> !OUT::write
[ $numbers... -> $ * $ ] -> !OUT::write
[ $numbers... -> cube ] -> !OUT::write
[ $numbers... -> cube ] -> !OUT::write
</syntaxhighlight>
</lang>


=={{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:
<lang tcl>foreach var $dat {
<syntaxhighlight lang=tcl>foreach var $dat {
myfunc $var
myfunc $var
}</lang>
}</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:
<lang tcl>foreach name [array names dat] {
<syntaxhighlight lang=tcl>foreach name [array names dat] {
myfunc $dat($name)
myfunc $dat($name)
}</lang>
}</syntaxhighlight>


More functional, with a simple <code>map</code> function:
More functional, with a simple <code>map</code> function:
<lang Tcl>proc map {f list} {
<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 3,356: Line 3,356:


% map square {1 2 3 4 5}
% map square {1 2 3 4 5}
1 4 9 16 25</lang>
1 4 9 16 25</syntaxhighlight>


=={{header|TI-89 BASIC}}==
=={{header|TI-89 BASIC}}==


<lang ti89b>© For no return value
<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 3,376: Line 3,376:


foreach("callback", {1,2,3,4,5})
foreach("callback", {1,2,3,4,5})
Disp map("√", {1,2,3,4,5})</lang>
Disp map("√", {1,2,3,4,5})</syntaxhighlight>


{{Out}}
{{Out}}
Line 3,390: Line 3,390:
JavaScript alike:
JavaScript alike:


<lang javascript>var a = [1, 2, 3, 4, 5];
<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:
<lang javascript>var a = [1, 2, 3, 4, 5];
<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}}==


<lang toka>( array count function -- )
<syntaxhighlight lang=toka>( array count function -- )
{
{
value| array fn |
value| array fn |
Line 3,417: Line 3,417:


( Add 1 to each item in the array )
( Add 1 to each item in the array )
a 5 [ 1 + ] map-array</lang>
a 5 [ 1 + ] map-array</syntaxhighlight>


=={{header|TorqueScript}}==
=={{header|TorqueScript}}==
Line 3,425: Line 3,425:
Callbacks:
Callbacks:


<lang TorqueScript>
<syntaxhighlight lang=TorqueScript>
function map(%array,%arrayCount,%function)
function map(%array,%arrayCount,%function)
{
{
Line 3,434: Line 3,434:
}
}
}
}
</syntaxhighlight>
</lang>


Now to set up an array:
Now to set up an array:


<lang TorqueScript>
<syntaxhighlight 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:


<lang TorqueScript>
<syntaxhighlight lang=TorqueScript>
map("$array",3,"echo");
map("$array",3,"echo");
</syntaxhighlight>
</lang>


Which should result in:
Which should result in:


<lang TorqueScript>
<syntaxhighlight lang=TorqueScript>
=> Hello.
=> Hello.


Line 3,458: Line 3,458:


=> How are you?
=> How are you?
</syntaxhighlight>
</lang>


=={{header|TXR}}==
=={{header|TXR}}==
Line 3,464: Line 3,464:
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:


<lang bash>$ txr -e '[mapdo prinl #(1 2 3 4 5 6 7 8 9 10)]'
<syntaxhighlight lang=bash>$ txr -e '[mapdo prinl #(1 2 3 4 5 6 7 8 9 10)]'
1
1
2
2
Line 3,474: Line 3,474:
8
8
9
9
10</lang>
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 3,543: Line 3,543:
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</lang>
Return ' through the stack</syntaxhighlight>
{{out}}
{{out}}
<pre>SQRT(1) = 1.0000
<pre>SQRT(1) = 1.0000
Line 3,561: Line 3,561:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
{{works with|Bourne Shell}}
<lang bash>map() {
<syntaxhighlight lang=bash>map() {
map_command=$1
map_command=$1
shift
shift
Line 3,567: Line 3,567:
}
}
list=1:2:3
list=1:2:3
(IFS=:; map echo $list)</lang>
(IFS=:; map echo $list)</syntaxhighlight>


{{works with|ksh93}}
{{works with|ksh93}}
{{works with|pdksh}}
{{works with|pdksh}}
{{works with|zsh}}
{{works with|zsh}}
<lang bash>map() {
<syntaxhighlight lang=bash>map() {
typeset command=$1
typeset command=$1
shift
shift
Line 3,578: Line 3,578:
}
}
set -A ary 1 2 3
set -A ary 1 2 3
map print "${ary[@]}"</lang>
map print "${ary[@]}"</syntaxhighlight>


{{works with|zsh}}
{{works with|zsh}}
<lang bash>map(){for i ($*[2,-1]) $1 $i}
<syntaxhighlight lang=bash>map(){for i ($*[2,-1]) $1 $i}
a=(1 2 3)
a=(1 2 3)
map print $a</lang>
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.
<lang Ursala>#import nat
<syntaxhighlight lang=Ursala>#import nat


#cast %nL
#cast %nL


demo = successor* <325,32,67,1,3,7,315></lang>
demo = successor* <325,32,67,1,3,7,315></syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,600: Line 3,600:
=={{header|V}}==
=={{header|V}}==
apply squaring (dup *) to each member of collection
apply squaring (dup *) to each member of collection
<lang v>[1 2 3 4] [dup *] map</lang>
<syntaxhighlight lang=v>[1 2 3 4] [dup *] map</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
<syntaxhighlight lang=vb>
<lang vb>
Option Explicit
Option Explicit


Line 3,624: Line 3,624:
Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)
Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)
End If
End If
End Function</lang>
End Function</syntaxhighlight>
{{out}}
{{out}}
<pre>0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55</pre>
<pre>0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55</pre>
Line 3,633: Line 3,633:


=====Implementation=====
=====Implementation=====
<syntaxhighlight lang=vb>
<lang vb>
class callback
class callback
dim sRule
dim sRule
Line 3,650: Line 3,650:
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 3,667: Line 3,667:
cb.applyto a1
cb.applyto a1
wscript.echo join( a1, ", " )
wscript.echo join( a1, ", " )
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 3,680: Line 3,680:
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.
<lang vim>echo map([10, 20, 30], 'v:val * v:val')
<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)')</lang>
echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:key)')</syntaxhighlight>


{{Out}}
{{Out}}
Line 3,702: Line 3,702:
and System.Linq.Enumerable.ToArray(Of TSource)(IEnumerable(Of TSource)) eagerly converts the enumerable to an array.
and System.Linq.Enumerable.ToArray(Of TSource)(IEnumerable(Of TSource)) eagerly converts the enumerable to an array.


<lang vbnet>Module Program
<syntaxhighlight lang=vbnet>Module Program
Function OneMoreThan(i As Integer) As Integer
Function OneMoreThan(i As Integer) As Integer
Return i + 1
Return i + 1
Line 3,726: Line 3,726:
Array.ForEach(resultArr, AddressOf Console.WriteLine)
Array.ForEach(resultArr, AddressOf Console.WriteLine)
End Sub
End Sub
End Module</lang>
End Module</syntaxhighlight>


{{out}}
{{out}}
Line 3,736: Line 3,736:
=={{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 vorpal>A.map(F)</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.
<lang vorpal>A.map(F, x, y)</lang>
<syntaxhighlight lang=vorpal>A.map(F, x, y)</syntaxhighlight>


=={{header|Wart}}==
=={{header|Wart}}==
<lang wart>map prn '(1 2 3 4 5)</lang>
<syntaxhighlight lang=wart>map prn '(1 2 3 4 5)</syntaxhighlight>


{{Out}}
{{Out}}
Line 3,752: Line 3,752:


=={{header|WDTE}}==
=={{header|WDTE}}==
<lang WDTE>let a => import 'arrays';
<syntaxhighlight lang=WDTE>let a => import 'arrays';
let s => import 'stream';
let s => import 'stream';


Line 3,760: Line 3,760:
-> s.map (* 2)
-> s.map (* 2)
-> s.collect
-> s.collect
;</lang>
;</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.
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}}==
<lang ecmascript>var arr = [1, 2, 3, 4, 5]
<syntaxhighlight lang=ecmascript>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) }</lang>
arr.each { |x| System.print(x) }</syntaxhighlight>


{{out}}
{{out}}
Line 3,780: Line 3,780:


=={{header|XBS}}==
=={{header|XBS}}==
<lang xbs>func map(arr:array,callback:function){
<syntaxhighlight lang=xbs>func map(arr:array,callback:function){
set newArr:array = [];
set newArr:array = [];
foreach(k,v as arr){
foreach(k,v as arr){
Line 3,794: Line 3,794:
log(arr.join(", "));
log(arr.join(", "));
log(result.join(", "));</lang>
log(result.join(", "));</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,802: Line 3,802:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>sub map(f$, t())
<syntaxhighlight lang=Yabasic>sub map(f$, t())
local i
local i


Line 3,832: Line 3,832:
print t(i), "\t";
print t(i), "\t";
next i
next i
print</lang>
print</syntaxhighlight>


=={{header|Yacas}}==
=={{header|Yacas}}==
<lang Yacas>Sin /@ {1, 2, 3, 4}
<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}}==
=={{header|Z80 Assembly}}==
<lang z80>Array:
<syntaxhighlight lang=z80>Array:
byte &01,&02,&03,&04,&05
byte &01,&02,&03,&04,&05
Array_End:
Array_End:
Line 3,856: Line 3,856:
inc (hl)
inc (hl)
inc hl ;next entry in array
inc hl ;next entry in array
djnz bar</lang>
djnz bar</syntaxhighlight>


{{out}}
{{out}}
Line 3,865: Line 3,865:


=={{header|Zig}}==
=={{header|Zig}}==
<lang zig>pub fn main() !void {
<syntaxhighlight lang=zig>pub fn main() !void {
var array = [_]i32{1, 2, 3};
var array = [_]i32{1, 2, 3};
apply(@TypeOf(array[0]), array[0..], func);
apply(@TypeOf(array[0]), array[0..], func);
Line 3,879: Line 3,879:
const std = @import("std");
const std = @import("std");
std.debug.print("{d}\n", .{a-1});
std.debug.print("{d}\n", .{a-1});
}</lang>
}</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>L(1,2,3,4,5).apply('+(5))</lang>
<syntaxhighlight lang=zkl>L(1,2,3,4,5).apply('+(5))</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,889: Line 3,889:


=={{header|zonnon}}==
=={{header|zonnon}}==
<lang zonnon>
<syntaxhighlight lang=zonnon>
module Main;
module Main;
type
type
Line 3,929: Line 3,929:
Write(Map(x,Power))
Write(Map(x,Power))
end Main.
end Main.
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,936: Line 3,936:


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
<lang zxbasic>10 LET a$="x+x"
<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,946: Line 3,946:
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}}