Apply a callback to an array: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1: Line 1:
{{task|Basic language learning}}
[[Category:Iteration]]
[[Category:Iteration]]
{{task|Basic language learning}}


;Task:
;Task:
Line 8: Line 8:
=={{header|11l}}==
=={{header|11l}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<syntaxhighlight 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)</syntaxhighlight>
print(arrsq)</syntaxhighlight>
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.
<syntaxhighlight lang=6502asm>define SRC_LO $00
<syntaxhighlight lang="6502asm">define SRC_LO $00
define SRC_HI $01
define SRC_HI $01


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.
<syntaxhighlight 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 109: Line 109:
=={{header|8th}}==
=={{header|8th}}==
The builtin word "a:map" does this:
The builtin word "a:map" does this:
<syntaxhighlight lang=forth>
<syntaxhighlight lang="forth">
[ 1 , 2, 3 ]
[ 1 , 2, 3 ]
' n:sqr
' n:sqr
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:


<syntaxhighlight lang=lisp>(defun apply-to-each (xs)
<syntaxhighlight lang="lisp">(defun apply-to-each (xs)
(if (endp xs)
(if (endp xs)
nil
nil
Line 131: Line 131:


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<syntaxhighlight lang=actionscript>package
<syntaxhighlight lang="actionscript">package
{
{
public class ArrayCallback
public class ArrayCallback
Line 153: Line 153:
=={{header|Ada}}==
=={{header|Ada}}==
{{works with|GNAT|GPL 2005}}
{{works with|GNAT|GPL 2005}}
<syntaxhighlight lang=ada>with Ada.Text_Io;
<syntaxhighlight lang="ada">with Ada.Text_Io;
with Ada.Integer_text_IO;
with Ada.Integer_text_IO;
Line 192: Line 192:


=={{header|Aime}}==
=={{header|Aime}}==
<syntaxhighlight lang=aime>void
<syntaxhighlight lang="aime">void
map(list l, void (*fp)(object))
map(list l, void (*fp)(object))
{
{
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}}
<syntaxhighlight 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 244: Line 244:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<syntaxhighlight 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 260: Line 260:
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:


<syntaxhighlight 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 273: Line 273:


=={{header|AppleScript}}==
=={{header|AppleScript}}==
<syntaxhighlight 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 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:


<syntaxhighlight 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 372: Line 372:


=={{header|Arturo}}==
=={{header|Arturo}}==
<syntaxhighlight lang=rebol>arr: [1 2 3 4 5]
<syntaxhighlight lang="rebol">arr: [1 2 3 4 5]


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


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


callback(array){
callback(array){
Line 393: Line 393:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang=awk>$ awk 'func psqr(x){print x,x*x}BEGIN{split("1 2 3 4 5",a);for(i in a)psqr(a[i])}'
<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
Line 404: Line 404:
Let us define a squaring operator:
Let us define a squaring operator:


<syntaxhighlight lang=babel>sq { dup * } <</syntaxhighlight>
<syntaxhighlight lang="babel">sq { dup * } <</syntaxhighlight>


Now, we apply the sq operator over a list and display the result using the lsnum utility:
Now, we apply the sq operator over a list and display the result using the lsnum utility:


<syntaxhighlight lang=babel>( 0 1 1 2 3 5 8 13 21 34 ) { sq ! } over ! lsnum !</syntaxhighlight>
<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}}
<syntaxhighlight 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 442: Line 442:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<syntaxhighlight lang=bracmat>( ( callbackFunction1
<syntaxhighlight lang="bracmat">( ( callbackFunction1
= location value
= location value
. !arg:(?location,?value)
. !arg:(?location,?value)
Line 483: Line 483:
=={{header|Brat}}==
=={{header|Brat}}==


<syntaxhighlight 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
Line 490: Line 490:
Alternatively:
Alternatively:


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


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


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


Line 513: Line 513:


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


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


<syntaxhighlight 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 568: Line 568:


{{works with|Visual C sharp|Visual C#|2005}}
{{works with|Visual C sharp|Visual C#|2005}}
<syntaxhighlight lang=csharp>using System;
<syntaxhighlight lang="csharp">using System;


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


Line 626: Line 626:
===std::vector===
===std::vector===
{{libheader|STL}}
{{libheader|STL}}
<syntaxhighlight 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 650: Line 650:


More tricky with binary function
More tricky with binary function
<syntaxhighlight 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 677: Line 677:
===Boost.Lambda===
===Boost.Lambda===
{{libheader|Boost}}
{{libheader|Boost}}
<syntaxhighlight 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);
Line 685: Line 685:


===C++11===
===C++11===
<syntaxhighlight lang=cpp>#include <vector>
<syntaxhighlight lang="cpp">#include <vector>
#include <iostream>
#include <iostream>
#include <algorithm>
#include <algorithm>
Line 705: Line 705:
Define a function and an initial (unboxed) array.
Define a function and an initial (unboxed) array.


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


values :: {#Int}
values :: {#Int}
Line 712: Line 712:
One can easily define a map for arrays, which is overloaded and works for all kinds of arrays (lazy, strict, unboxed).
One can easily define a map for arrays, which is overloaded and works for all kinds of arrays (lazy, strict, unboxed).


<syntaxhighlight lang=clean>mapArray f array = {f x \\ x <-: array}</syntaxhighlight>
<syntaxhighlight lang="clean">mapArray f array = {f x \\ x <-: array}</syntaxhighlight>


Apply the function to the initial array (using a comprehension) and print result.
Apply the function to the initial array (using a comprehension) and print result.


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


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


Line 737: Line 737:
=={{header|Clojure}}==
=={{header|Clojure}}==


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


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


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


=={{header|CLU}}==
=={{header|CLU}}==
<syntaxhighlight 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 799: Line 799:


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


Line 824: Line 824:


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


<syntaxhighlight lang=lisp>(map nil #'print #(1 2 3 4 5))</syntaxhighlight>
<syntaxhighlight lang="lisp">(map nil #'print #(1 2 3 4 5))</syntaxhighlight>


Functional: collect squares into new vector that is returned:
Functional: collect squares into new vector that is returned:


<syntaxhighlight lang=lisp>(defun square (x) (* x x))
<syntaxhighlight lang="lisp">(defun square (x) (* x x))
(map 'vector #'square #(1 2 3 4 5))</syntaxhighlight>
(map 'vector #'square #(1 2 3 4 5))</syntaxhighlight>


Destructive, like the Javascript example; add 1 to every slot of vector *a*:
Destructive, like the Javascript example; add 1 to every slot of vector *a*:


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


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
BlackBox Component Builder
BlackBox Component Builder
<syntaxhighlight lang=oberon2>
<syntaxhighlight lang="oberon2">
MODULE Callback;
MODULE Callback;
IMPORT StdLog;
IMPORT StdLog;
Line 933: Line 933:
=={{header|Crystal}}==
=={{header|Crystal}}==
Calling with a block
Calling with a block
<syntaxhighlight 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 942: Line 942:


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


def double(number)
def double(number)
Line 956: Line 956:


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


void main() {
void main() {
Line 967: Line 967:


=={{header|Delphi}}==
=={{header|Delphi}}==
<syntaxhighlight lang=Delphi>
<syntaxhighlight lang="delphi">
// Declare the callback function
// Declare the callback function
procedure callback(const AInt:Integer);
procedure callback(const AInt:Integer);
Line 989: Line 989:
=={{header|Dyalect}}==
=={{header|Dyalect}}==


<syntaxhighlight 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,004: Line 1,004:
=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
There is a <code>map</code> builtin that does just this.
There is a <code>map</code> builtin that does just this.
<syntaxhighlight lang=dejavu>!. map @++ [ 1 4 8 ]
<syntaxhighlight lang="dejavu">!. map @++ [ 1 4 8 ]


#implemented roughly like this:
#implemented roughly like this:
Line 1,017: Line 1,017:
=={{header|E}}==
=={{header|E}}==


<syntaxhighlight 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
Line 1,024: Line 1,024:
Example of builtin iteration:
Example of builtin iteration:


<syntaxhighlight lang=e>def callback(index, value) {
<syntaxhighlight lang="e">def callback(index, value) {
println(`Item $index is $value.`)
println(`Item $index is $value.`)
}
}
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).


<syntaxhighlight 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,043: Line 1,043:


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<syntaxhighlight 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,059: Line 1,059:
=={{header|Efene}}==
=={{header|Efene}}==


<syntaxhighlight lang=efene>square = fn (N) {
<syntaxhighlight lang="efene">square = fn (N) {
N * N
N * N
}
}
Line 1,094: Line 1,094:


=={{header|EGL}}==
=={{header|EGL}}==
<syntaxhighlight 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,117: Line 1,117:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<syntaxhighlight 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,127: Line 1,127:


=={{header|Elixir}}==
=={{header|Elixir}}==
<syntaxhighlight 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)
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.


<syntaxhighlight lang=Erlang>
<syntaxhighlight lang="erlang">
1> L = [1,2,3].
1> L = [1,2,3].
[1,2,3]
[1,2,3]
Line 1,147: Line 1,147:
You can use lists:foreach/2 if you just want to apply the callback to each element of the list.
You can use lists:foreach/2 if you just want to apply the callback to each element of the list.


<lang>
<syntaxhighlight lang="text">
2> lists:foreach(fun(X) -> io:format("~w ",[X]) end, L).
2> lists:foreach(fun(X) -> io:format("~w ",[X]) end, L).
1 2 3 ok
1 2 3 ok
Line 1,154: Line 1,154:
Or you can use lists:map/2 if you want to create a new list with the result of the callback on each element.
Or you can use lists:map/2 if you want to create a new list with the result of the callback on each element.


<syntaxhighlight lang=Erlang>
<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]
Line 1,161: Line 1,161:
Or you can use lists:foldl/3 if you want to accumulate the result of the callback on each element into one value.
Or you can use lists:foldl/3 if you want to accumulate the result of the callback on each element into one value.


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


=={{header|ERRE}}==
=={{header|ERRE}}==
<lang>
<syntaxhighlight lang="text">
PROGRAM CALLBACK
PROGRAM CALLBACK


Line 1,200: Line 1,200:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<syntaxhighlight 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,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.
<syntaxhighlight 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 |]</syntaxhighlight>
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.
<syntaxhighlight lang=fsharp>let result = Array.map (fun x -> x * x) [|1; 2; 3; 4; 5|]</syntaxhighlight>
<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.
<syntaxhighlight lang=fsharp>Array.iter (fun x -> printfn "%d" x) [|1; 2; 3; 4; 5|]</syntaxhighlight>
<syntaxhighlight lang="fsharp">Array.iter (fun x -> printfn "%d" x) [|1; 2; 3; 4; 5|]</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
Print each element squared:
Print each element squared:
<syntaxhighlight lang=factor>{ 1 2 3 4 } [ sq . ] each</syntaxhighlight>
<syntaxhighlight lang="factor">{ 1 2 3 4 } [ sq . ] each</syntaxhighlight>


Collect return values:
Collect return values:
<syntaxhighlight lang=factor>{ 1 2 3 4 } [ sq ] map</syntaxhighlight>
<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.


<syntaxhighlight lang=fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 1,265: Line 1,265:
=={{header|FBSL}}==
=={{header|FBSL}}==
'''User-defined mapping function:'''
'''User-defined mapping function:'''
<syntaxhighlight 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,287: Line 1,287:


'''Standard MAP() function:'''
'''Standard MAP() function:'''
<syntaxhighlight 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,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.


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


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


Line 1,344: Line 1,344:


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


<syntaxhighlight lang=fortran>program testAC
<syntaxhighlight lang="fortran">program testAC
use arrCallback
use arrCallback
implicit none
implicit none
Line 1,373: Line 1,373:


{{Works with|ANSI FORTRAN| 77 (with MIL-STD-1753 structured DO) and later}}
{{Works with|ANSI FORTRAN| 77 (with MIL-STD-1753 structured DO) and later}}
<syntaxhighlight lang=fortran> program test
<syntaxhighlight lang="fortran"> program test
C
C
C-- Declare array:
C-- Declare array:
Line 1,389: Line 1,389:


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


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<syntaxhighlight 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,430: Line 1,430:


=={{header|Frink}}==
=={{header|Frink}}==
<syntaxhighlight 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]
Line 1,437: Line 1,437:


=={{header|FunL}}==
=={{header|FunL}}==
<syntaxhighlight lang=funl>[1, 2, 3].foreach( println )
<syntaxhighlight lang="funl">[1, 2, 3].foreach( println )


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


=={{header|Futhark}}==
=={{header|Futhark}}==
<syntaxhighlight lang=Futhark>
<syntaxhighlight lang="futhark">
map f l
map f l
</syntaxhighlight>
</syntaxhighlight>
e.g.
e.g.
<syntaxhighlight 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>
</syntaxhighlight>
or equivalently
or equivalently
<syntaxhighlight lang=Futhark>
<syntaxhighlight lang="futhark">
map (+1) [1,2,3] -- [2,3,4]
map (+1) [1,2,3] -- [2,3,4]
</syntaxhighlight>
</syntaxhighlight>
Line 1,474: Line 1,474:


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


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


import "fmt"
import "fmt"
Line 1,512: Line 1,512:


Alternatively though, an array-like type can be defined and callback-style methods can be defined on it to apply a function to the elements.
Alternatively though, an array-like type can be defined and callback-style methods can be defined on it to apply a function to the elements.
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,556: Line 1,556:


Print each value in a list
Print each value in a list
<syntaxhighlight lang=groovy>[1,2,3,4].each { println it }</syntaxhighlight>
<syntaxhighlight lang="groovy">[1,2,3,4].each { println it }</syntaxhighlight>


Create a new list containing the squares of another list
Create a new list containing the squares of another list
<syntaxhighlight lang=groovy>[1,2,3,4].collect { it * it }</syntaxhighlight>
<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}}
<syntaxhighlight 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</syntaxhighlight>
map square values</syntaxhighlight>


Using list comprehension to generate a list of the squared values
Using list comprehension to generate a list of the squared values
<syntaxhighlight lang=haskell>[square x | x <- values]</syntaxhighlight>
<syntaxhighlight lang="haskell">[square x | x <- values]</syntaxhighlight>


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


Or with one less layer of monadic wrapping
Or with one less layer of monadic wrapping
<syntaxhighlight lang=haskell>(^ 2) <$> [1..10]</syntaxhighlight>
<syntaxhighlight lang="haskell">(^ 2) <$> [1..10]</syntaxhighlight>


Using function composition to create a function that will print the squares of a list
Using function composition to create a function that will print the squares of a list
<syntaxhighlight lang=haskell>let printSquares = mapM_ (print.square)
<syntaxhighlight lang="haskell">let printSquares = mapM_ (print.square)
printSquares values</syntaxhighlight>
printSquares values</syntaxhighlight>


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


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


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight 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,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


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


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


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


'''Example''':
'''Example''':
<syntaxhighlight lang=j> callback =: *:
<syntaxhighlight lang="j"> callback =: *:
array =: 1 2 3 4 5
array =: 1 2 3 4 5
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.


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


interface IntConsumer {
interface IntConsumer {
Line 1,688: Line 1,688:
{{works with|Java|8}}
{{works with|Java|8}}


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


public class ArrayCallback {
public class ArrayCallback {
Line 1,709: Line 1,709:


===ES3===
===ES3===
<syntaxhighlight 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,720: Line 1,720:


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


===ES6===
===ES6===
<syntaxhighlight lang=javascript>[1, 2, 3, 4, 5].map(v => v * v);</syntaxhighlight>
<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}}==
<syntaxhighlight lang=joy>[1 2 3 4 5] [dup *] map.</syntaxhighlight>
<syntaxhighlight lang="joy">[1 2 3 4 5] [dup *] map.</syntaxhighlight>


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


=={{header|Jsish}}==
=={{header|Jsish}}==
<syntaxhighlight 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,768: Line 1,768:
=={{header|Julia}}==
=={{header|Julia}}==
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}
<syntaxhighlight 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,778: Line 1,778:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<syntaxhighlight 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
Line 1,788: Line 1,788:


=={{header|Klingphix}}==
=={{header|Klingphix}}==
<syntaxhighlight 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,799: Line 1,799:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<syntaxhighlight 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]
Line 1,805: Line 1,805:


=={{header|Lang5}}==
=={{header|Lang5}}==
<syntaxhighlight 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" .</syntaxhighlight>
[1 2 3 4 5] 'square apply . "\n" .</syntaxhighlight>


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


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


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


local(
local(
Line 1,831: Line 1,831:


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


Line 1,847: Line 1,847:


=={{header|Logo}}==
=={{header|Logo}}==
<syntaxhighlight lang=logo>to square :x
<syntaxhighlight lang="logo">to square :x
output :x * :x
output :x * :x
end
end
Line 1,857: Line 1,857:


Say we have an array:
Say we have an array:
<syntaxhighlight lang=lua>myArray = {1, 2, 3, 4, 5}</syntaxhighlight>
<syntaxhighlight lang="lua">myArray = {1, 2, 3, 4, 5}</syntaxhighlight>
A map function for this would be
A map function for this would be
<syntaxhighlight lang=lua>map = function(f, data)
<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,867: Line 1,867:
end</syntaxhighlight>
end</syntaxhighlight>
Together with our array and a square function this yields:
Together with our array and a square function this yields:
<syntaxhighlight lang=lua>myFunc = function(x) return x*x end
<syntaxhighlight lang="lua">myFunc = function(x) return x*x end


print(unpack( map(myFunc, myArray) ))
print(unpack( map(myFunc, myArray) ))
Line 1,876: Line 1,876:


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight 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,907: Line 1,907:


=={{header|M4}}==
=={{header|M4}}==
<syntaxhighlight 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,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.
<syntaxhighlight 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,939: Line 1,939:
</syntaxhighlight>
</syntaxhighlight>
For Arrays (Vectors, Matrices, etc.) both map and trailing tilde also work, and by default create a new object, leaving the input Array unchanged.
For Arrays (Vectors, Matrices, etc.) both map and trailing tilde also work, and by default create a new object, leaving the input Array unchanged.
<syntaxhighlight lang=Maple>
<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,956: Line 1,956:
</syntaxhighlight>
</syntaxhighlight>
However, since these are mutable data structures in Maple, it is possible to use map to modify its input according to the applied procedure.
However, since these are mutable data structures in Maple, it is possible to use map to modify its input according to the applied procedure.
<syntaxhighlight lang=Maple>
<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,966: Line 1,966:


It is also possible to pass additional arguments to the mapped procedure.
It is also possible to pass additional arguments to the mapped procedure.
<syntaxhighlight lang=Maple>
<syntaxhighlight lang="maple">
> map( `+`, [ 1, 2, 3 ], 3 );
> map( `+`, [ 1, 2, 3 ], 3 );
[4, 5, 6]
[4, 5, 6]
</syntaxhighlight>
</syntaxhighlight>
Passing additional arguments *before* the arguments from the mapped data structure is achieved using map2, or the more general map[n] procedure.
Passing additional arguments *before* the arguments from the mapped data structure is achieved using map2, or the more general map[n] procedure.
<syntaxhighlight lang=Maple>
<syntaxhighlight lang="maple">
> map2( `-`, 5, [ 1, 2, 3 ] );
> map2( `-`, 5, [ 1, 2, 3 ] );
[4, 3, 2]
[4, 3, 2]
Line 1,980: Line 1,980:


=={{header|Mathematica}}//{{header|Wolfram Language}}==
=={{header|Mathematica}}//{{header|Wolfram Language}}==
<syntaxhighlight 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}]
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.
<syntaxhighlight lang=MATLAB>>> array = [1 2 3 4 5]
<syntaxhighlight lang="matlab">>> array = [1 2 3 4 5]


array =
array =
Line 2,026: Line 2,026:


=={{header|Maxima}}==
=={{header|Maxima}}==
<syntaxhighlight 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,037: Line 2,037:
=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<syntaxhighlight 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</syntaxhighlight>
(1 2 3 4 5) 'sqrt map ; collect return values</syntaxhighlight>


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


IMPORT IO, Fmt;
IMPORT IO, Fmt;
Line 2,069: Line 2,069:


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<syntaxhighlight 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,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).
<syntaxhighlight 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);</syntaxhighlight>
def squares = seq.Map(x => x*x);</syntaxhighlight>


=={{header|NetLogo}}==
=={{header|NetLogo}}==
<syntaxhighlight 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.
Line 2,101: Line 2,101:
=={{header|NewLISP}}==
=={{header|NewLISP}}==


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


=={{header|NGS}}==
=={{header|NGS}}==
<syntaxhighlight 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)
}</syntaxhighlight>
}</syntaxhighlight>
Line 2,112: Line 2,112:
=={{header|Nial}}==
=={{header|Nial}}==


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


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


<syntaxhighlight 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)</syntaxhighlight>
arr.apply proc(some: var int) = echo(some, " squared = ", some*some)</syntaxhighlight>


Line 2,128: Line 2,128:
=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
{{Works with|oo2x}}
{{Works with|oo2x}}
<syntaxhighlight lang=oberon2>
<syntaxhighlight lang="oberon2">
MODULE ApplyCallBack;
MODULE ApplyCallBack;
IMPORT
IMPORT
Line 2,226: Line 2,226:


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


Line 2,253: Line 2,253:
This function is part of the standard library:
This function is part of the standard library:


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


Usage example:
Usage example:
<syntaxhighlight 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;;</syntaxhighlight>
Array.map square values;;</syntaxhighlight>


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


Use <tt>iter</tt> if the applied function does not return a value.
Use <tt>iter</tt> if the applied function does not return a value.


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


with partial application we can also write:
with partial application we can also write:


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


<syntaxhighlight 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,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 :
<syntaxhighlight lang=Oforth>0 #+ [ 1, 2, 3, 4, 5 ] apply</syntaxhighlight>
<syntaxhighlight lang="oforth">0 #+ [ 1, 2, 3, 4, 5 ] apply</syntaxhighlight>


map regroups all results into a new list :
map regroups all results into a new list :
<syntaxhighlight lang=Oforth>#sq [ 1, 2, 3, 4, 5 ] map</syntaxhighlight>
<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.
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
(for-each
(for-each
(lambda (element)
(lambda (element)
Line 2,307: Line 2,307:
=={{header|ooRexx}}==
=={{header|ooRexx}}==
ooRexx doesn't directly support callbacks on array items, but this is pretty easy to implement using Routine objects.
ooRexx doesn't directly support callbacks on array items, but this is pretty easy to implement using Routine objects.
<syntaxhighlight lang=ooRexx>start = .array~of("Rick", "Mike", "David", "Mark")
<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,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>.
<syntaxhighlight 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,351: Line 2,351:


=={{header|Oz}}==
=={{header|Oz}}==
<syntaxhighlight lang=oz>declare
<syntaxhighlight lang="oz">declare
fun{Square A}
fun{Square A}
A*A
A*A
Line 2,367: Line 2,367:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.2 and above}}
{{works with|PARI/GP|2.4.2 and above}}
<syntaxhighlight lang=parigp>callback(n)=n+n;
<syntaxhighlight lang="parigp">callback(n)=n+n;
apply(callback, [1,2,3,4,5])</syntaxhighlight>
apply(callback, [1,2,3,4,5])</syntaxhighlight>


This should be contrasted with <code>call</code>:
This should be contrasted with <code>call</code>:
<syntaxhighlight lang=parigp>call(callback, [1,2,3,4,5])</syntaxhighlight>
<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}}==
<syntaxhighlight 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,411: Line 2,411:
=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
<!--<syntaxhighlight 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,433: Line 2,433:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<syntaxhighlight 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,459: Line 2,459:


=={{header|PHP}}==
=={{header|PHP}}==
<syntaxhighlight lang=php>function cube($n)
<syntaxhighlight lang="php">function cube($n)
{
{
return($n * $n * $n);
return($n * $n * $n);
Line 2,471: Line 2,471:
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.
<syntaxhighlight lang=Picat>go =>
<syntaxhighlight lang="picat">go =>
L = 1..10,
L = 1..10,


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.
<syntaxhighlight lang=Picat>go2 =>
<syntaxhighlight lang="picat">go2 =>
L = 1..10,
L = 1..10,


Line 2,513: Line 2,513:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<syntaxhighlight 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,531: Line 2,531:


=={{header|Pike}}==
=={{header|Pike}}==
<syntaxhighlight lang=pike>int cube(int n)
<syntaxhighlight lang="pike">int cube(int n)
{
{
return n*n*n;
return n*n*n;
Line 2,541: Line 2,541:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight 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);</syntaxhighlight>
x = sin(x);</syntaxhighlight>
Line 2,547: Line 2,547:
=={{header|PL/SQL}}==
=={{header|PL/SQL}}==
PL/SQL doesn't have callbacks, though we can pass around an object and use its method to simulate one. Further, this callback method can be defined in an abstract class that the mapping function will expect.
PL/SQL doesn't have callbacks, though we can pass around an object and use its method to simulate one. Further, this callback method can be defined in an abstract class that the mapping function will expect.
<syntaxhighlight lang=plsql>-- Let's create a generic class with one method to be used as an interface:
<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,626: Line 2,626:
=={{header|Pop11}}==
=={{header|Pop11}}==


<syntaxhighlight 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,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.
<syntaxhighlight lang=postscript>[1 2 3 4 5] { dup mul = } forall</syntaxhighlight>
<syntaxhighlight lang="postscript">[1 2 3 4 5] { dup mul = } forall</syntaxhighlight>
In this case the respective square numbers for the elements are printed.
In this case the respective square numbers for the elements are printed.


To create a new array from the results above code can simply be wrapped in <code>[]</code>:
To create a new array from the results above code can simply be wrapped in <code>[]</code>:
<syntaxhighlight lang=postscript>[ [1 2 3 4 5] { dup mul } forall ]</syntaxhighlight>
<syntaxhighlight lang="postscript">[ [1 2 3 4 5] { dup mul } forall ]</syntaxhighlight>


{{libheader|initlib}}
{{libheader|initlib}}
<syntaxhighlight lang=postscript>
<syntaxhighlight lang="postscript">
[1 2 3 4 5] {dup *} map
[1 2 3 4 5] {dup *} map
</syntaxhighlight>
</syntaxhighlight>
Line 2,654: Line 2,654:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
This can be done in PowerShell with the <code>ForEach-Object</code> cmdlet which applies a scriptblock to each element of an array:
This can be done in PowerShell with the <code>ForEach-Object</code> cmdlet which applies a scriptblock to each element of an array:
<syntaxhighlight lang=powershell>1..5 | ForEach-Object { $_ * $_ }</syntaxhighlight>
<syntaxhighlight lang="powershell">1..5 | ForEach-Object { $_ * $_ }</syntaxhighlight>
To recreate a ''map'' function, found in other languages the same method applies:
To recreate a ''map'' function, found in other languages the same method applies:
<syntaxhighlight lang=powershell>function map ([array] $a, [scriptblock] $s) {
<syntaxhighlight lang="powershell">function map ([array] $a, [scriptblock] $s) {
$a | ForEach-Object $s
$a | ForEach-Object $s
}
}
Line 2,663: Line 2,663:
=={{header|Prolog}}==
=={{header|Prolog}}==
Prolog doesn't have arrays, but we can do it with lists. This can be done in the console mode.
Prolog doesn't have arrays, but we can do it with lists. This can be done in the console mode.
<syntaxhighlight lang=Prolog> ?- assert((fun(X, Y) :- Y is 2 * X)).
<syntaxhighlight lang="prolog"> ?- assert((fun(X, Y) :- Y is 2 * X)).
true.
true.


Line 2,671: Line 2,671:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<syntaxhighlight 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,687: Line 2,687:


=={{header|Python}}==
=={{header|Python}}==
<syntaxhighlight lang=python>def square(n):
<syntaxhighlight lang="python">def square(n):
return n * n
return n * n
Line 2,706: Line 2,706:
isquares2 = itertools.imap(square, numbers) # iterator, lazy</syntaxhighlight>
isquares2 = itertools.imap(square, numbers) # iterator, lazy</syntaxhighlight>
To print squares of integers in the range from 0 to 9, type:
To print squares of integers in the range from 0 to 9, type:
<syntaxhighlight lang=python>print " ".join(str(n * n) for n in range(10))</syntaxhighlight>
<syntaxhighlight lang="python">print " ".join(str(n * n) for n in range(10))</syntaxhighlight>
Or:
Or:
<syntaxhighlight lang=python>print " ".join(map(str, map(square, range(10))))</syntaxhighlight>
<syntaxhighlight lang="python">print " ".join(map(str, map(square, range(10))))</syntaxhighlight>
Result:
Result:
<syntaxhighlight lang=python>0 1 4 9 16 25 36 49 64 81</syntaxhighlight>
<syntaxhighlight lang="python">0 1 4 9 16 25 36 49 64 81</syntaxhighlight>


=={{header|QB64}}==
=={{header|QB64}}==
<syntaxhighlight 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,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.


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


Line 2,782: Line 2,782:
=={{header|R}}==
=={{header|R}}==
Many functions can take advantage of implicit vectorisation, e.g.
Many functions can take advantage of implicit vectorisation, e.g.
<syntaxhighlight lang=R>cube <- function(x) x*x*x
<syntaxhighlight lang="r">cube <- function(x) x*x*x
elements <- 1:5
elements <- 1:5
cubes <- cube(elements)</syntaxhighlight>
cubes <- cube(elements)</syntaxhighlight>
Explicit looping over array elements is also possible.
Explicit looping over array elements is also possible.
<syntaxhighlight lang=R>cubes <- numeric(5)
<syntaxhighlight lang="r">cubes <- numeric(5)
for(i in seq_along(cubes))
for(i in seq_along(cubes))
{
{
Line 2,792: Line 2,792:
}</syntaxhighlight>
}</syntaxhighlight>
Loop syntax can often simplified using the [http://stat.ethz.ch/R-manual/R-patched/library/base/html/apply.html *apply] family of functions.
Loop syntax can often simplified using the [http://stat.ethz.ch/R-manual/R-patched/library/base/html/apply.html *apply] family of functions.
<syntaxhighlight lang=R>elements2 <- list(1,2,3,4,5)
<syntaxhighlight lang="r">elements2 <- list(1,2,3,4,5)
cubes <- sapply(elements2, cube)</syntaxhighlight>
cubes <- sapply(elements2, cube)</syntaxhighlight>
In each case above, the value of 'cubes' is
In each case above, the value of 'cubes' is
Line 2,799: Line 2,799:
=={{header|Racket}}==
=={{header|Racket}}==


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


Line 2,813: Line 2,813:
{{works with|Rakudo|2015.10-11}}
{{works with|Rakudo|2015.10-11}}


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


Line 2,835: Line 2,835:


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


<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 *
Line 2,844: Line 2,844:


=={{header|REBOL}}==
=={{header|REBOL}}==
<syntaxhighlight 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,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:


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


=={{header|REXX}}==
=={{header|REXX}}==
<syntaxhighlight 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,945: Line 2,945:


=={{header|Ring}}==
=={{header|Ring}}==
<syntaxhighlight 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
Line 2,965: Line 2,965:
Consider an example:
Consider an example:


<syntaxhighlight 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,977: Line 2,977:
'for' or 'while' loops are slow in interpreted languages, and RLaB is no exception.
'for' or 'while' loops are slow in interpreted languages, and RLaB is no exception.


<syntaxhighlight lang=RLaB>
<syntaxhighlight lang="rlab">
x = rand(2,4);
x = rand(2,4);
y = zeros(2,4);
y = zeros(2,4);
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.


<syntaxhighlight lang=RLaB>
<syntaxhighlight lang="rlab">
x = <<>>;
x = <<>>;
for (i in 1:9)
for (i in 1:9)
Line 3,010: Line 3,010:
=={{header|Ruby}}==
=={{header|Ruby}}==
You could use a traditional "for i in arr" approach like below:
You could use a traditional "for i in arr" approach like below:
<syntaxhighlight lang=ruby>for i in [1,2,3,4,5] do
<syntaxhighlight lang="ruby">for i in [1,2,3,4,5] do
puts i**2
puts i**2
end</syntaxhighlight>
end</syntaxhighlight>


Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk)
Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk)
<syntaxhighlight lang=ruby>[1,2,3,4,5].each{ |i| puts i**2 }</syntaxhighlight>
<syntaxhighlight lang="ruby">[1,2,3,4,5].each{ |i| puts i**2 }</syntaxhighlight>


To create a new array of each value squared
To create a new array of each value squared
<syntaxhighlight lang=ruby>[1,2,3,4,5].map{ |i| i**2 }</syntaxhighlight>
<syntaxhighlight lang="ruby">[1,2,3,4,5].map{ |i| i**2 }</syntaxhighlight>


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


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


<syntaxhighlight 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,046: Line 3,046:
With short identifiers:
With short identifiers:


<syntaxhighlight 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,058: Line 3,058:
With the numbers given as a list of individual elements:
With the numbers given as a list of individual elements:


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


Line 3,067: Line 3,067:


=={{header|Sather}}==
=={{header|Sather}}==
<syntaxhighlight 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,081: Line 3,081:


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


Or for an externally defined function:
Or for an externally defined function:
<syntaxhighlight lang=scala>def doSomething(in: int) = {println("Doing something with "+in)}
<syntaxhighlight lang="scala">def doSomething(in: int) = {println("Doing something with "+in)}
l.foreach(doSomething)</syntaxhighlight>
l.foreach(doSomething)</syntaxhighlight>


There is also a ''for'' syntax, which is internally rewritten to call foreach. A foreach method must be defined on ''a''
There is also a ''for'' syntax, which is internally rewritten to call foreach. A foreach method must be defined on ''a''
<syntaxhighlight lang=scala>for(val i <- a) println(i)</syntaxhighlight>
<syntaxhighlight lang="scala">for(val i <- a) println(i)</syntaxhighlight>


It is also possible to apply a function on each item of an list to get a new list (same on array and most collections)
It is also possible to apply a function on each item of an list to get a new list (same on array and most collections)
<syntaxhighlight lang=scala>val squares = l.map{i => i * i} ''//squares is'' List(1,4,9,16)</syntaxhighlight>
<syntaxhighlight lang="scala">val squares = l.map{i => i * i} ''//squares is'' List(1,4,9,16)</syntaxhighlight>


Or the equivalent ''for'' syntax, with the additional keyword ''yield'', map is called instead of foreach
Or the equivalent ''for'' syntax, with the additional keyword ''yield'', map is called instead of foreach
<syntaxhighlight lang=scala>val squares = for (val i <- l) yield i * i</syntaxhighlight>
<syntaxhighlight lang="scala">val squares = for (val i <- l) yield i * i</syntaxhighlight>


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


A single-line variation
A single-line variation
<syntaxhighlight lang=scheme>(map (lambda (n) (* n n)) '(1 2 3 4 5))</syntaxhighlight>
<syntaxhighlight lang="scheme">(map (lambda (n) (* n n)) '(1 2 3 4 5))</syntaxhighlight>


For completeness, the <tt>map</tt> function (which is R5RS standard) can be coded as follows:
For completeness, the <tt>map</tt> function (which is R5RS standard) can be coded as follows:
<syntaxhighlight lang=scheme>(define (map f L)
<syntaxhighlight lang="scheme">(define (map f L)
(if (null? L)
(if (null? L)
L
L
Line 3,119: Line 3,119:


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<syntaxhighlight 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,128: Line 3,128:
end myFunc</syntaxhighlight>
end myFunc</syntaxhighlight>
Output:
Output:
<syntaxhighlight 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)</syntaxhighlight>
(3,5,7,11,19,29,49)</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
Defining a callback function:
Defining a callback function:
<syntaxhighlight lang=ruby>func callback(i) { say i**2 }</syntaxhighlight>
<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:
<syntaxhighlight lang=ruby>[1,2,3,4].each(callback)</syntaxhighlight>
<syntaxhighlight lang="ruby">[1,2,3,4].each(callback)</syntaxhighlight>


Same as above, but with the function inlined:
Same as above, but with the function inlined:
<syntaxhighlight lang=ruby>[1,2,3,4].each{|i| say i**2 }</syntaxhighlight>
<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:
<syntaxhighlight lang=ruby>[1,2,3,4,5].map{|i| i**2 }</syntaxhighlight>
<syntaxhighlight lang="ruby">[1,2,3,4,5].map{|i| i**2 }</syntaxhighlight>


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


! APPLIES A CALLBACK FUNCTION TO AN ARRAY ;
! APPLIES A CALLBACK FUNCTION TO AN ARRAY ;
Line 3,173: Line 3,173:


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


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<syntaxhighlight lang=smalltalk>#( 1 2.0 'three') do: [:each | each displayNl].</syntaxhighlight>
<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;:
<syntaxhighlight lang=smalltalk>#( 1 2.0 'three') do: #displayNl.</syntaxhighlight>
<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.:
<syntaxhighlight lang=smalltalk>#( 1 2 3 4 5 ) collect: [:n | n * n].</syntaxhighlight>
<syntaxhighlight lang="smalltalk">#( 1 2 3 4 5 ) collect: [:n | n * n].</syntaxhighlight>


=={{header|Sparkling}}==
=={{header|Sparkling}}==
The <tt>foreach</tt> function calls the supplied callback on each element of the (possibly associative) array, passing it each key and the corresponding value:
The <tt>foreach</tt> function calls the supplied callback on each element of the (possibly associative) array, passing it each key and the corresponding value:
<syntaxhighlight lang=sparkling>let numbers = { 1, 2, 3, 4 };
<syntaxhighlight lang="sparkling">let numbers = { 1, 2, 3, 4 };
foreach(numbers, function(idx, num) {
foreach(numbers, function(idx, num) {
print(num);
print(num);
Line 3,192: Line 3,192:


The <tt>map</tt> function applies the transform to each key-value pair and constructs a new array, of which the keys are the keys of the original array, and the corresponding values are the return values of each call to the transform function:
The <tt>map</tt> function applies the transform to each key-value pair and constructs a new array, of which the keys are the keys of the original array, and the corresponding values are the return values of each call to the transform function:
<syntaxhighlight lang=sparkling>let dict = { "foo": 42, "bar": 13, "baz": 37 };
<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;
Line 3,200: Line 3,200:
{{works with|Db2 LUW}} version 9.7 or higher.
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
With SQL PL:
<syntaxhighlight lang=sql pl>
<syntaxhighlight lang="sql pl">
--#SET TERMINATOR @
--#SET TERMINATOR @


Line 3,245: Line 3,245:


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<syntaxhighlight lang=Standard ML>
<syntaxhighlight lang="standard ml">
map f l
map f l
</syntaxhighlight>
</syntaxhighlight>
i.e.
i.e.
<syntaxhighlight 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>
</syntaxhighlight>
Line 3,256: Line 3,256:
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.


<syntaxhighlight 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,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:
<syntaxhighlight lang=SuperCollider>[1, 2, 3].squared // returns [1, 4, 9]</syntaxhighlight>
<syntaxhighlight lang="supercollider">[1, 2, 3].squared // returns [1, 4, 9]</syntaxhighlight>
Anything that is a <tt>Collection</tt> can be used with <tt>collect</tt>:
Anything that is a <tt>Collection</tt> can be used with <tt>collect</tt>:
<syntaxhighlight lang=SuperCollider>[1, 2, 3].collect { |x| x * x }</syntaxhighlight>
<syntaxhighlight lang="supercollider">[1, 2, 3].collect { |x| x * x }</syntaxhighlight>
[[List Comprehension#SuperCollider|List comprehension]] combined with a higher-order function can also be used:
[[List Comprehension#SuperCollider|List comprehension]] combined with a higher-order function can also be used:
<syntaxhighlight lang=SuperCollider>var square = { |x| x * x };
<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 };
Line 3,302: Line 3,302:


=={{header|Swift}}==
=={{header|Swift}}==
<syntaxhighlight lang=swift>func square(n: Int) -> Int {
<syntaxhighlight lang="swift">func square(n: Int) -> Int {
return n * n
return n * n
}
}
Line 3,317: Line 3,317:


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


Line 3,337: Line 3,337:


If I wanted to call "<tt>myfunc</tt>" on each element of <tt>dat</tt> and <tt>dat</tt> were a list:
If I wanted to call "<tt>myfunc</tt>" on each element of <tt>dat</tt> and <tt>dat</tt> were a list:
<syntaxhighlight lang=tcl>foreach var $dat {
<syntaxhighlight lang="tcl">foreach var $dat {
myfunc $var
myfunc $var
}</syntaxhighlight>
}</syntaxhighlight>
Line 3,343: Line 3,343:


if <tt>dat</tt> were an (associative) array, however:
if <tt>dat</tt> were an (associative) array, however:
<syntaxhighlight lang=tcl>foreach name [array names dat] {
<syntaxhighlight lang="tcl">foreach name [array names dat] {
myfunc $dat($name)
myfunc $dat($name)
}</syntaxhighlight>
}</syntaxhighlight>


More functional, with a simple <code>map</code> function:
More functional, with a simple <code>map</code> function:
<syntaxhighlight lang=Tcl>proc map {f list} {
<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,360: Line 3,360:
=={{header|TI-89 BASIC}}==
=={{header|TI-89 BASIC}}==


<syntaxhighlight 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,390: Line 3,390:
JavaScript alike:
JavaScript alike:


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


Using short form of lambda notation:
Using short form of lambda notation:
<syntaxhighlight 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>
</syntaxhighlight>
Line 3,401: Line 3,401:
=={{header|Toka}}==
=={{header|Toka}}==


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


<syntaxhighlight lang=TorqueScript>
<syntaxhighlight lang="torquescript">
function map(%array,%arrayCount,%function)
function map(%array,%arrayCount,%function)
{
{
Line 3,438: Line 3,438:
Now to set up an array:
Now to set up an array:


<syntaxhighlight lang=TorqueScript>
<syntaxhighlight lang="torquescript">
$array[0] = "Hello.";
$array[0] = "Hello.";
$array[1] = "Hi.";
$array[1] = "Hi.";
Line 3,446: Line 3,446:
Now to call the function correctly:
Now to call the function correctly:


<syntaxhighlight lang=TorqueScript>
<syntaxhighlight lang="torquescript">
map("$array",3,"echo");
map("$array",3,"echo");
</syntaxhighlight>
</syntaxhighlight>
Line 3,452: Line 3,452:
Which should result in:
Which should result in:


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


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:


<syntaxhighlight 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,482: Line 3,482:
=={{header|uBasic/4tH}}==
=={{header|uBasic/4tH}}==
We cannot transfer the array address, since uBasic/4tH has only got one, but we can transfer the function pointer and size.
We cannot transfer the array address, since uBasic/4tH has only got one, but we can transfer the function pointer and size.
<lang>S = 5 ' Size of the array
<syntaxhighlight lang="text">S = 5 ' Size of the array


For x = 0 To S - 1 ' Initialize array
For x = 0 To S - 1 ' Initialize array
Line 3,561: Line 3,561:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
{{works with|Bourne Shell}}
<syntaxhighlight lang=bash>map() {
<syntaxhighlight lang="bash">map() {
map_command=$1
map_command=$1
shift
shift
Line 3,572: Line 3,572:
{{works with|pdksh}}
{{works with|pdksh}}
{{works with|zsh}}
{{works with|zsh}}
<syntaxhighlight lang=bash>map() {
<syntaxhighlight lang="bash">map() {
typeset command=$1
typeset command=$1
shift
shift
Line 3,581: Line 3,581:


{{works with|zsh}}
{{works with|zsh}}
<syntaxhighlight 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</syntaxhighlight>
map print $a</syntaxhighlight>
Line 3,588: Line 3,588:
The * is a built-in map operator.
The * is a built-in map operator.
This example shows a map of the successor function over a list of natural numbers.
This example shows a map of the successor function over a list of natural numbers.
<syntaxhighlight lang=Ursala>#import nat
<syntaxhighlight lang="ursala">#import nat


#cast %nL
#cast %nL
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
<syntaxhighlight lang=v>[1 2 3 4] [dup *] map</syntaxhighlight>
<syntaxhighlight lang="v">[1 2 3 4] [dup *] map</syntaxhighlight>


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


Line 3,633: Line 3,633:


=====Implementation=====
=====Implementation=====
<syntaxhighlight lang=vb>
<syntaxhighlight lang="vb">
class callback
class callback
dim sRule
dim sRule
Line 3,653: Line 3,653:


=====Invocation=====
=====Invocation=====
<syntaxhighlight lang=vb>
<syntaxhighlight lang="vb">
dim a1
dim a1
dim cb
dim cb
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.
<syntaxhighlight 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)')
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.


<syntaxhighlight 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,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:
<syntaxhighlight lang=vorpal>A.map(F)</syntaxhighlight>
<syntaxhighlight lang="vorpal">A.map(F)</syntaxhighlight>
If F takes 2 arguments, x and , then simply pass them to map.
If F takes 2 arguments, x and , then simply pass them to map.
They will be passed to F when as it is applied to each element of A.
They will be passed to F when as it is applied to each element of A.
<syntaxhighlight lang=vorpal>A.map(F, x, y)</syntaxhighlight>
<syntaxhighlight lang="vorpal">A.map(F, x, y)</syntaxhighlight>


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


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


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


Line 3,765: Line 3,765:


=={{header|Wren}}==
=={{header|Wren}}==
<syntaxhighlight 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
Line 3,780: Line 3,780:


=={{header|XBS}}==
=={{header|XBS}}==
<syntaxhighlight 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,802: Line 3,802:


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


Line 3,835: Line 3,835:


=={{header|Yacas}}==
=={{header|Yacas}}==
<syntaxhighlight 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})
Line 3,843: Line 3,843:


=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
<syntaxhighlight 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,865: Line 3,865:


=={{header|Zig}}==
=={{header|Zig}}==
<syntaxhighlight 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,882: Line 3,882:


=={{header|zkl}}==
=={{header|zkl}}==
<syntaxhighlight lang=zkl>L(1,2,3,4,5).apply('+(5))</syntaxhighlight>
<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}}==
<syntaxhighlight lang=zonnon>
<syntaxhighlight lang="zonnon">
module Main;
module Main;
type
type
Line 3,936: Line 3,936:


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
<syntaxhighlight 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"