Apply a callback to an array: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 8:
=={{header|11l}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang=11l>V array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
V arrsq = array.map(i -> i * i)
print(arrsq)</langsyntaxhighlight>
{{out}}
<pre>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</pre>
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.)
This was implemented in easy6502.
<langsyntaxhighlight lang=6502asm>define SRC_LO $00
define SRC_HI $01
 
Line 70:
CLC
ADC temp ;2a + a = 3a
RTS</langsyntaxhighlight>
 
 
Line 87:
{{trans|11l}}
The following assumes all code/data is stored/executed in RAM and is therefore mutable.
<langsyntaxhighlight lang=68000devpac>LEA MyArray,A0
MOVE.W #(MyArray_End-MyArray)-1,D7 ;Len(MyArray)-1
MOVEQ #0,D0 ;sanitize D0-D2 to ensure nothing from any previous work will affect our math.
Line 104:
MyArray:
DC.B 1,2,3,4,5,6,7,8,9,10
MyArray_End:</langsyntaxhighlight>
 
 
=={{header|8th}}==
The builtin word "a:map" does this:
<langsyntaxhighlight lang=forth>
[ 1 , 2, 3 ]
' n:sqr
a:map
</syntaxhighlight>
</lang>
That results in the array [1,4,9]
 
Line 120:
ACL2 does not have first-class functions; this is close, however:
 
<langsyntaxhighlight lang=lisp>(defun apply-to-each (xs)
(if (endp xs)
nil
Line 128:
(defun fn-to-apply (x)
(* x x))
</syntaxhighlight>
</lang>
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang=actionscript>package
{
public class ArrayCallback
Line 149:
}
}
}</langsyntaxhighlight>
 
=={{header|Ada}}==
{{works with|GNAT|GPL 2005}}
<langsyntaxhighlight lang=ada>with Ada.Text_Io;
with Ada.Integer_text_IO;
Line 189:
begin
Map(Sample, Display'access);
end Call_Back_Example;</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang=aime>void
map(list l, void (*fp)(object))
{
Line 210:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
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]}}
{{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}}
<langsyntaxhighlight lang=algol68> PROC call back proc = (INT location, INT value)VOID:
(
printf(($"array["g"] = "gl$, location, value))
Line 233:
[4]INT array := ( 1, 4, 9, 16 );
map(array, call back proc)
)</langsyntaxhighlight>
 
{{Out}}
Line 244:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang=algolw>begin
procedure printSquare ( integer value x ) ; writeon( i_w := 1, s_w := 0, " ", x * x );
% applys f to each element of a from lb to ub (inclusive) %
Line 255:
applyI( printSquare, a, 1, 3 )
end
end.</langsyntaxhighlight>
 
=={{header|APL}}==
By default functions in APL work on arrays as it is an array oriented language. Some examples:
 
<langsyntaxhighlight lang=APL> - 1 2 3
¯1 ¯2 ¯3
2 * 1 2 3 4
Line 270:
81 243 729
2187 6561 19683
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang=applescript>on callback for arg
-- Returns a string like "arc has 3 letters"
arg & " has " & (count arg) & " letters"
Line 283:
-- to callback, then speaks the return value.
say (callback for aref)
end repeat</langsyntaxhighlight>
 
If the callback would <code>set arg's contents to "something"</code>, then <code>alist</code> would be mutated.
Line 290:
For a more general implementation of '''map(function, list)''', '''foldl(function, startValue, list)''', and '''filter(predicate, list)''', we could write:
 
<langsyntaxhighlight lang=applescript>on run
set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Line 367:
return lst
end tell
end map</langsyntaxhighlight>
{{Out}}
<pre>{{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}, {2, 4, 6, 8, 10}, 55}</pre>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang=rebol>arr: [1 2 3 4 5]
 
print map arr => [2*&]</langsyntaxhighlight>
{{out}}
Line 381:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang=AutoHotkey>map("callback", "3,4,5")
 
callback(array){
Line 390:
map(callback, array){
%callback%(array)
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight 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
5 25
1 1
2 4
3 9</langsyntaxhighlight>
 
=={{header|Babel}}==
Line 404:
Let us define a squaring operator:
 
<langsyntaxhighlight lang=babel>sq { dup * } <</langsyntaxhighlight>
 
Now, we apply the sq operator over a list and display the result using the lsnum utility:
 
<langsyntaxhighlight lang=babel>( 0 1 1 2 3 5 8 13 21 34 ) { sq ! } over ! lsnum !</langsyntaxhighlight>
 
{{Out}}
Line 415:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang=bbcbasic> DIM a(4)
a() = 1, 2, 3, 4, 5
PROCmap(a(), FNsqrt())
Line 431:
NEXT
ENDPROC
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 442:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang=bracmat>( ( callbackFunction1
= location value
. !arg:(?location,?value)
Line 470:
& mapar$(array,4,callbackFunction2)
& mapar$(array,4,callbackFunction1)
);</langsyntaxhighlight>
{{Out}}
<pre>array[0] = 1
Line 483:
=={{header|Brat}}==
 
<langsyntaxhighlight lang=brat>#Print out each element in array
[:a :b :c :d :e].each { element |
p element
}</langsyntaxhighlight>
 
Alternatively:
 
<langsyntaxhighlight lang=brat>[:a :b :c :d :e].each ->p</langsyntaxhighlight>
 
=={{header|C}}==
 
'''callback.h'''
<langsyntaxhighlight lang=c>#ifndef CALLBACK_H
#define CALLBACK_H
 
Line 510:
void map(int* array, int len, void(*callback)(int,int));
 
#endif</langsyntaxhighlight>
 
'''callback.c'''
<langsyntaxhighlight lang=c>#include <stdio.h>
#include "callback.h"
 
Line 539:
map(array, 4, callbackFunction);
return 0;
}</langsyntaxhighlight>
 
{{Out}}
Line 553:
This version uses the C# 3 lambda notation.
 
<langsyntaxhighlight lang=csharp>int[] intArray = { 1, 2, 3, 4, 5 };
// Simplest method: LINQ, functional
int[] squares1 = intArray.Select(x => x * x).ToArray();
Line 563:
// Or, if you only want to call a function on each element, just use foreach
foreach (var i in intArray)
Console.WriteLine(i * i);</langsyntaxhighlight>
 
{{works with|C sharp|C#|2.0+}}
 
{{works with|Visual C sharp|Visual C#|2005}}
<langsyntaxhighlight lang=csharp>using System;
 
static class Program
Line 601:
Console.WriteLine(value * value);
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 607:
{{works with|g++|4.1.1}}
===C-Style Array===
<langsyntaxhighlight lang=cpp>#include <iostream> //cout for printing
#include <algorithm> //for_each defined here
 
Line 622:
return 0;
}
//prints 1 4 9 16 25</langsyntaxhighlight>
 
===std::vector===
{{libheader|STL}}
<langsyntaxhighlight lang=cpp>#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
#include <vector> // stl vector class
Line 647:
return 0;
}
//prints 1 4 9 16 25</langsyntaxhighlight>
 
More tricky with binary function
<langsyntaxhighlight lang=cpp>#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
#include <vector> // stl vector class
Line 673:
return 0;
}
//prints 1x 2x 3x 4x 5x</langsyntaxhighlight>
 
===Boost.Lambda===
{{libheader|Boost}}
<langsyntaxhighlight lang=cpp>using namespace std;
using namespace boost::lambda;
vector<int> ary(10);
int i = 0;
for_each(ary.begin(), ary.end(), _1 = ++var(i)); // init array
transform(ary.begin(), ary.end(), ostream_iterator<int>(cout, " "), _1 * _1); // square and output</langsyntaxhighlight>
 
===C++11===
<langsyntaxhighlight lang=cpp>#include <vector>
#include <iostream>
#include <algorithm>
Line 699:
std::cout << std::endl;
return 0;
}</langsyntaxhighlight>
 
=={{header|Clean}}==
Line 705:
Define a function and an initial (unboxed) array.
 
<langsyntaxhighlight lang=clean>square x = x * x
 
values :: {#Int}
values = {x \\ x <- [1 .. 10]}</langsyntaxhighlight>
 
One can easily define a map for arrays, which is overloaded and works for all kinds of arrays (lazy, strict, unboxed).
 
<langsyntaxhighlight lang=clean>mapArray f array = {f x \\ x <-: array}</langsyntaxhighlight>
 
Apply the function to the initial array (using a comprehension) and print result.
 
<langsyntaxhighlight lang=clean>Start :: {#Int}
Start = mapArray square values</langsyntaxhighlight>
 
=={{header|Clio}}==
'''Math operations'''
<langsyntaxhighlight lang=clio>[1 2 3 4] * 2 + 1 -> print</langsyntaxhighlight>
'''Quick functions'''
<lang>[1 2 3 4] -> * n: n * 2 + 1 -> print</langsyntaxhighlight>
'''Anonymous function'''
<langsyntaxhighlight lang=clio>[1 2 3 4]
-> * fn n:
n * 2 + 1
-> print</langsyntaxhighlight>
'''Named function'''
<langsyntaxhighlight lang=clio>fn double-plus-one n:
n * 2 + 1
 
[1 2 3 4] -> * double-plus-one -> print</langsyntaxhighlight>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang=lisp>;; apply a named function, inc
(map inc [1 2 3 4])</langsyntaxhighlight>
 
<langsyntaxhighlight lang=lisp>;; apply a function
(map (fn [x] (* x x)) [1 2 3 4])</langsyntaxhighlight>
 
<langsyntaxhighlight lang=lisp>;; shortcut syntax for a function
(map #(* % %) [1 2 3 4])</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight lang=clu>% This procedure will call a given procedure with each element
% of the given array. Thanks to CLU's type parameterization,
% it will work for any type of element.
Line 780:
stream$putl(po, "\nStrings: ")
apply_to_all[string](strings, show_string)
end start_up</langsyntaxhighlight>
{{out}}
<pre>Ints:
Line 799:
 
Basic implementation of a map function:
<langsyntaxhighlight lang=cobol> IDENTIFICATION DIVISION.
PROGRAM-ID. Map.
 
Line 821:
 
GOBACK
.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang=coffeescript>
map = (arr, f) -> (f(e) for e in arr)
arr = [1, 2, 3, 4, 5]
f = (x) -> x * x
console.log map arr, f # prints [1, 4, 9, 16, 25]
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 835:
Imperative: print 1, 2, 3, 4 and 5:
 
<langsyntaxhighlight lang=lisp>(map nil #'print #(1 2 3 4 5))</langsyntaxhighlight>
 
Functional: collect squares into new vector that is returned:
 
<langsyntaxhighlight lang=lisp>(defun square (x) (* x x))
(map 'vector #'square #(1 2 3 4 5))</langsyntaxhighlight>
 
Destructive, like the Javascript example; add 1 to every slot of vector *a*:
 
<langsyntaxhighlight lang=lisp>(defvar *a* (vector 1 2 3))
(map-into *a* #'1+ *a*)</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang=oberon2>
MODULE Callback;
IMPORT StdLog;
Line 904:
END Do;
END Callback.
</syntaxhighlight>
</lang>
Execute: ^Q Callback.Do<br/>
{{Out}}
Line 933:
=={{header|Crystal}}==
Calling with a block
<langsyntaxhighlight lang=ruby>values = [1, 2, 3]
 
new_values = values.map do |number|
Line 939:
end
 
puts new_values #=> [2, 4, 6]</langsyntaxhighlight>
 
Calling with a function/method
<langsyntaxhighlight lang=ruby>values = [1, 2, 3]
 
def double(number)
Line 953:
new_values = values.map &->double(Int32)
 
puts new_values #=> [2, 4, 6]</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang=d>import std.stdio, std.algorithm;
 
void main() {
Line 962:
auto m = items.map!(x => x + 5)();
writeln(m);
}</langsyntaxhighlight>
{{out}}
<pre>[6, 7, 8, 9, 10]</pre>
 
=={{header|Delphi}}==
<langsyntaxhighlight lang=Delphi>
// Declare the callback function
procedure callback(const AInt:Integer);
Line 985:
callback(myArray[i]);
end.
</syntaxhighlight>
</lang>
 
=={{header|Dyalect}}==
 
<langsyntaxhighlight lang=Dyalect>func Array.Select(pred) {
let ys = []
for x in this when pred(x) {
Line 1,000:
var squares = arr.Select(x => x * x)
print(squares)</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
There is a <code>map</code> builtin that does just this.
<langsyntaxhighlight lang=dejavu>!. map @++ [ 1 4 8 ]
 
#implemented roughly like this:
Line 1,011:
# for i in lst:
# f i
# [</langsyntaxhighlight>
{{out}}
<pre>[ 2 5 9 ]</pre>
Line 1,017:
=={{header|E}}==
 
<langsyntaxhighlight lang=e>def array := [1,2,3,4,5]
def square(value) {
return value * value
}</langsyntaxhighlight>
 
Example of builtin iteration:
 
<langsyntaxhighlight lang=e>def callback(index, value) {
println(`Item $index is $value.`)
}
array.iterate(callback)</langsyntaxhighlight>
 
There is no built-in map function '''yet'''.
Line 1,033:
returning a plain list (which is usually an array in implementation).
 
<langsyntaxhighlight lang=e>def map(func, collection) {
def output := [].diverge()
for item in collection {
Line 1,040:
return output.snapshot()
}
println(map(square, array))</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang=scheme>
(vector-map sqrt #(0 4 16 49))
→ #( 0 2 4 7)
Line 1,055:
v[2] = 4
→ #( 4 9 16)
</syntaxhighlight>
</lang>
 
=={{header|Efene}}==
 
<langsyntaxhighlight lang=efene>square = fn (N) {
N * N
}
Line 1,091:
io.format("squares3 : ~p~n", [squares3(Numbers)])
}
</syntaxhighlight>
</lang>
 
=={{header|EGL}}==
<langsyntaxhighlight lang=EGL>delegate callback( i int ) returns( int ) end
 
program ApplyCallbackToArray
Line 1,113:
return( i * i );
end
end</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 5.0 :
<langsyntaxhighlight lang=elena>import system'routines;
 
PrintSecondPower(n){ console.writeLine(n * n) }
Line 1,124:
{
new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.forEach:PrintSecondPower
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang=Elixir>
Enum.map([1, 2, 3], fn(n) -> n * 2 end)
Enum.map [1, 2, 3], &(&1 * 2)
</syntaxhighlight>
</lang>
 
{{Out}}
Line 1,140:
A list would be more commonly used in Erlang rather than an array.
 
<langsyntaxhighlight lang=Erlang>
1> L = [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.
Line 1,150:
2> lists:foreach(fun(X) -> io:format("~w ",[X]) end, L).
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.
 
<langsyntaxhighlight lang=Erlang>
3> lists:map(fun(X) -> X + 1 end, L).
[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.
 
<langsyntaxhighlight lang=Erlang>
4> lists:foldl(fun(X, Sum) -> X + Sum end, 0, L).
6
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
Line 1,192:
PRINT
END PROGRAM
</syntaxhighlight>
</lang>
This example shows how to pass a function to a procedure.
{{Out}}
Line 1,200:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang=euphoria>function apply_to_all(sequence s, integer f)
-- apply a function to all elements of a sequence
sequence result
Line 1,217:
-- add1() is visible here, so we can ask for its routine id
? apply_to_all({1, 2, 3}, routine_id("add1"))
-- displays {2,3,4}</langsyntaxhighlight>
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.
Line 1,223:
=={{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.
<langsyntaxhighlight lang=fsharp>let evenp x = x % 2 = 0
let result = Array.map evenp [| 1; 2; 3; 4; 5; 6 |]</langsyntaxhighlight>
The same can be done using anonymous functions, this time squaring the members of the input array.
<langsyntaxhighlight lang=fsharp>let result = Array.map (fun x -> x * x) [|1; 2; 3; 4; 5|]</langsyntaxhighlight>
Use ''iter'' if the applied function does not return a value.
<langsyntaxhighlight lang=fsharp>Array.iter (fun x -> printfn "%d" x) [|1; 2; 3; 4; 5|]</langsyntaxhighlight>
 
=={{header|Factor}}==
Print each element squared:
<langsyntaxhighlight lang=factor>{ 1 2 3 4 } [ sq . ] each</langsyntaxhighlight>
 
Collect return values:
<langsyntaxhighlight lang=factor>{ 1 2 3 4 } [ sq ] map</langsyntaxhighlight>
 
=={{header|Fantom}}==
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.
 
<langsyntaxhighlight lang=fantom>
class Main
{
Line 1,251:
}
}
</syntaxhighlight>
</lang>
 
{{Out}}
Line 1,265:
=={{header|FBSL}}==
'''User-defined mapping function:'''
<langsyntaxhighlight lang=qbasic>#APPTYPE CONSOLE
 
FOREACH DIM e IN MyMap(Add42, {1, 2, 3})
Line 1,281:
END FUNCTION
 
FUNCTION Add42(n): RETURN n + 42: END FUNCTION</langsyntaxhighlight>
{{Out}}
<pre>43 44 45
Line 1,287:
 
'''Standard MAP() function:'''
<langsyntaxhighlight lang=qbasic>#APPTYPE CONSOLE
 
DIM languages[] = {{"English", {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}}, _
Line 1,303:
MAP(NameANumber, lang[0], 1 TO 10, lang[1])
PRINT LPAD("", 40, "-")
END SUB</langsyntaxhighlight>
{{Out}}
<pre>The number 1 is called "one" in English
Line 1,333:
This is a word that will call a given function on each cell in an array.
 
<langsyntaxhighlight lang=forth>: map ( addr n fn -- )
-rot cells bounds do i @ over execute i ! cell +loop ;</langsyntaxhighlight>
 
{{Out|Example usage}}
<langsyntaxhighlight lang=forth>create data 1 , 2 , 3 , 4 , 5 ,
data 5 ' 1+ map \ adds one to each element of data</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 1,344:
 
{{Works with |Fortran|ISO 95 and later}}
<langsyntaxhighlight lang=fortran>module arrCallback
contains
elemental function cube( x )
Line 1,352:
cube = x * x * x
end function cube
end module arrCallback</langsyntaxhighlight>
 
<langsyntaxhighlight lang=fortran>program testAC
use arrCallback
implicit none
Line 1,370:
write(*,*) b(i,:)
end do
end program testAC</langsyntaxhighlight>
 
{{Works with|ANSI FORTRAN| 77 (with MIL-STD-1753 structured DO) and later}}
<langsyntaxhighlight lang=fortran> program test
C
C-- Declare array:
Line 1,386:
end do
C
end</langsyntaxhighlight>
 
=={{header|FP}}==
<langsyntaxhighlight lang=fp>{square * . [id, id]}
& square: <1,2,3,4,5></langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang=freebasic>' FB 1.05.0 Win64
 
Sub PrintEx(n As Integer)
Line 1,411:
Print
Print "Press any key to quit the program"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,430:
 
=={{header|Frink}}==
<langsyntaxhighlight lang=frink>
f = {|x| x^2} // Anonymous function to square input
a = [1,2,3,5,7]
println[map[f, a]]
</syntaxhighlight>
</lang>
 
=={{header|FunL}}==
<langsyntaxhighlight lang=funl>[1, 2, 3].foreach( println )
 
[1, 2, 3].foreach( a -> println(2a) )</langsyntaxhighlight>
 
{{out}}
Line 1,453:
 
=={{header|Futhark}}==
<langsyntaxhighlight lang=Futhark>
map f l
</syntaxhighlight>
</lang>
e.g.
<langsyntaxhighlight lang=Futhark>
map (\x->x+1) [1,2,3] -- [2,3,4]
</syntaxhighlight>
</lang>
or equivalently
<langsyntaxhighlight lang=Futhark>
map (+1) [1,2,3] -- [2,3,4]
</syntaxhighlight>
</lang>
 
=={{header|Fōrmulæ}}==
Line 1,474:
 
=={{header|GAP}}==
<langsyntaxhighlight lang=gap>a := [1 .. 4];
b := ShallowCopy(a);
 
Line 1,494:
 
b;
# [ 1 .. 4 ]</langsyntaxhighlight>
 
=={{header|Go}}==
Line 1,501:
 
Perhaps in contrast to Ruby, it is idiomatic in Go to use the for statement:
<langsyntaxhighlight lang=go>package main
 
import "fmt"
Line 1,509:
fmt.Println(i * i)
}
}</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang=go>package main
 
import "fmt"
Line 1,542:
return i * i
}))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,556:
 
Print each value in a list
<langsyntaxhighlight lang=groovy>[1,2,3,4].each { println it }</langsyntaxhighlight>
 
Create a new list containing the squares of another list
<langsyntaxhighlight lang=groovy>[1,2,3,4].collect { it * it }</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 1,565:
===List===
{{works with|GHC}}
<langsyntaxhighlight lang=haskell>let square x = x*x
let values = [1..10]
map square values</langsyntaxhighlight>
 
Using list comprehension to generate a list of the squared values
<langsyntaxhighlight lang=haskell>[square x | x <- values]</langsyntaxhighlight>
 
More directly
<langsyntaxhighlight lang=haskell>[1 .. 10] >>= pure . (^ 2)</langsyntaxhighlight>
 
Or with one less layer of monadic wrapping
<langsyntaxhighlight lang=haskell>(^ 2) <$> [1..10]</langsyntaxhighlight>
 
Using function composition to create a function that will print the squares of a list
<langsyntaxhighlight lang=haskell>let printSquares = mapM_ (print.square)
printSquares values</langsyntaxhighlight>
 
===Array===
{{works with|GHC|7.10.3}}
<langsyntaxhighlight lang=haskell>import Data.Array (Array, listArray)
 
square :: Int -> Int
Line 1,593:
 
main :: IO ()
main = print $ fmap square values</langsyntaxhighlight>
{{Out}}
<pre>array (1,10) [(1,1),(2,4),(3,9),(4,16),(5,25),(6,36),(7,49),(8,64),(9,81),(10,100)]</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang=icon>procedure main()
local lst
lst := [10, 20, 30, 40]
Line 1,606:
procedure callback(p,arg)
return p(" -> ", arg)
end</langsyntaxhighlight>
 
=={{header|IDL}}==
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
 
<langsyntaxhighlight lang=idl>b = a^3</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang=io>list(1,2,3,4,5) map(squared)</langsyntaxhighlight>
 
=={{header|J}}==
 
'''Solution''':
<syntaxhighlight lang =j> "_1</langsyntaxhighlight>
 
'''Example''':
<langsyntaxhighlight lang=j> callback =: *:
array =: 1 2 3 4 5
callback"_1 array
1 4 9 16 25</langsyntaxhighlight>
 
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:
while the <code>IntToInt</code> is used to replace the array values.
 
<langsyntaxhighlight lang=java>public class ArrayCallback7 {
 
interface IntConsumer {
Line 1,683:
});
}
}</langsyntaxhighlight>
 
Using Java 8 streams:
{{works with|Java|8}}
 
<langsyntaxhighlight lang=java>import java.util.Arrays;
 
public class ArrayCallback {
Line 1,704:
System.out.println("sum: " + sum);
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
 
===ES3===
<langsyntaxhighlight lang=javascript>function map(a, func) {
var ret = [];
for (var i = 0; i < a.length; i++) {
Line 1,717:
}
 
map([1, 2, 3, 4, 5], function(v) { return v * v; });</langsyntaxhighlight>
 
===ES5===
<langsyntaxhighlight lang=javascript>[1, 2, 3, 4, 5].map(function(v) { return v * v; });</langsyntaxhighlight>
 
===ES6===
<langsyntaxhighlight lang=javascript>[1, 2, 3, 4, 5].map(v => v * v);</langsyntaxhighlight>
 
The result is always:
Line 1,730:
 
=={{header|Joy}}==
<langsyntaxhighlight lang=joy>[1 2 3 4 5] [dup *] map.</langsyntaxhighlight>
 
=={{header|jq}}==
<langsyntaxhighlight lang=jq># Illustration of map/1 using the builtin filter: exp
map(exp) # exponentiate each item in the input list
 
Line 1,747:
# Elementwise operation
[.[] + 1 ] # add 1 to each element of the input array
</langsyntaxhighlight>Here is a transcript illustrating how the last of these jq expressions can be evaluated:
<langsyntaxhighlight lang=jq>$ jq -c ' [.[] + 1 ]'
[0, 1 , 10]
[1,2,11]</langsyntaxhighlight>
 
=={{header|Jsish}}==
<langsyntaxhighlight lang=javascript>/* Apply callback, in Jsish using array.map() */
;[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; });
 
Line 1,760:
[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; }) ==> [ 1, 4, 9, 16, 25 ]
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,768:
=={{header|Julia}}==
{{works with|Julia|0.6}}
<langsyntaxhighlight lang=julia>numbers = [1, 3, 5, 7]
 
@show [n ^ 2 for n in numbers] # list comprehension
Line 1,775:
@show [n * n for n in numbers] # no need for a function,
@show numbers .* numbers # element-wise operation
@show numbers .^ 2 # includes .+, .-, ./, comparison, and bitwise operations as well</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang=scala>fun main(args: Array<String>) {
val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // build
val function = { i: Int -> i * i } // function to apply
val list = array.map { function(it) } // process each item
println(list) // print results
}</langsyntaxhighlight>
{{out}}
<pre>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</pre>
 
=={{header|Klingphix}}==
<langsyntaxhighlight lang=Klingphix>include ..\Utilitys.tlhy
 
( 1 2 3 4 ) [dup *] map
Line 1,794:
pstack
 
" " input</langsyntaxhighlight>
{{out}}
<pre>((1, 4, 9, 16))</pre>
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang=Scheme>
{A.map {lambda {:x} {* :x :x}} {A.new 1 2 3 4 5 6 7 8 9 10}}
-> [1,4,9,16,25,36,49,64,81,100]
</syntaxhighlight>
</lang>
 
=={{header|Lang5}}==
<langsyntaxhighlight lang=lang5>: square(*) dup * ;
[1 2 3 4 5] square . "\n" .
[1 2 3 4 5] 'square apply . "\n" .</langsyntaxhighlight>
 
=={{header|langur}}==
<langsyntaxhighlight lang=langur>writeln map f{^2}, 1..10</langsyntaxhighlight>
 
{{out}}
Line 1,816:
 
=={{header|Lasso}}==
<langsyntaxhighlight lang=Lasso>define cube(n::integer) => #n*#n*#n
 
local(
Line 1,827:
}
 
#mycube</langsyntaxhighlight>
-> array(1, 8, 27, 64, 125)
 
=={{header|Lisaac}}==
<langsyntaxhighlight lang=Lisaac>+ a : ARRAY(INTEGER);
+ b : {INTEGER;};
 
Line 1,844:
};
 
a.foreach b;</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang=logo>to square :x
output :x * :x
end
show map "square [1 2 3 4 5] ; [1 4 9 16 25]
show map [? * ?] [1 2 3 4 5] ; [1 4 9 16 25]
foreach [1 2 3 4 5] [print square ?] ; 1 4 9 16 25, one per line</langsyntaxhighlight>
 
=={{header|Lua}}==
 
Say we have an array:
<langsyntaxhighlight lang=lua>myArray = {1, 2, 3, 4, 5}</langsyntaxhighlight>
A map function for this would be
<langsyntaxhighlight lang=lua>map = function(f, data)
local result = {}
for k,v in ipairs(data) do
Line 1,865:
end
return result
end</langsyntaxhighlight>
Together with our array and a square function this yields:
<langsyntaxhighlight lang=lua>myFunc = function(x) return x*x end
 
print(unpack( map(myFunc, myArray) ))
--> 1 4 9 16 25</langsyntaxhighlight>
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,
Line 1,876:
 
=={{header|M2000 Interpreter}}==
<langsyntaxhighlight lang=M2000 Interpreter>
a=(1,2,3,4,5)
b=lambda->{
Line 1,904:
Print s=>sum=115
 
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
<langsyntaxhighlight lang=M4>define(`foreach', `pushdef(`$1')_foreach($@)popdef(`$1')')dnl
define(`_arg1', `$1')dnl
define(`_foreach', `ifelse(`$2', `()', `',
Line 1,915:
dnl
define(`z',`eval(`$1*2') ')dnl
apply(`(1,2,3)',`z')</langsyntaxhighlight>
 
{{Out}}
Line 1,925:
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.
<langsyntaxhighlight lang=Maple>
> map( sqrt, [ 1.1, 3.2, 5.7 ] );
[1.048808848, 1.788854382, 2.387467277]
Line 1,937:
> (x -> x + 1)~( { 1, 3, 5 } );
{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.
<langsyntaxhighlight lang=Maple>
> a := Array( [ 1.1, 3.2, 5.7 ] );
a := [1.1, 3.2, 5.7]
Line 1,954:
> a;
[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.
<langsyntaxhighlight lang=Maple>
> map[inplace]( sqrt, a );
[1.048808848, 1.788854382, 2.387467277]
Line 1,962:
> a;
[1.048808848, 1.788854382, 2.387467277]
</syntaxhighlight>
</lang>
The Array a has been modified.
 
It is also possible to pass additional arguments to the mapped procedure.
<langsyntaxhighlight lang=Maple>
> map( `+`, [ 1, 2, 3 ], 3 );
[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.
<langsyntaxhighlight lang=Maple>
> map2( `-`, 5, [ 1, 2, 3 ] );
[4, 3, 2]
Line 1,977:
> map[2]( `/`, 5, [ 1, 2, 3 ] );
[5, 5/2, 5/3]
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}//{{header|Wolfram Language}}==
<langsyntaxhighlight lang=Mathematica>(#*#)& /@ {1, 2, 3, 4}
Map[Function[#*#], {1, 2, 3, 4}]
Map[((#*#)&,{1,2,3,4}]
Map[Function[w,w*w],{1,2,3,4}]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
Line 1,989:
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.
<langsyntaxhighlight lang=MATLAB>>> array = [1 2 3 4 5]
 
array =
Line 2,023:
Column 5
 
-3.380515006246586</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang=maxima>/* for lists or sets */
 
map(sin, [1, 2, 3, 4]);
Line 2,033:
/* for matrices */
 
matrixmap(sin, matrix([1, 2], [2, 4]));</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<langsyntaxhighlight lang=min>(1 2 3 4 5) (sqrt puts) foreach ; print each square root
(1 2 3 4 5) 'sqrt map ; collect return values</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang=modula3>MODULE Callback EXPORTS Main;
 
IMPORT IO, Fmt;
Line 2,066:
BEGIN
Map(sample, NUMBER(sample), callback);
END Callback.</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight lang=Nanoquery>// create a list of numbers 1-10
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Line 2,081:
// display the squared list
println numbers</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Line 2,088:
=={{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).
<langsyntaxhighlight lang=Nemerle>def seg = array[1, 2, 3, 5, 8, 13];
def squares = seq.Map(x => x*x);</langsyntaxhighlight>
 
=={{header|NetLogo}}==
<langsyntaxhighlight lang=NetLogo>
;; NetLogo “anonymous procedures”
;; stored in a variable, just to show it can be done.
let callback [ [ x ] x * x ]
show (map callback [ 1 2 3 4 5 ])
</syntaxhighlight>
</lang>
 
=={{header|NewLISP}}==
 
<langsyntaxhighlight lang=NewLISP>> (map (fn (x) (* x x)) '(1 2 3 4))
(1 4 9 16)
</syntaxhighlight>
</lang>
 
=={{header|NGS}}==
<langsyntaxhighlight lang=NGS>{
[1, 2, 3, 4, 5].map(F(x) x*x)
}</langsyntaxhighlight>
 
=={{header|Nial}}==
 
<langsyntaxhighlight lang=nial>each (* [first, first] ) 1 2 3 4
=1 4 9 16</langsyntaxhighlight>
 
=={{header|Nim}}==
 
<langsyntaxhighlight lang=nim>var arr = @[1,2,3,4]
arr.apply proc(some: var int) = echo(some, " squared = ", some*some)</langsyntaxhighlight>
 
{{Out}}
Line 2,128:
=={{header|Oberon-2}}==
{{Works with|oo2x}}
<langsyntaxhighlight lang=oberon2>
MODULE ApplyCallBack;
IMPORT
Line 2,217:
Init(a);r := Map3(Fun3,a);Show(r^);
END ApplyCallBack.
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,226:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang=objeck>
use Structure;
 
Line 2,248:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
This function is part of the standard library:
 
<syntaxhighlight lang =ocaml>Array.map</langsyntaxhighlight>
 
Usage example:
<langsyntaxhighlight lang=ocaml>let square x = x * x;;
let values = Array.init 10 ((+) 1);;
Array.map square values;;</langsyntaxhighlight>
 
Or with lists (which are more typical in OCaml):
<langsyntaxhighlight lang=ocaml>let values = [1;2;3;4;5;6;7;8;9;10];;
List.map square values;;</langsyntaxhighlight>
 
Use <tt>iter</tt> if the applied function does not return a value.
 
<langsyntaxhighlight lang=ocaml>Array.iter (fun x -> Printf.printf "%d" x) [|1; 2; 3; 4; 5|];;</langsyntaxhighlight>
<langsyntaxhighlight lang=ocaml>List.iter (fun x -> Printf.printf "%d" x) [1; 2; 3; 4; 5];;</langsyntaxhighlight>
 
with partial application we can also write:
 
<langsyntaxhighlight lang=ocaml>Array.iter (Printf.printf "%d") [|1; 2; 3; 4; 5|];;</langsyntaxhighlight>
<langsyntaxhighlight lang=ocaml>List.iter (Printf.printf "%d") [1; 2; 3; 4; 5];;</langsyntaxhighlight>
 
=={{header|Octave}}==
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.
 
<langsyntaxhighlight lang=octave>function e = f(x, y)
e = x^2 + exp(-1/(y+1));
endfunction
Line 2,284:
% f([2,3], [1,4]) gives and error, but
arrayfun(@f, [2, 3], [1,4])
% works</langsyntaxhighlight>
 
(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:
=={{header|Oforth}}==
apply allows to perform a function on all elements of a list :
<langsyntaxhighlight lang=Oforth>0 #+ [ 1, 2, 3, 4, 5 ] apply</langsyntaxhighlight>
 
map regroups all results into a new list :
<langsyntaxhighlight lang=Oforth>#sq [ 1, 2, 3, 4, 5 ] map</langsyntaxhighlight>
 
=={{header|Ol}}==
Apply custom callback (lambda) to every element of list.
<langsyntaxhighlight lang=scheme>
(for-each
(lambda (element)
Line 2,303:
'(1 2 3 4 5))
; ==> 12345
</syntaxhighlight>
</lang>
 
=={{header|ooRexx}}==
ooRexx doesn't directly support callbacks on array items, but this is pretty easy to implement using Routine objects.
<langsyntaxhighlight lang=ooRexx>start = .array~of("Rick", "Mike", "David", "Mark")
new = map(start, .routines~reversit)
call map new, .routines~sayit
Line 2,330:
use arg string
say string
return .true -- called as a function, so a result is required</langsyntaxhighlight>
{{out}}
<pre>kciR
Line 2,339:
=={{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>.
<langsyntaxhighlight lang=c>#include <order/interpreter.h>
 
ORDER_PP( 8tuple_map(8fn(8X, 8times(8X, 8X)), 8tuple(1, 2, 3, 4, 5)) )
Line 2,348:
 
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</langsyntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang=oz>declare
fun{Square A}
A*A
Line 2,363:
%% apply a FUNCTION to every element
Result = {Map Lst Square}
{Show Result}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.2 and above}}
<langsyntaxhighlight lang=parigp>callback(n)=n+n;
apply(callback, [1,2,3,4,5])</langsyntaxhighlight>
 
This should be contrasted with <code>call</code>:
<langsyntaxhighlight lang=parigp>call(callback, [1,2,3,4,5])</langsyntaxhighlight>
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:
 
=={{header|Perl}}==
<langsyntaxhighlight lang=perl># create array
my @a = (1, 2, 3, 4, 5);
 
Line 2,407:
 
# filter an array
my @e = grep { $_ % 2 == 0 } @a; # @e is now (2, 4)</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<langsyntaxhighlight 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>
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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,433:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight lang=Phixmonti>/# Rosetta Code problem: http://rosettacode.org/wiki/Apply_a_callback_to_an_array
by Galileo, 05/2022 #/
 
Line 2,451:
getid square map
 
pstack</langsyntaxhighlight>
{{out}}
<pre>
Line 2,459:
 
=={{header|PHP}}==
<langsyntaxhighlight lang=php>function cube($n)
{
return($n * $n * $n);
Line 2,466:
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);</langsyntaxhighlight>
 
=={{header|Picat}}==
Picat doesn't support anonymous (lambda) functions so the function must be defined in the program to be used by - say - map/2.
There are - however - quite a few ways without proper lambdas, using map/2, apply/2, or list comprehensions.
<langsyntaxhighlight lang=Picat>go =>
L = 1..10,
 
Line 2,491:
% Some function
fun(X) = X*X.
</syntaxhighlight>
</lang>
 
{{trans|Prolog}}
Line 2,499:
 
Note that fun2/2 is not a function so map/2 or apply/2 cannot be used here.
<langsyntaxhighlight lang=Picat>go2 =>
L = 1..10,
 
Line 2,508:
println([B : A in L, bp.fun2(A,B)]),
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.
 
=={{header|PicoLisp}}==
<langsyntaxhighlight lang=PicoLisp>: (mapc println (1 2 3 4 5)) # Print numbers
1
2
Line 2,528:
 
: (mapcar if '(T NIL T NIL) '(1 2 3 4) '(5 6 7 8)) # Conditional function
-> (1 6 3 8)</langsyntaxhighlight>
 
=={{header|Pike}}==
<langsyntaxhighlight lang=pike>int cube(int n)
{
return n*n*n;
Line 2,538:
array(int) a = ({ 1,2,3,4,5 });
array(int) b = cube(a[*]); // automap operator
array(int) c = map(a, cube); // conventional map function</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang=PL/I> declare x(5) initial (1,3,5,7,8);
x = sqrt(x);
x = sin(x);</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang=plsql>-- Let's create a generic class with one method to be used as an interface:
create or replace
TYPE callback AS OBJECT (
Line 2,622:
PKG_CALLBACK.TEST_CALLBACK();
END;
/</langsyntaxhighlight>
 
=={{header|Pop11}}==
 
<langsyntaxhighlight lang=pop11>;;; Define a procedure
define proc(x);
printf(x*x, '%p,');
Line 2,635:
 
;;; Apply procedure to array
appdata(ar, proc);</langsyntaxhighlight>
 
If one wants to create a new array consisting of transformed values then procedure mapdata may be more convenient.
Line 2,641:
=={{header|PostScript}}==
The <code>forall</code> operator applies a procedure to each element of an array, a packed array or a string.
<langsyntaxhighlight lang=postscript>[1 2 3 4 5] { dup mul = } forall</langsyntaxhighlight>
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>:
<langsyntaxhighlight lang=postscript>[ [1 2 3 4 5] { dup mul } forall ]</langsyntaxhighlight>
 
{{libheader|initlib}}
<langsyntaxhighlight lang=postscript>
[1 2 3 4 5] {dup *} map
</syntaxhighlight>
</lang>
 
=={{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:
<langsyntaxhighlight lang=powershell>1..5 | ForEach-Object { $_ * $_ }</langsyntaxhighlight>
To recreate a ''map'' function, found in other languages the same method applies:
<langsyntaxhighlight lang=powershell>function map ([array] $a, [scriptblock] $s) {
$a | ForEach-Object $s
}
map (1..5) { $_ * $_ }</langsyntaxhighlight>
 
=={{header|Prolog}}==
Prolog doesn't have arrays, but we can do it with lists. This can be done in the console mode.
<langsyntaxhighlight lang=Prolog> ?- assert((fun(X, Y) :- Y is 2 * X)).
true.
 
?- maplist(fun, [1,2,3,4,5], L).
L = [2,4,6,8,10].
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang=PureBasic>Procedure Cube(Array param.i(1))
Protected n.i
For n = 0 To ArraySize(param())
Line 2,684:
Next
 
Cube(AnArray()) </langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang=python>def square(n):
return n * n
Line 2,704:
 
import itertools
isquares2 = itertools.imap(square, numbers) # iterator, lazy</langsyntaxhighlight>
To print squares of integers in the range from 0 to 9, type:
<langsyntaxhighlight lang=python>print " ".join(str(n * n) for n in range(10))</langsyntaxhighlight>
Or:
<langsyntaxhighlight lang=python>print " ".join(map(str, map(square, range(10))))</langsyntaxhighlight>
Result:
<langsyntaxhighlight lang=python>0 1 4 9 16 25 36 49 64 81</langsyntaxhighlight>
 
=={{header|QB64}}==
<langsyntaxhighlight lang=QB64>
'Task
'Take a combined set of elements and apply a function to each element.
Line 2,750:
End Sub
 
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
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.
 
<langsyntaxhighlight lang=Quackery>/O> [ 3 ** ] is cubed ( n --> n )
...
 
Line 2,778:
...
 
Stack: [ 1 8 27 64 125 216 343 512 729 1000 ]</langsyntaxhighlight>
 
=={{header|R}}==
Many functions can take advantage of implicit vectorisation, e.g.
<langsyntaxhighlight lang=R>cube <- function(x) x*x*x
elements <- 1:5
cubes <- cube(elements)</langsyntaxhighlight>
Explicit looping over array elements is also possible.
<langsyntaxhighlight lang=R>cubes <- numeric(5)
for(i in seq_along(cubes))
{
cubes[i] <- cube(elements[i])
}</langsyntaxhighlight>
Loop syntax can often simplified using the [http://stat.ethz.ch/R-manual/R-patched/library/base/html/apply.html *apply] family of functions.
<langsyntaxhighlight lang=R>elements2 <- list(1,2,3,4,5)
cubes <- sapply(elements2, cube)</langsyntaxhighlight>
In each case above, the value of 'cubes' is
1 8 27 64 125
Line 2,799:
=={{header|Racket}}==
 
<langsyntaxhighlight lang=racket>
#lang racket
 
Line 2,807:
;; the usual functional `map'
(vector-map sqr #(1 2 3 4 5))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,813:
{{works with|Rakudo|2015.10-11}}
 
<langsyntaxhighlight lang=perl6>sub function { 2 * $^x + 3 };
my @array = 1 .. 5;
 
Line 2,832:
# we neither need a variable for the array nor for the function
say [1,2,3]>>.&({ $^x + 1});
</syntaxhighlight>
</lang>
 
=={{header|Raven}}==
<langsyntaxhighlight lang=raven># To print the squared elements
[1 2 3 4 5] each dup * print</langsyntaxhighlight>
 
<langsyntaxhighlight lang=raven># To obtain a new array
group [1 2 3 4 5] each
dup *
list</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight lang=REBOL>REBOL [
Title: "Array Callback"
URL: http://rosettacode.org/wiki/Apply_a_callback_to_an_Array
Line 2,869:
 
print [crlf "Applying native function with 'map':"]
assert [[2 4 6] = map :square-root [4 16 36]]</langsyntaxhighlight>
 
{{Out}}
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:
 
<langsyntaxhighlight lang=Retro>{ #1 #2 #3 #4 #5 } [ #10 * ] a:map [ n:put sp ] a:for-each</langsyntaxhighlight>
 
=={{header|REXX}}==
<langsyntaxhighlight 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.*/
parse arg # . /*obtain an optional value from the CL.*/
Line 2,910:
/*──────────────────────────────────────────────────────────────────────────────────────*/
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</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 2,945:
 
=={{header|Ring}}==
<langsyntaxhighlight lang=ring>
for x in [1,2,3,4,5]
x = x*x
next
</syntaxhighlight>
</lang>
 
=={{header|RLaB}}==
Line 2,965:
Consider an example:
 
<langsyntaxhighlight lang=RLaB>
>> x = rand(2,4)
0.707213207 0.275298961 0.396757763 0.232312312
Line 2,972:
0.649717845 0.271834652 0.386430003 0.230228332
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
'for' or 'while' loops are slow in interpreted languages, and RLaB is no exception.
 
<langsyntaxhighlight lang=RLaB>
x = rand(2,4);
y = zeros(2,4);
Line 2,987:
}
}
</syntaxhighlight>
</lang>
 
 
Line 2,994:
function 'members' which returns a string vector with the names of the elements of the list.
 
<langsyntaxhighlight lang=RLaB>
x = <<>>;
for (i in 1:9)
Line 3,006:
y.[i] = sin( x.[i] );
}
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
You could use a traditional "for i in arr" approach like below:
<langsyntaxhighlight lang=ruby>for i in [1,2,3,4,5] do
puts i**2
end</langsyntaxhighlight>
 
Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk)
<langsyntaxhighlight lang=ruby>[1,2,3,4,5].each{ |i| puts i**2 }</langsyntaxhighlight>
 
To create a new array of each value squared
<langsyntaxhighlight lang=ruby>[1,2,3,4,5].map{ |i| i**2 }</langsyntaxhighlight>
 
=={{header|Rust}}==
 
<langsyntaxhighlight lang=rust>fn echo(n: &i32) {
println!("{}", n);
}
Line 3,030:
a = [1, 2, 3, 4, 5];
let _: Vec<_> = a.into_iter().map(echo).collect();
}</langsyntaxhighlight>
 
=={{header|Salmon}}==
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.
 
<langsyntaxhighlight lang=Salmon>function apply(list, ageless to_apply)
(comprehend(x; list) (to_apply(x)));
 
Line 3,042:
 
iterate(x; apply([0...9], square))
x!;</langsyntaxhighlight>
 
With short identifiers:
 
<langsyntaxhighlight lang=Salmon>include "short.salm";
 
fun apply(list, ageless to_apply)
Line 3,054:
 
iter(x; apply([0...9], square))
x!;</langsyntaxhighlight>
 
With the numbers given as a list of individual elements:
 
<langsyntaxhighlight lang=Salmon>function apply(list, to_apply)
(comprehend(x; list) (to_apply(x)));
 
Line 3,064:
 
iterate(x; apply([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], square))
x!;</langsyntaxhighlight>
 
=={{header|Sather}}==
<langsyntaxhighlight lang=sather>class MAIN is
do_something(i:INT):INT is
return i * i;
Line 3,078:
loop #OUT + a.elt! + "\n"; end;
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang=scala>val l = List(1,2,3,4)
l.foreach {i => println(i)}</langsyntaxhighlight>
 
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(_))</langsyntaxhighlight>
Same for an array
<langsyntaxhighlight lang=scala>val a = Array(1,2,3,4)
a.foreach {i => println(i)}
a.foreach(println(_)) '' // same as previous line''</langsyntaxhighlight>
 
Or for an externally defined function:
<langsyntaxhighlight lang=scala>def doSomething(in: int) = {println("Doing something with "+in)}
l.foreach(doSomething)</langsyntaxhighlight>
 
There is also a ''for'' syntax, which is internally rewritten to call foreach. A foreach method must be defined on ''a''
<langsyntaxhighlight lang=scala>for(val i <- a) println(i)</langsyntaxhighlight>
 
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)
<langsyntaxhighlight lang=scala>val squares = l.map{i => i * i} ''//squares is'' List(1,4,9,16)</langsyntaxhighlight>
 
Or the equivalent ''for'' syntax, with the additional keyword ''yield'', map is called instead of foreach
<langsyntaxhighlight lang=scala>val squares = for (val i <- l) yield i * i</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang=scheme>(define (square n) (* n n))
(define x #(1 2 3 4 5))
(map square (vector->list x))</langsyntaxhighlight>
 
A single-line variation
<langsyntaxhighlight lang=scheme>(map (lambda (n) (* n n)) '(1 2 3 4 5))</langsyntaxhighlight>
 
For completeness, the <tt>map</tt> function (which is R5RS standard) can be coded as follows:
<langsyntaxhighlight lang=scheme>(define (map f L)
(if (null? L)
L
(cons (f (car L)) (map f (cdr L)))))</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang=sensetalk>
put each item in [1,2,3,5,9,14,24] squared
 
Line 3,126:
to handle myFunc of num
return 2*num + 1
end myFunc</langsyntaxhighlight>
Output:
<langsyntaxhighlight lang=sensetalk>(1,4,9,25,81,196,576)
(3,5,7,11,19,29,49)</langsyntaxhighlight>
 
=={{header|Sidef}}==
Defining a callback function:
<langsyntaxhighlight lang=ruby>func callback(i) { say i**2 }</langsyntaxhighlight>
 
The function will get called for each element:
<langsyntaxhighlight lang=ruby>[1,2,3,4].each(callback)</langsyntaxhighlight>
 
Same as above, but with the function inlined:
<langsyntaxhighlight lang=ruby>[1,2,3,4].each{|i| say i**2 }</langsyntaxhighlight>
 
For creating a new array, we can use the Array.map method:
<langsyntaxhighlight lang=ruby>[1,2,3,4,5].map{|i| i**2 }</langsyntaxhighlight>
 
=={{header|Simula}}==
<langsyntaxhighlight lang=simula>BEGIN
 
! APPLIES A CALLBACK FUNCTION TO AN ARRAY ;
Line 3,166:
FOR I := 1 STEP 1 UNTIL 5 DO OUTFIX(A(I), 2, 8); OUTIMAGE;
 
END.</langsyntaxhighlight>
{{out}}
<pre>
Line 3,173:
 
=={{header|Slate}}==
<langsyntaxhighlight lang=slate>#( 1 2 3 4 5 ) collect: [| :n | n * n].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang=smalltalk>#( 1 2.0 'three') do: [:each | each displayNl].</langsyntaxhighlight>
You can tell symbols how to react to the <tt>value:</tt> message, and then write &sup2;:
<langsyntaxhighlight lang=smalltalk>#( 1 2.0 'three') do: #displayNl.</langsyntaxhighlight>
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.:
<langsyntaxhighlight lang=smalltalk>#( 1 2 3 4 5 ) collect: [:n | n * n].</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight lang=sparkling>let numbers = { 1, 2, 3, 4 };
foreach(numbers, function(idx, num) {
print(num);
});</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang=sparkling>let dict = { "foo": 42, "bar": 13, "baz": 37 };
let doubled = map(dict, function(key, val) {
return val * 2;
});</langsyntaxhighlight>
 
=={{header|SQL PL}}==
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
<langsyntaxhighlight lang=sql pl>
--#SET TERMINATOR @
 
Line 3,232:
END;
END @
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,245:
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang=Standard ML>
map f l
</syntaxhighlight>
</lang>
i.e.
<langsyntaxhighlight lang=Standard ML>
map (fn x=>x+1) [1,2,3];; (* [2,3,4] *)
</syntaxhighlight>
</lang>
 
=={{header|Stata}}==
There is no 'map' function in Mata, but it's easy to implement. Notice that you can only pass functions that are written in Mata, no builtin ones. For instance, the trigonometric functions (cos, sin) or the exponential are builtin. To pass a builtin function to another function, one needs to write a wrapper in Mata. See also Stata help about '''[https://www.stata.com/help.cgi?m2_pointers pointers]''' and '''[https://www.stata.com/help.cgi?m2_ftof passing functions to functions]'''. There are two versions of the function: one to return a numeric array, another to return a string array.
 
<langsyntaxhighlight lang=stata>function map(f,a) {
nr = rows(a)
nc = cols(a)
Line 3,278:
function square(x) {
return(x*x)
}</langsyntaxhighlight>
 
'''Output'''
Line 3,291:
=={{header|SuperCollider}}==
Actually, there is a builtin <tt>squared</tt> operator:
<langsyntaxhighlight lang=SuperCollider>[1, 2, 3].squared // returns [1, 4, 9]</langsyntaxhighlight>
Anything that is a <tt>Collection</tt> can be used with <tt>collect</tt>:
<langsyntaxhighlight lang=SuperCollider>[1, 2, 3].collect { |x| x * x }</langsyntaxhighlight>
[[List Comprehension#SuperCollider|List comprehension]] combined with a higher-order function can also be used:
<langsyntaxhighlight lang=SuperCollider>var square = { |x| x * x };
var map = { |fn, xs|
all {: fn.value(x), x <- xs };
};
map.value(square, [1, 2, 3]);</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang=swift>func square(n: Int) -> Int {
return n * n
}
Line 3,314:
let squares1b = numbers.map { $0 * $0 } // map method on array with anonymous function and unnamed parameters
 
let isquares1 = numbers.lazy.map(square) // lazy sequence</langsyntaxhighlight>
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang=tailspin>
def numbers: [1,3,7,10];
 
Line 3,332:
[ $numbers... -> $ * $ ] -> !OUT::write
[ $numbers... -> cube ] -> !OUT::write
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
 
If I wanted to call "<tt>myfunc</tt>" on each element of <tt>dat</tt> and <tt>dat</tt> were a list:
<langsyntaxhighlight lang=tcl>foreach var $dat {
myfunc $var
}</langsyntaxhighlight>
This does not retain any of the values returned by <tt>myfunc</tt>.
 
if <tt>dat</tt> were an (associative) array, however:
<langsyntaxhighlight lang=tcl>foreach name [array names dat] {
myfunc $dat($name)
}</langsyntaxhighlight>
 
More functional, with a simple <code>map</code> function:
<langsyntaxhighlight lang=Tcl>proc map {f list} {
set res {}
foreach e $list {lappend res [$f $e]}
Line 3,356:
 
% map square {1 2 3 4 5}
1 4 9 16 25</langsyntaxhighlight>
 
=={{header|TI-89 BASIC}}==
 
<langsyntaxhighlight lang=ti89b>© For no return value
Define foreach(fe_cname,fe_list) = Prgm
Local fe_i
Line 3,376:
 
foreach("callback", {1,2,3,4,5})
Disp map("√", {1,2,3,4,5})</langsyntaxhighlight>
 
{{Out}}
Line 3,390:
JavaScript alike:
 
<langsyntaxhighlight lang=javascript>var a = [1, 2, 3, 4, 5];
a.map(function(v) { return v * v; })
</syntaxhighlight>
</lang>
 
Using short form of lambda notation:
<langsyntaxhighlight lang=javascript>var a = [1, 2, 3, 4, 5];
a.map( :v: v*v );
</syntaxhighlight>
</lang>
 
=={{header|Toka}}==
 
<langsyntaxhighlight lang=toka>( array count function -- )
{
value| array fn |
Line 3,417:
 
( Add 1 to each item in the array )
a 5 [ 1 + ] map-array</langsyntaxhighlight>
 
=={{header|TorqueScript}}==
Line 3,425:
Callbacks:
 
<langsyntaxhighlight lang=TorqueScript>
function map(%array,%arrayCount,%function)
{
Line 3,434:
}
}
</syntaxhighlight>
</lang>
 
Now to set up an array:
 
<langsyntaxhighlight lang=TorqueScript>
$array[0] = "Hello.";
$array[1] = "Hi.";
$array[2] = "How are you?";
</syntaxhighlight>
</lang>
 
Now to call the function correctly:
 
<langsyntaxhighlight lang=TorqueScript>
map("$array",3,"echo");
</syntaxhighlight>
</lang>
 
Which should result in:
 
<langsyntaxhighlight lang=TorqueScript>
=> Hello.
 
Line 3,458:
 
=> How are you?
</syntaxhighlight>
</lang>
 
=={{header|TXR}}==
Line 3,464:
Print 1 through 10 out of a vector, using <code>prinl</code> the callback, right from the system shell command prompt:
 
<langsyntaxhighlight lang=bash>$ txr -e '[mapdo prinl #(1 2 3 4 5 6 7 8 9 10)]'
1
2
Line 3,474:
8
9
10</langsyntaxhighlight>
 
<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:
Push 10000+((Pop()*-(Pop()/2))/10000)
If a@ Then Push -Pop() ' Result is directly transferred
Return ' through the stack</langsyntaxhighlight>
{{out}}
<pre>SQRT(1) = 1.0000
Line 3,561:
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
<langsyntaxhighlight lang=bash>map() {
map_command=$1
shift
Line 3,567:
}
list=1:2:3
(IFS=:; map echo $list)</langsyntaxhighlight>
 
{{works with|ksh93}}
{{works with|pdksh}}
{{works with|zsh}}
<langsyntaxhighlight lang=bash>map() {
typeset command=$1
shift
Line 3,578:
}
set -A ary 1 2 3
map print "${ary[@]}"</langsyntaxhighlight>
 
{{works with|zsh}}
<langsyntaxhighlight lang=bash>map(){for i ($*[2,-1]) $1 $i}
a=(1 2 3)
map print $a</langsyntaxhighlight>
 
=={{header|Ursala}}==
The * is a built-in map operator.
This example shows a map of the successor function over a list of natural numbers.
<langsyntaxhighlight lang=Ursala>#import nat
 
#cast %nL
 
demo = successor* <325,32,67,1,3,7,315></langsyntaxhighlight>
{{Out}}
<pre>
Line 3,600:
=={{header|V}}==
apply squaring (dup *) to each member of collection
<langsyntaxhighlight lang=v>[1 2 3 4] [dup *] map</langsyntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang=vb>
<lang vb>
Option Explicit
 
Line 3,624:
Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)
End If
End Function</langsyntaxhighlight>
{{out}}
<pre>0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55</pre>
Line 3,633:
 
=====Implementation=====
<syntaxhighlight lang=vb>
<lang vb>
class callback
dim sRule
Line 3,650:
end function
end class
</syntaxhighlight>
</lang>
 
=====Invocation=====
<syntaxhighlight lang=vb>
<lang vb>
dim a1
dim cb
Line 3,667:
cb.applyto a1
wscript.echo join( a1, ", " )
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,680:
The result of evaluating the string will be the new value.
The list/dictionary is modified in place.
<langsyntaxhighlight lang=vim>echo map([10, 20, 30], 'v:val * v:val')
echo map([10, 20, 30], '"Element " . v:key . " = " . v:val')
echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:val)')
echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:key)')</langsyntaxhighlight>
 
{{Out}}
Line 3,702:
and System.Linq.Enumerable.ToArray(Of TSource)(IEnumerable(Of TSource)) eagerly converts the enumerable to an array.
 
<langsyntaxhighlight lang=vbnet>Module Program
Function OneMoreThan(i As Integer) As Integer
Return i + 1
Line 3,726:
Array.ForEach(resultArr, AddressOf Console.WriteLine)
End Sub
End Module</langsyntaxhighlight>
 
{{out}}
Line 3,736:
=={{header|Vorpal}}==
Given and array, A, and a function, F, mapping F over the elements of A is simple:
<syntaxhighlight lang =vorpal>A.map(F)</langsyntaxhighlight>
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.
<langsyntaxhighlight lang=vorpal>A.map(F, x, y)</langsyntaxhighlight>
 
=={{header|Wart}}==
<langsyntaxhighlight lang=wart>map prn '(1 2 3 4 5)</langsyntaxhighlight>
 
{{Out}}
Line 3,752:
 
=={{header|WDTE}}==
<langsyntaxhighlight lang=WDTE>let a => import 'arrays';
let s => import 'stream';
 
Line 3,760:
-> s.map (* 2)
-> s.collect
;</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang=ecmascript>var arr = [1, 2, 3, 4, 5]
arr = arr.map { |x| x * 2 }.toList
arr = arr.map(Fn.new { |x| x / 2 }).toList
arr.each { |x| System.print(x) }</langsyntaxhighlight>
 
{{out}}
Line 3,780:
 
=={{header|XBS}}==
<langsyntaxhighlight lang=xbs>func map(arr:array,callback:function){
set newArr:array = [];
foreach(k,v as arr){
Line 3,794:
log(arr.join(", "));
log(result.join(", "));</langsyntaxhighlight>
{{out}}
<pre>
Line 3,802:
 
=={{header|Yabasic}}==
<langsyntaxhighlight lang=Yabasic>sub map(f$, t())
local i
 
Line 3,832:
print t(i), "\t";
next i
print</langsyntaxhighlight>
 
=={{header|Yacas}}==
<langsyntaxhighlight lang=Yacas>Sin /@ {1, 2, 3, 4}
 
MapSingle(Sin, {1,2,3,4})
 
MapSingle({{x}, x^2}, {1,2,3,4})
</syntaxhighlight>
</lang>
 
=={{header|Z80 Assembly}}==
<langsyntaxhighlight lang=z80>Array:
byte &01,&02,&03,&04,&05
Array_End:
Line 3,856:
inc (hl)
inc hl ;next entry in array
djnz bar</langsyntaxhighlight>
 
{{out}}
Line 3,865:
 
=={{header|Zig}}==
<langsyntaxhighlight lang=zig>pub fn main() !void {
var array = [_]i32{1, 2, 3};
apply(@TypeOf(array[0]), array[0..], func);
Line 3,879:
const std = @import("std");
std.debug.print("{d}\n", .{a-1});
}</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang=zkl>L(1,2,3,4,5).apply('+(5))</langsyntaxhighlight>
{{Out}}
<pre>
Line 3,889:
 
=={{header|zonnon}}==
<langsyntaxhighlight lang=zonnon>
module Main;
type
Line 3,929:
Write(Map(x,Power))
end Main.
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,936:
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang=zxbasic>10 LET a$="x+x"
20 LET b$="x*x"
30 LET c$="x+x^2"
Line 3,946:
190 STOP
200 DATA 2,5,6,10,100
</syntaxhighlight>
</lang>
 
{{omit from|gnuplot}}
10,327

edits