Apply a callback to an array: Difference between revisions

m (syntax highlighting fixup automation)
(27 intermediate revisions by 19 users not shown)
Line 1:
{{task|Basic language learning}}
[[Category:Iteration]]
{{task|Basic language learning}}
 
;Task:
Line 8:
=={{header|11l}}==
{{trans|Kotlin}}
<syntaxhighlight lang="11l">V array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
V arrsq = array.map(i -> i * i)
print(arrsq)</syntaxhighlight>
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.
<syntaxhighlight lang="6502asm">define SRC_LO $00
define SRC_HI $01
 
Line 87:
{{trans|11l}}
The following assumes all code/data is stored/executed in RAM and is therefore mutable.
<syntaxhighlight lang="68000devpac">LEA MyArray,A0
MOVE.W #(MyArray_End-MyArray)-1,D7 ;Len(MyArray)-1
MOVEQ #0,D0 ;sanitize D0-D2 to ensure nothing from any previous work will affect our math.
Line 109:
=={{header|8th}}==
The builtin word "a:map" does this:
<syntaxhighlight lang="forth">
[ 1 , 2, 3 ]
' n:sqr
Line 120:
ACL2 does not have first-class functions; this is close, however:
 
<syntaxhighlight lang="lisp">(defun apply-to-each (xs)
(if (endp xs)
nil
Line 131:
 
=={{header|ActionScript}}==
<syntaxhighlight lang="actionscript">package
{
public class ArrayCallback
Line 153:
=={{header|Ada}}==
{{works with|GNAT|GPL 2005}}
<syntaxhighlight lang="ada">with Ada.Text_Io;
with Ada.Integer_text_IO;
Line 192:
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">void
map(list l, void (*fp)(object))
{
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}}
<syntaxhighlight lang="algol68"> PROC call back proc = (INT location, INT value)VOID:
(
printf(($"array["g"] = "gl$, location, value))
Line 244:
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
procedure printSquare ( integer value x ) ; writeon( i_w := 1, s_w := 0, " ", x * x );
% applys f to each element of a from lb to ub (inclusive) %
Line 260:
By default functions in APL work on arrays as it is an array oriented language. Some examples:
 
<syntaxhighlight lang=APL"apl"> - 1 2 3
¯1 ¯2 ¯3
2 * 1 2 3 4
Line 273:
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">on callback for arg
-- Returns a string like "arc has 3 letters"
arg & " has " & (count arg) & " letters"
Line 290:
For a more general implementation of '''map(function, list)''', '''foldl(function, startValue, list)''', and '''filter(predicate, list)''', we could write:
 
<syntaxhighlight lang="applescript">on run
set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Line 372:
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">arr: [1 2 3 4 5]
 
print map arr => [2*&]</syntaxhighlight>
Line 381:
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang=AutoHotkey"autohotkey">map("callback", "3,4,5")
 
callback(array){
Line 393:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">$ awk 'func psqr(x){print x,x*x}BEGIN{split("1 2 3 4 5",a);for(i in a)psqr(a[i])}'
4 16
5 25
Line 404:
Let us define a squaring operator:
 
<syntaxhighlight lang="babel">sq { dup * } <</syntaxhighlight>
 
Now, we apply the sq operator over a list and display the result using the lsnum utility:
 
<syntaxhighlight lang="babel">( 0 1 1 2 3 5 8 13 21 34 ) { sq ! } over ! lsnum !</syntaxhighlight>
 
{{Out}}
Line 415:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> DIM a(4)
a() = 1, 2, 3, 4, 5
PROCmap(a(), FNsqrt())
Line 440:
2.23606798
</pre>
 
=={{header|Binary Lambda Calculus}}==
In the lambda calculus, we can map over a list as in https://github.com/tromp/AIT/blob/master/lists/map.lam, which gives the following BLC program to negate every bit of input:
<pre>010001101000000101100000000001011000000101111111010110010111111101111110111010</pre>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">Square ← ט
 
array ← 2‿3‿5‿7‿11‿13
 
Square¨ array</syntaxhighlight>
The use of the ¨ modifier is the general approach, but actually not necessary with arithmetic functions.
{{out}}
<pre>⟨ 4 9 25 49 121 169 ⟩</pre>
 
=={{header|Bracmat}}==
<syntaxhighlight lang="bracmat">( ( callbackFunction1
= location value
. !arg:(?location,?value)
Line 483 ⟶ 497:
=={{header|Brat}}==
 
<syntaxhighlight lang="brat">#Print out each element in array
[:a :b :c :d :e].each { element |
p element
Line 490 ⟶ 504:
Alternatively:
 
<syntaxhighlight lang="brat">[:a :b :c :d :e].each ->p</syntaxhighlight>
 
=={{header|C}}==
 
'''callback.h'''
<syntaxhighlight lang="c">#ifndef CALLBACK_H
#define CALLBACK_H
 
Line 513 ⟶ 527:
 
'''callback.c'''
<syntaxhighlight lang="c">#include <stdio.h>
#include "callback.h"
 
Line 553 ⟶ 567:
This version uses the C# 3 lambda notation.
 
<syntaxhighlight lang="csharp">int[] intArray = { 1, 2, 3, 4, 5 };
// Simplest method: LINQ, functional
int[] squares1 = intArray.Select(x => x * x).ToArray();
Line 568 ⟶ 582:
 
{{works with|Visual C sharp|Visual C#|2005}}
<syntaxhighlight lang="csharp">using System;
 
static class Program
Line 607 ⟶ 621:
{{works with|g++|4.1.1}}
===C-Style Array===
<syntaxhighlight lang="cpp">#include <iostream> //cout for printing
#include <algorithm> //for_each defined here
 
Line 626 ⟶ 640:
===std::vector===
{{libheader|STL}}
<syntaxhighlight lang="cpp">#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
#include <vector> // stl vector class
Line 650 ⟶ 664:
 
More tricky with binary function
<syntaxhighlight lang="cpp">#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
#include <vector> // stl vector class
Line 677 ⟶ 691:
===Boost.Lambda===
{{libheader|Boost}}
<syntaxhighlight lang="cpp">using namespace std;
using namespace boost::lambda;
vector<int> ary(10);
Line 685 ⟶ 699:
 
===C++11===
<syntaxhighlight lang="cpp">#include <vector>
#include <iostream>
#include <algorithm>
Line 705 ⟶ 719:
Define a function and an initial (unboxed) array.
 
<syntaxhighlight lang="clean">square x = x * x
 
values :: {#Int}
Line 712 ⟶ 726:
One can easily define a map for arrays, which is overloaded and works for all kinds of arrays (lazy, strict, unboxed).
 
<syntaxhighlight lang="clean">mapArray f array = {f x \\ x <-: array}</syntaxhighlight>
 
Apply the function to the initial array (using a comprehension) and print result.
 
<syntaxhighlight lang="clean">Start :: {#Int}
Start = mapArray square values</syntaxhighlight>
 
=={{header|Clio}}==
'''Math operations'''
<syntaxhighlight lang="clio">[1 2 3 4] * 2 + 1 -> print</syntaxhighlight>
'''Quick functions'''
<syntaxhighlight lang="text">[1 2 3 4] -> * n: n * 2 + 1 -> print</syntaxhighlight>
'''Anonymous function'''
<syntaxhighlight lang="clio">[1 2 3 4]
-> * fn n:
n * 2 + 1
-> print</syntaxhighlight>
'''Named function'''
<syntaxhighlight lang="clio">fn double-plus-one n:
n * 2 + 1
 
Line 737 ⟶ 751:
=={{header|Clojure}}==
 
<syntaxhighlight lang="lisp">;; apply a named function, inc
(map inc [1 2 3 4])</syntaxhighlight>
 
<syntaxhighlight lang="lisp">;; apply a function
(map (fn [x] (* x x)) [1 2 3 4])</syntaxhighlight>
 
<syntaxhighlight lang="lisp">;; shortcut syntax for a function
(map #(* % %) [1 2 3 4])</syntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% This procedure will call a given procedure with each element
% of the given array. Thanks to CLU's type parameterization,
% it will work for any type of element.
Line 797 ⟶ 811:
 
=={{header|COBOL}}==
{{Works with|COBOL 2002}}
 
Basic implementation of a map function:
<syntaxhighlight lang=cobol"cobolfree"> IDENTIFICATION>>SOURCE FORMAT IS DIVISION.FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. Map.
PROGRAM-ID. map.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Table-Size CONSTANT 30.
 
LOCAL-STORAGE SECTION.
01 I USAGE UNSIGNED-INT.
 
LINKAGE SECTION.
01 Table-Param.
03 Table-Values USAGE COMP-2 OCCURS Table-Size TIMES.
 
DATA DIVISION.
01 Func-Id PIC X(30).
LOCAL-STORAGE SECTION.
01 i USAGE IS INDEX.
01 table-size CONSTANT AS 30.
LINKAGE SECTION.
01 table-param.
03 table-values USAGE IS FLOAT-LONG, OCCURS table-size TIMES.
01 func-ptr USAGE IS PROGRAM-POINTER.
 
PROCEDURE DIVISION USING BY REFERENCE table-param, BY VALUE func-ptr.
PROCEDURE DIVISION USING Table-Param Func-Id.
PERFORM VARYING Ii FROM 1 BY 1 UNTIL Table-Sizei IS <GREATER ITHAN table-size
CALL Funcfunc-Idptr USING BY REFERENCE Tabletable-Values values(Ii)
END-PERFORM
GOBACK.
 
END PROGRAM map.</syntaxhighlight>
GOBACK
.</syntaxhighlight>
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript">
map = (arr, f) -> (f(e) for e in arr)
arr = [1, 2, 3, 4, 5]
Line 835 ⟶ 846:
Imperative: print 1, 2, 3, 4 and 5:
 
<syntaxhighlight lang="lisp">(map nil #'print #(1 2 3 4 5))</syntaxhighlight>
 
Functional: collect squares into new vector that is returned:
 
<syntaxhighlight lang="lisp">(defun square (x) (* x x))
(map 'vector #'square #(1 2 3 4 5))</syntaxhighlight>
 
Destructive, like the Javascript example; add 1 to every slot of vector *a*:
 
<syntaxhighlight lang="lisp">(defvar *a* (vector 1 2 3))
(map-into *a* #'1+ *a*)</syntaxhighlight>
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<syntaxhighlight lang="oberon2">
MODULE Callback;
IMPORT StdLog;
Line 933 ⟶ 944:
=={{header|Crystal}}==
Calling with a block
<syntaxhighlight lang="ruby">values = [1, 2, 3]
 
new_values = values.map do |number|
Line 942 ⟶ 953:
 
Calling with a function/method
<syntaxhighlight lang="ruby">values = [1, 2, 3]
 
def double(number)
Line 956 ⟶ 967:
 
=={{header|D}}==
<syntaxhighlight lang="d">import std.stdio, std.algorithm;
 
void main() {
Line 967 ⟶ 978:
 
=={{header|Delphi}}==
<syntaxhighlight lang=Delphi"delphi">
// Declare the callback function
procedure callback(const AInt:Integer);
Line 989 ⟶ 1,000:
=={{header|Dyalect}}==
 
<syntaxhighlight lang=Dyalect"dyalect">func Array.Select(pred) {
let ys = []
for x in this when pred(x) {
Line 1,004 ⟶ 1,015:
=={{header|Déjà Vu}}==
There is a <code>map</code> builtin that does just this.
<syntaxhighlight lang="dejavu">!. map @++ [ 1 4 8 ]
 
#implemented roughly like this:
Line 1,017 ⟶ 1,028:
=={{header|E}}==
 
<syntaxhighlight lang="e">def array := [1,2,3,4,5]
def square(value) {
return value * value
Line 1,024 ⟶ 1,035:
Example of builtin iteration:
 
<syntaxhighlight lang="e">def callback(index, value) {
println(`Item $index is $value.`)
}
Line 1,033 ⟶ 1,044:
returning a plain list (which is usually an array in implementation).
 
<syntaxhighlight lang="e">def map(func, collection) {
def output := [].diverge()
for item in collection {
Line 1,043 ⟶ 1,054:
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
(vector-map sqrt #(0 4 16 49))
→ #( 0 2 4 7)
Line 1,059 ⟶ 1,070:
=={{header|Efene}}==
 
<syntaxhighlight lang="efene">square = fn (N) {
N * N
}
Line 1,094 ⟶ 1,105:
 
=={{header|EGL}}==
<syntaxhighlight lang=EGL"egl">delegate callback( i int ) returns( int ) end
 
program ApplyCallbackToArray
Line 1,116 ⟶ 1,127:
 
=={{header|Elena}}==
ELENA 56.0x :
<syntaxhighlight lang="elena">import system'routines;
 
PrintSecondPower(n){ console.writeLine(n * n) }
Line 1,123 ⟶ 1,134:
public program()
{
new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.forEach:(PrintSecondPower)
}</syntaxhighlight>
 
=={{header|Elixir}}==
<syntaxhighlight lang=Elixir"elixir">
Enum.map([1, 2, 3], fn(n) -> n * 2 end)
Enum.map [1, 2, 3], &(&1 * 2)
Line 1,140 ⟶ 1,151:
A list would be more commonly used in Erlang rather than an array.
 
<syntaxhighlight lang=Erlang"erlang">
1> L = [1,2,3].
[1,2,3]
Line 1,147 ⟶ 1,158:
You can use lists:foreach/2 if you just want to apply the callback to each element of the list.
 
<syntaxhighlight lang="text">
2> lists:foreach(fun(X) -> io:format("~w ",[X]) end, L).
1 2 3 ok
Line 1,154 ⟶ 1,165:
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"erlang">
3> lists:map(fun(X) -> X + 1 end, L).
[2,3,4]
Line 1,161 ⟶ 1,172:
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"erlang">
4> lists:foldl(fun(X, Sum) -> X + Sum end, 0, L).
6
Line 1,167 ⟶ 1,178:
 
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM CALLBACK
 
Line 1,200 ⟶ 1,211:
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">function apply_to_all(sequence s, integer f)
-- apply a function to all elements of a sequence
sequence result
Line 1,223 ⟶ 1,234:
=={{header|F_Sharp|F#}}==
Apply a named function to each member of the array. The result is a new array of the same size as the input.
<syntaxhighlight lang="fsharp">let evenp x = x % 2 = 0
let result = Array.map evenp [| 1; 2; 3; 4; 5; 6 |]</syntaxhighlight>
The same can be done using anonymous functions, this time squaring the members of the input array.
<syntaxhighlight lang="fsharp">let result = Array.map (fun x -> x * x) [|1; 2; 3; 4; 5|]</syntaxhighlight>
Use ''iter'' if the applied function does not return a value.
<syntaxhighlight lang="fsharp">Array.iter (fun x -> printfn "%d" x) [|1; 2; 3; 4; 5|]</syntaxhighlight>
 
=={{header|Factor}}==
Print each element squared:
<syntaxhighlight lang="factor">{ 1 2 3 4 } [ sq . ] each</syntaxhighlight>
 
Collect return values:
<syntaxhighlight lang="factor">{ 1 2 3 4 } [ sq ] map</syntaxhighlight>
 
=={{header|Fantom}}==
Line 1,241 ⟶ 1,252:
In Fantom, functions can be passed to a collection iterator, such as 'each'. 'map' is used similarly, and the results are collected into a list.
 
<syntaxhighlight lang="fantom">
class Main
{
Line 1,265 ⟶ 1,276:
=={{header|FBSL}}==
'''User-defined mapping function:'''
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
FOREACH DIM e IN MyMap(Add42, {1, 2, 3})
Line 1,287 ⟶ 1,298:
 
'''Standard MAP() function:'''
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
DIM languages[] = {{"English", {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}}, _
Line 1,328 ⟶ 1,339:
----------------------------------------
Press any key to continue...</pre>
 
=={{header|Fe}}==
<syntaxhighlight lang="clojure">
(= map (fn (f lst)
(let res (cons nil nil))
(let tail res)
(while lst
(setcdr tail (cons (f (car lst)) nil))
(= lst (cdr lst))
(= tail (cdr tail)))
(cdr res)))
 
(print (map (fn (x) (* x x)) '(1 2 3 4 5 6 7 8 9 10)))
</syntaxhighlight>
 
=={{header|Forth}}==
Line 1,333 ⟶ 1,358:
This is a word that will call a given function on each cell in an array.
 
<syntaxhighlight lang="forth">: map ( addr n fn -- )
-rot cells bounds do i @ over execute i ! cell +loop ;</syntaxhighlight>
 
{{Out|Example usage}}
<syntaxhighlight lang="forth">create data 1 , 2 , 3 , 4 , 5 ,
data 5 ' 1+ map \ adds one to each element of data</syntaxhighlight>
 
Line 1,344 ⟶ 1,369:
 
{{Works with |Fortran|ISO 95 and later}}
<syntaxhighlight lang="fortran">module arrCallback
contains
elemental function cube( x )
Line 1,354 ⟶ 1,379:
end module arrCallback</syntaxhighlight>
 
<syntaxhighlight lang="fortran">program testAC
use arrCallback
implicit none
Line 1,373 ⟶ 1,398:
 
{{Works with|ANSI FORTRAN| 77 (with MIL-STD-1753 structured DO) and later}}
<syntaxhighlight lang="fortran"> program test
C
C-- Declare array:
Line 1,389 ⟶ 1,414:
 
=={{header|FP}}==
<syntaxhighlight lang="fp">{square * . [id, id]}
& square: <1,2,3,4,5></syntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub PrintEx(n As Integer)
Line 1,430 ⟶ 1,455:
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">
f = {|x| x^2} // Anonymous function to square input
a = [1,2,3,5,7]
Line 1,437 ⟶ 1,462:
 
=={{header|FunL}}==
<syntaxhighlight lang="funl">[1, 2, 3].foreach( println )
 
[1, 2, 3].foreach( a -> println(2a) )</syntaxhighlight>
Line 1,453 ⟶ 1,478:
 
=={{header|Futhark}}==
<syntaxhighlight lang=Futhark"futhark">
map f l
</syntaxhighlight>
e.g.
<syntaxhighlight lang=Futhark"futhark">
map (\x->x+1) [1,2,3] -- [2,3,4]
</syntaxhighlight>
or equivalently
<syntaxhighlight lang=Futhark"futhark">
map (+1) [1,2,3] -- [2,3,4]
</syntaxhighlight>
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
 
include "NSLog.incl"
 
void local fn Callback( n as NSInteger )
NSLog( @"Square root of %ld = %f", n, sqr(n) )
end fn
 
void local fn DoIt
NSUInteger i, count
CFArrayRef array = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10]
 
count = len(array)
for i = 0 to count -1
fn Callback( fn NumberIntegerValue( array[i] ) )
next
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
 
Another option is to enumerate the array.
<syntaxhighlight lang="futurebasic">include "NSLog.incl"
 
void local fn Callback( array as CFArrayRef, obj as CFTypeRef )
long value = intVal(obj)
NSLog( @"Square root of %ld = %f", value, sqr(value) )
end fn
 
void local fn DoIt
CFArrayRef array = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10]
ArrayEnumerateObjects( array, @fn Callback, NULL )
end fn
 
fn DoIt
 
HandleEvents</syntaxhighlight>
 
{{out}}
<pre>
Square root of 1 = 1.000000
Square root of 2 = 1.414214
Square root of 3 = 1.732051
Square root of 4 = 2.000000
Square root of 5 = 2.236068
Square root of 6 = 2.449490
Square root of 7 = 2.645751
Square root of 8 = 2.828427
Square root of 9 = 3.000000
Square root of 10 = 3.162278
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Apply_a_callback_to_an_array}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
 
Most programming languages define a high-order map function. In Fōrmulæ, there is ''arraization'' (by analogy with ''summation''). In the following expression, the "big" curly braces resembles the "big" sigma of a summation:
 
[[File:Fōrmulæ - Apply a callback to an array 01.png]]
 
[[File:Fōrmulæ - Apply a callback to an array 02.png]]
 
The elements of the array are not required to be of the same type:
 
[[File:Fōrmulæ - Apply a callback to an array 03.png]]
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Apply a callback to an array 04.png]]
In '''[https://formulae.org/?example=Apply_a_callback_to_an_array this]''' page you can see the program(s) related to this task and their results.
 
=={{header|GAP}}==
<syntaxhighlight lang="gap">a := [1 .. 4];
b := ShallowCopy(a);
 
Line 1,501 ⟶ 1,593:
 
Perhaps in contrast to Ruby, it is idiomatic in Go to use the for statement:
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 1,512 ⟶ 1,604:
 
Alternatively though, an array-like type can be defined and callback-style methods can be defined on it to apply a function to the elements.
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 1,556 ⟶ 1,648:
 
Print each value in a list
<syntaxhighlight lang="groovy">[1,2,3,4].each { println it }</syntaxhighlight>
 
Create a new list containing the squares of another list
<syntaxhighlight lang="groovy">[1,2,3,4].collect { it * it }</syntaxhighlight>
 
=={{header|Haskell}}==
Line 1,565 ⟶ 1,657:
===List===
{{works with|GHC}}
<syntaxhighlight lang="haskell">let square x = x*x
let values = [1..10]
map square values</syntaxhighlight>
 
Using list comprehension to generate a list of the squared values
<syntaxhighlight lang="haskell">[square x | x <- values]</syntaxhighlight>
 
More directly
<syntaxhighlight lang="haskell">[1 .. 10] >>= pure . (^ 2)</syntaxhighlight>
 
Or with one less layer of monadic wrapping
<syntaxhighlight lang="haskell">(^ 2) <$> [1..10]</syntaxhighlight>
 
Using function composition to create a function that will print the squares of a list
<syntaxhighlight lang="haskell">let printSquares = mapM_ (print.square)
printSquares values</syntaxhighlight>
 
===Array===
{{works with|GHC|7.10.3}}
<syntaxhighlight lang="haskell">import Data.Array (Array, listArray)
 
square :: Int -> Int
Line 1,596 ⟶ 1,688:
{{Out}}
<pre>array (1,10) [(1,1),(2,4),(3,9),(4,16),(5,25),(6,36),(7,49),(8,64),(9,81),(10,100)]</pre>
 
=={{header|Guish}}==
{{works with|guish|2.5.1}}
<syntaxhighlight lang="guish">
# applies add2 (adds 2) to each element
add2 = {
return add(@1, 2)
}
l = {1, 2, 3, 4, 5, 6, 7}
puts each(add2, flat(@l))
</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang="icon">procedure main()
local lst
lst := [10, 20, 30, 40]
Line 1,612 ⟶ 1,715:
Hard to come up with an example that isn't completely contrived. IDL doesn't really distinguish between a scalar and an array; thus
 
<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
 
=={{header|Insitux}}==
 
<syntaxhighlight lang="insitux">; apply a named function
(map inc [1 2 3 4])</syntaxhighlight>
 
<syntaxhighlight lang="insitux">; apply a parameterised closure
(map (fn x (+ x 1)) [1 2 3 4])</syntaxhighlight>
 
<syntaxhighlight lang="insitux">; apply a non-parameterised closure
(map #(+ % 1) [1 2 3 4])</syntaxhighlight>
 
<syntaxhighlight lang="insitux">; apply an explicit partial closure
(map @(+ 1) [1 2 3 4])</syntaxhighlight>
 
<syntaxhighlight lang="insitux">; apply an implicit partial closure
(map (+ 1) [1 2 3 4])</syntaxhighlight>
 
=={{header|Io}}==
<syntaxhighlight lang="io">list(1,2,3,4,5) map(squared)</syntaxhighlight>
 
=={{header|J}}==
 
'''Solution''':
<syntaxhighlight lang="j"> "_1</syntaxhighlight>
 
'''Example''':
<syntaxhighlight lang="j"> callback =: *:
array =: 1 2 3 4 5
Line 1,632 ⟶ 1,752:
 
But note that this is a trivial example since <code>*: 1 2 3 4 5</code> would get the same result. Then again, this is something of a trivial exercise in J since all of J is designed around the idea of applying functions usefully to arrays.
 
=={{header|Jakt}}==
<syntaxhighlight lang="jakt">
fn map<T, U>(anon array: [T], function: fn(anon x: T) -> U) throws -> [U] {
mut result: [U] = []
result.ensure_capacity(array.size())
for item in array {
result.push(value: function(item))
}
return result
}
 
fn main() {
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let array_squared = map(array, function: fn(anon n: i64) => n * n)
println("{}", array_squared)
}
</syntaxhighlight>
 
{{out}}
<pre>
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
</pre>
 
=={{header|Java}}==
Line 1,639 ⟶ 1,782:
while the <code>IntToInt</code> is used to replace the array values.
 
<syntaxhighlight lang="java">public class ArrayCallback7 {
 
interface IntConsumer {
Line 1,688 ⟶ 1,831:
{{works with|Java|8}}
 
<syntaxhighlight lang="java">import java.util.Arrays;
 
public class ArrayCallback {
Line 1,709 ⟶ 1,852:
 
===ES3===
<syntaxhighlight lang="javascript">function map(a, func) {
var ret = [];
for (var i = 0; i < a.length; i++) {
Line 1,720 ⟶ 1,863:
 
===ES5===
<syntaxhighlight lang="javascript">[1, 2, 3, 4, 5].map(function(v) { return v * v; });</syntaxhighlight>
 
===ES6===
<syntaxhighlight lang="javascript">[1, 2, 3, 4, 5].map(v => v * v);</syntaxhighlight>
 
The result is always:
Line 1,730 ⟶ 1,873:
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">[1 2 3 4 5] [dup *] map.</syntaxhighlight>
 
=={{header|jq}}==
<syntaxhighlight lang="jq"># Illustration of map/1 using the builtin filter: exp
map(exp) # exponentiate each item in the input list
 
Line 1,748 ⟶ 1,891:
[.[] + 1 ] # add 1 to each element of the input array
</syntaxhighlight>Here is a transcript illustrating how the last of these jq expressions can be evaluated:
<syntaxhighlight lang="jq">$ jq -c ' [.[] + 1 ]'
[0, 1 , 10]
[1,2,11]</syntaxhighlight>
 
=={{header|Jsish}}==
<syntaxhighlight lang="javascript">/* Apply callback, in Jsish using array.map() */
;[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; });
 
Line 1,768 ⟶ 1,911:
=={{header|Julia}}==
{{works with|Julia|0.6}}
<syntaxhighlight lang="julia">numbers = [1, 3, 5, 7]
 
@show [n ^ 2 for n in numbers] # list comprehension
Line 1,778 ⟶ 1,921:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">fun main(args: Array<String>) {
val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // build
val function = { i: Int -> i * i } // function to apply
Line 1,788 ⟶ 1,931:
 
=={{header|Klingphix}}==
<syntaxhighlight lang=Klingphix"klingphix">include ..\Utilitys.tlhy
 
( 1 2 3 4 ) [dup *] map
Line 1,799 ⟶ 1,942:
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang=Scheme"scheme">
{A.map {lambda {:x} {* :x :x}} {A.new 1 2 3 4 5 6 7 8 9 10}}
-> [1,4,9,16,25,36,49,64,81,100]
</syntaxhighlight>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
&arr = fn.arrayGenerateFrom(fn.inc, 10)
fn.println(&arr)
fn.arrayMap(&arr, fn.combC(fn.pow, 2))
fn.println(&arr)
</syntaxhighlight>
{{out}}
<pre>
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
</pre>
 
=={{header|Lang5}}==
<syntaxhighlight lang="lang5">: square(*) dup * ;
[1 2 3 4 5] square . "\n" .
[1 2 3 4 5] 'square apply . "\n" .</syntaxhighlight>
 
=={{header|langur}}==
<syntaxhighlight lang="langur">writeln map ffn{^2}, 1..10</syntaxhighlight>
 
{{out}}
Line 1,816 ⟶ 1,972:
 
=={{header|Lasso}}==
<syntaxhighlight lang=Lasso"lasso">define cube(n::integer) => #n*#n*#n
 
local(
Line 1,831 ⟶ 1,987:
 
=={{header|Lisaac}}==
<syntaxhighlight lang=Lisaac"lisaac">+ a : ARRAY(INTEGER);
+ b : {INTEGER;};
 
Line 1,847 ⟶ 2,003:
 
=={{header|Logo}}==
<syntaxhighlight lang="logo">to square :x
output :x * :x
end
Line 1,857 ⟶ 2,013:
 
Say we have an array:
<syntaxhighlight lang="lua">myArray = {1, 2, 3, 4, 5}</syntaxhighlight>
A map function for this would be
<syntaxhighlight lang="lua">map = function(f, data)
local result = {}
for k,v in ipairs(data) do
Line 1,867 ⟶ 2,023:
end</syntaxhighlight>
Together with our array and a square function this yields:
<syntaxhighlight lang="lua">myFunc = function(x) return x*x end
 
print(unpack( map(myFunc, myArray) ))
Line 1,876 ⟶ 2,032:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
a=(1,2,3,4,5)
b=lambda->{
Line 1,907 ⟶ 2,063:
 
=={{header|M4}}==
<syntaxhighlight lang=M4"m4">define(`foreach', `pushdef(`$1')_foreach($@)popdef(`$1')')dnl
define(`_arg1', `$1')dnl
define(`_foreach', `ifelse(`$2', `()', `',
Line 1,925 ⟶ 2,081:
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.
<syntaxhighlight lang=Maple"maple">
> map( sqrt, [ 1.1, 3.2, 5.7 ] );
[1.048808848, 1.788854382, 2.387467277]
Line 1,939 ⟶ 2,095:
</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.
<syntaxhighlight lang=Maple"maple">
> a := Array( [ 1.1, 3.2, 5.7 ] );
a := [1.1, 3.2, 5.7]
Line 1,956 ⟶ 2,112:
</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.
<syntaxhighlight lang=Maple"maple">
> map[inplace]( sqrt, a );
[1.048808848, 1.788854382, 2.387467277]
Line 1,966 ⟶ 2,122:
 
It is also possible to pass additional arguments to the mapped procedure.
<syntaxhighlight lang=Maple"maple">
> map( `+`, [ 1, 2, 3 ], 3 );
[4, 5, 6]
</syntaxhighlight>
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"maple">
> map2( `-`, 5, [ 1, 2, 3 ] );
[4, 3, 2]
Line 1,980 ⟶ 2,136:
 
=={{header|Mathematica}}//{{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">(#*#)& /@ {1, 2, 3, 4}
Map[Function[#*#], {1, 2, 3, 4}]
Map[((#*#)&,{1,2,3,4}]
Line 1,989 ⟶ 2,145:
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.
<syntaxhighlight lang=MATLAB"matlab">>> array = [1 2 3 4 5]
 
array =
Line 2,026 ⟶ 2,182:
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">/* for lists or sets */
 
map(sin, [1, 2, 3, 4]);
Line 2,037 ⟶ 2,193:
=={{header|min}}==
{{works with|min|0.19.3}}
<syntaxhighlight lang="min">(1 2 3 4 5) (sqrt puts) foreach ; print each square root
(1 2 3 4 5) 'sqrt map ; collect return values</syntaxhighlight>
 
=={{header|Modula-3}}==
<syntaxhighlight lang="modula3">MODULE Callback EXPORTS Main;
 
IMPORT IO, Fmt;
Line 2,069 ⟶ 2,225:
 
=={{header|Nanoquery}}==
<syntaxhighlight lang=Nanoquery"nanoquery">// create a list of numbers 1-10
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Line 2,088 ⟶ 2,244:
=={{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).
<syntaxhighlight lang=Nemerle"nemerle">def seg = array[1, 2, 3, 5, 8, 13];
def squares = seq.Map(x => x*x);</syntaxhighlight>
 
=={{header|NetLogo}}==
<syntaxhighlight lang=NetLogo"netlogo">
;; NetLogo “anonymous procedures”
;; stored in a variable, just to show it can be done.
Line 2,101 ⟶ 2,257:
=={{header|NewLISP}}==
 
<syntaxhighlight lang=NewLISP"newlisp">> (map (fn (x) (* x x)) '(1 2 3 4))
(1 4 9 16)
</syntaxhighlight>
 
=={{header|NGS}}==
<syntaxhighlight lang=NGS"ngs">{
[1, 2, 3, 4, 5].map(F(x) x*x)
}</syntaxhighlight>
Line 2,112 ⟶ 2,268:
=={{header|Nial}}==
 
<syntaxhighlight lang="nial">each (* [first, first] ) 1 2 3 4
=1 4 9 16</syntaxhighlight>
 
=={{header|Nim}}==
 
<syntaxhighlight lang="nim">var arr = @[1,2,3,4]
from std/sequtils import apply
arr.apply proc(some: var int) = echo(some, " squared = ", some*some)</syntaxhighlight>
let arr = @[1,2,3,4]
arr.apply proc(some: int) = echo(some, " squared = ", some*some)</syntaxhighlight>
 
{{Out}}
Line 2,125 ⟶ 2,283:
3 squared = 9
4 squared = 16
 
=={{header|Nutt}}==
<syntaxhighlight lang="Nutt">
module main
imports native.io.output.say
 
operator |> (arr:Array,f:Procedure):Array==>{f(x) of x |-> arr}
 
say({0,1,2,3,4,5}|>a==>a+2)//|{2,3,4,5,6,7}
 
end
</syntaxhighlight>
 
 
=={{header|Oberon-2}}==
{{Works with|oo2x}}
<syntaxhighlight lang="oberon2">
MODULE ApplyCallBack;
IMPORT
Line 2,226 ⟶ 2,397:
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">
use Structure;
 
Line 2,253 ⟶ 2,424:
This function is part of the standard library:
 
<syntaxhighlight lang="ocaml">Array.map</syntaxhighlight>
 
Usage example:
<syntaxhighlight lang="ocaml">let square x = x * x;;
let values = Array.init 10 ((+) 1);;
Array.map square values;;</syntaxhighlight>
 
Or with lists (which are more typical in OCaml):
<syntaxhighlight lang="ocaml">let values = [1;2;3;4;5;6;7;8;9;10];;
List.map square values;;</syntaxhighlight>
 
Use <tt>iter</tt> if the applied function does not return a value.
 
<syntaxhighlight lang="ocaml">Array.iter (fun x -> Printf.printf "%d" x) [|1; 2; 3; 4; 5|];;</syntaxhighlight>
<syntaxhighlight lang="ocaml">List.iter (fun x -> Printf.printf "%d" x) [1; 2; 3; 4; 5];;</syntaxhighlight>
 
with partial application we can also write:
 
<syntaxhighlight lang="ocaml">Array.iter (Printf.printf "%d") [|1; 2; 3; 4; 5|];;</syntaxhighlight>
<syntaxhighlight lang="ocaml">List.iter (Printf.printf "%d") [1; 2; 3; 4; 5];;</syntaxhighlight>
 
=={{header|Octave}}==
Line 2,278 ⟶ 2,449:
Almost all the built-in can operate on each element of a vector or matrix; e.g. sin([pi/2, pi, 2*pi]) computes the function sin on pi/2, pi and 2*pi (returning a vector). If a function does not accept vectors/matrices as arguments, the <tt>arrayfun</tt> can be used.
 
<syntaxhighlight lang="octave">function e = f(x, y)
e = x^2 + exp(-1/(y+1));
endfunction
Line 2,287 ⟶ 2,458:
 
(The function <tt>f</tt> can be rewritten so that it can accept vectors as argument simply changing operators to their dot ''relatives'': <code>e = x.^2 + exp(-1 ./ (y.+1))</code>)
 
=={{header|Odin}}==
 
<syntaxhighlight lang="odin">package main
 
import "core:slice"
import "core:fmt"
 
squared :: proc(x: int) -> int {
return x * x
}
 
main :: proc() {
arr := []int{1, 2, 3, 4, 5}
res := slice.mapper(arr, squared)
 
fmt.println(res) // prints: [1, 4, 9, 16, 25]
}</syntaxhighlight>
 
=={{header|Oforth}}==
apply allows to perform a function on all elements of a list :
<syntaxhighlight lang=Oforth"oforth">0 #+ [ 1, 2, 3, 4, 5 ] apply</syntaxhighlight>
 
map regroups all results into a new list :
<syntaxhighlight lang=Oforth"oforth">#sq [ 1, 2, 3, 4, 5 ] map</syntaxhighlight>
 
=={{header|Ol}}==
Apply custom callback (lambda) to every element of list.
<syntaxhighlight lang="scheme">
(for-each
(lambda (element)
Line 2,307 ⟶ 2,496:
=={{header|ooRexx}}==
ooRexx doesn't directly support callbacks on array items, but this is pretty easy to implement using Routine objects.
<syntaxhighlight lang=ooRexx"oorexx">start = .array~of("Rick", "Mike", "David", "Mark")
new = map(start, .routines~reversit)
call map new, .routines~sayit
Line 2,339 ⟶ 2,528:
=={{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>.
<syntaxhighlight lang="c">#include <order/interpreter.h>
 
ORDER_PP( 8tuple_map(8fn(8X, 8times(8X, 8X)), 8tuple(1, 2, 3, 4, 5)) )
Line 2,351 ⟶ 2,540:
 
=={{header|Oz}}==
<syntaxhighlight lang="oz">declare
fun{Square A}
A*A
Line 2,367 ⟶ 2,556:
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.2 and above}}
<syntaxhighlight lang="parigp">callback(n)=n+n;
apply(callback, [1,2,3,4,5])</syntaxhighlight>
 
This should be contrasted with <code>call</code>:
<syntaxhighlight lang="parigp">call(callback, [1,2,3,4,5])</syntaxhighlight>
which is equivalent to <code>callback(1, 2, 3, 4, 5)</code> rather than <code>[callback(1), callback(2), callback(3), callback(4), callback(5)]</code>.
 
Line 2,378 ⟶ 2,567:
 
=={{header|Perl}}==
<syntaxhighlight lang="perl"># create array
my @a = (1, 2, 3, 4, 5);
 
Line 2,411 ⟶ 2,600:
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<syntaxhighlight lang=Phix"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,433 ⟶ 2,622:
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Apply_a_callback_to_an_array
by Galileo, 05/2022 #/
 
Line 2,459 ⟶ 2,648:
 
=={{header|PHP}}==
<syntaxhighlight lang="php">function cube($n)
{
return($n * $n * $n);
Line 2,471 ⟶ 2,660:
Picat doesn't support anonymous (lambda) functions so the function must be defined in the program to be used by - say - map/2.
There are - however - quite a few ways without proper lambdas, using map/2, apply/2, or list comprehensions.
<syntaxhighlight lang=Picat"picat">go =>
L = 1..10,
 
Line 2,499 ⟶ 2,688:
 
Note that fun2/2 is not a function so map/2 or apply/2 cannot be used here.
<syntaxhighlight lang=Picat"picat">go2 =>
L = 1..10,
 
Line 2,513 ⟶ 2,702:
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">: (mapc println (1 2 3 4 5)) # Print numbers
1
2
Line 2,531 ⟶ 2,720:
 
=={{header|Pike}}==
<syntaxhighlight lang="pike">int cube(int n)
{
return n*n*n;
Line 2,541 ⟶ 2,730:
 
=={{header|PL/I}}==
<syntaxhighlight lang=PL"pl/Ii"> declare x(5) initial (1,3,5,7,8);
x = sqrt(x);
x = sin(x);</syntaxhighlight>
Line 2,547 ⟶ 2,736:
=={{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.
<syntaxhighlight 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,626 ⟶ 2,815:
=={{header|Pop11}}==
 
<syntaxhighlight lang="pop11">;;; Define a procedure
define proc(x);
printf(x*x, '%p,');
Line 2,641 ⟶ 2,830:
=={{header|PostScript}}==
The <code>forall</code> operator applies a procedure to each element of an array, a packed array or a string.
<syntaxhighlight lang="postscript">[1 2 3 4 5] { dup mul = } forall</syntaxhighlight>
In this case the respective square numbers for the elements are printed.
 
To create a new array from the results above code can simply be wrapped in <code>[]</code>:
<syntaxhighlight lang="postscript">[ [1 2 3 4 5] { dup mul } forall ]</syntaxhighlight>
 
{{libheader|initlib}}
<syntaxhighlight lang="postscript">
[1 2 3 4 5] {dup *} map
</syntaxhighlight>
Line 2,654 ⟶ 2,843:
=={{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:
<syntaxhighlight lang="powershell">1..5 | ForEach-Object { $_ * $_ }</syntaxhighlight>
To recreate a ''map'' function, found in other languages the same method applies:
<syntaxhighlight lang="powershell">function map ([array] $a, [scriptblock] $s) {
$a | ForEach-Object $s
}
Line 2,663 ⟶ 2,852:
=={{header|Prolog}}==
Prolog doesn't have arrays, but we can do it with lists. This can be done in the console mode.
<syntaxhighlight lang=Prolog"prolog"> ?- assert((fun(X, Y) :- Y is 2 * X)).
true.
 
Line 2,671 ⟶ 2,860:
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">Procedure Cube(Array param.i(1))
Protected n.i
For n = 0 To ArraySize(param())
Line 2,687 ⟶ 2,876:
 
=={{header|Python}}==
<syntaxhighlight lang="python">def square(n):
return n * n
Line 2,706 ⟶ 2,895:
isquares2 = itertools.imap(square, numbers) # iterator, lazy</syntaxhighlight>
To print squares of integers in the range from 0 to 9, type:
<syntaxhighlight lang="python">print " ".join(str(n * n) for n in range(10))</syntaxhighlight>
Or:
<syntaxhighlight lang="python">print " ".join(map(str, map(square, range(10))))</syntaxhighlight>
Result:
<syntaxhighlight lang="python">0 1 4 9 16 25 36 49 64 81</syntaxhighlight>
 
=={{header|QB64}}==
<syntaxhighlight lang=QB64"qb64">
'Task
'Take a combined set of elements and apply a function to each element.
Line 2,756 ⟶ 2,945:
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"quackery">/O> [ 3 ** ] is cubed ( n --> n )
...
 
Line 2,782 ⟶ 2,971:
=={{header|R}}==
Many functions can take advantage of implicit vectorisation, e.g.
<syntaxhighlight lang=R"r">cube <- function(x) x*x*x
elements <- 1:5
cubes <- cube(elements)</syntaxhighlight>
Explicit looping over array elements is also possible.
<syntaxhighlight lang=R"r">cubes <- numeric(5)
for(i in seq_along(cubes))
{
Line 2,792 ⟶ 2,981:
}</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.
<syntaxhighlight lang=R"r">elements2 <- list(1,2,3,4,5)
cubes <- sapply(elements2, cube)</syntaxhighlight>
In each case above, the value of 'cubes' is
Line 2,799 ⟶ 2,988:
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
#lang racket
 
Line 2,813 ⟶ 3,002:
{{works with|Rakudo|2015.10-11}}
 
<syntaxhighlight lang=perl6"raku" line>sub function { 2 * $^x + 3 };
my @array = 1 .. 5;
 
Line 2,835 ⟶ 3,024:
 
=={{header|Raven}}==
<syntaxhighlight lang="raven"># To print the squared elements
[1 2 3 4 5] each dup * print</syntaxhighlight>
 
<syntaxhighlight lang="raven"># To obtain a new array
group [1 2 3 4 5] each
dup *
Line 2,844 ⟶ 3,033:
 
=={{header|REBOL}}==
<syntaxhighlight lang=REBOL"rebol">REBOL [
Title: "Array Callback"
URL: http://rosettacode.org/wiki/Apply_a_callback_to_an_Array
Line 2,885 ⟶ 3,074:
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"retro">{ #1 #2 #3 #4 #5 } [ #10 * ] a:map [ n:put sp ] a:for-each</syntaxhighlight>
 
=={{header|REXX}}==
<syntaxhighlight lang="rexx">/*REXX program applies a callback to an array (using factorials for a demonstration).*/
numeric digits 100 /*be able to display some huge numbers.*/
parse arg # . /*obtain an optional value from the CL.*/
Line 2,945 ⟶ 3,134:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
for x in [1,2,3,4,5]
x = x*x
Line 2,965 ⟶ 3,154:
Consider an example:
 
<syntaxhighlight lang=RLaB"rlab">
>> x = rand(2,4)
0.707213207 0.275298961 0.396757763 0.232312312
Line 2,977 ⟶ 3,166:
'for' or 'while' loops are slow in interpreted languages, and RLaB is no exception.
 
<syntaxhighlight lang=RLaB"rlab">
x = rand(2,4);
y = zeros(2,4);
Line 2,994 ⟶ 3,183:
function 'members' which returns a string vector with the names of the elements of the list.
 
<syntaxhighlight lang=RLaB"rlab">
x = <<>>;
for (i in 1:9)
Line 3,007 ⟶ 3,196:
}
</syntaxhighlight>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
≪ → array func
≪ array 0 CON
1 array SIZE FOR j
j array j GET func EVAL PUT
NEXT
≫ ≫
´MAP’ STO
 
[1,2,3,4,5,6,7,8,9] ≪ SQ ≫ MAP
{{out}}
<pre>
1: [ 1 4 9 16 25 36 49 64 81 ]
</pre>
 
=={{header|Ruby}}==
You could use a traditional "for i in arr" approach like below:
<syntaxhighlight lang="ruby">for i in [1,2,3,4,5] do
puts i**2
end</syntaxhighlight>
 
Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk)
<syntaxhighlight lang="ruby">[1,2,3,4,5].each{ |i| puts i**2 }</syntaxhighlight>
 
To create a new array of each value squared
<syntaxhighlight lang="ruby">[1,2,3,4,5].map{ |i| i**2 }</syntaxhighlight>
 
=={{header|Rust}}==
 
<syntaxhighlight lang="rust">fn echo(n: &i32) {
println!("{}", n);
}
Line 3,036 ⟶ 3,241:
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"salmon">function apply(list, ageless to_apply)
(comprehend(x; list) (to_apply(x)));
 
Line 3,046 ⟶ 3,251:
With short identifiers:
 
<syntaxhighlight lang=Salmon"salmon">include "short.salm";
 
fun apply(list, ageless to_apply)
Line 3,058 ⟶ 3,263:
With the numbers given as a list of individual elements:
 
<syntaxhighlight lang=Salmon"salmon">function apply(list, to_apply)
(comprehend(x; list) (to_apply(x)));
 
Line 3,067 ⟶ 3,272:
 
=={{header|Sather}}==
<syntaxhighlight lang="sather">class MAIN is
do_something(i:INT):INT is
return i * i;
Line 3,081 ⟶ 3,286:
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">val l = List(1,2,3,4)
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
<syntaxhighlight lang="scala">l.foreach(println(_))</syntaxhighlight>
Same for an array
<syntaxhighlight lang="scala">val a = Array(1,2,3,4)
a.foreach {i => println(i)}
a.foreach(println(_)) '' // same as previous line''</syntaxhighlight>
 
Or for an externally defined function:
<syntaxhighlight lang="scala">def doSomething(in: int) = {println("Doing something with "+in)}
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''
<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)
<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
<syntaxhighlight lang="scala">val squares = for (val i <- l) yield i * i</syntaxhighlight>
 
=={{header|Scheme}}==
<syntaxhighlight lang="scheme">(define (square n) (* n n))
(define x #(1 2 3 4 5))
(map square (vector->list x))</syntaxhighlight>
 
A single-line variation
<syntaxhighlight lang="scheme">(map (lambda (n) (* n n)) '(1 2 3 4 5))</syntaxhighlight>
 
For completeness, the <tt>map</tt> function (which is R5RS standard) can be coded as follows:
<syntaxhighlight lang="scheme">(define (map f L)
(if (null? L)
L
Line 3,119 ⟶ 3,324:
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">
put each item in [1,2,3,5,9,14,24] squared
 
Line 3,128 ⟶ 3,333:
end myFunc</syntaxhighlight>
Output:
<syntaxhighlight lang="sensetalk">(1,4,9,25,81,196,576)
(3,5,7,11,19,29,49)</syntaxhighlight>
 
=={{header|Sidef}}==
Defining a callback function:
<syntaxhighlight lang="ruby">func callback(i) { say i**2 }</syntaxhighlight>
 
The function will get called for each element:
<syntaxhighlight lang="ruby">[1,2,3,4].each(callback)</syntaxhighlight>
 
Same as above, but with the function inlined:
<syntaxhighlight lang="ruby">[1,2,3,4].each{|i| say i**2 }</syntaxhighlight>
 
For creating a new array, we can use the Array.map method:
<syntaxhighlight lang="ruby">[1,2,3,4,5].map{|i| i**2 }</syntaxhighlight>
 
=={{header|Simula}}==
<syntaxhighlight lang="simula">BEGIN
 
! APPLIES A CALLBACK FUNCTION TO AN ARRAY ;
Line 3,173 ⟶ 3,378:
 
=={{header|Slate}}==
<syntaxhighlight lang="slate">#( 1 2 3 4 5 ) collect: [| :n | n * n].</syntaxhighlight>
 
=={{header|Smalltalk}}==
<syntaxhighlight lang="smalltalk">#( 1 2.0 'three') do: [:each | each displayNl].</syntaxhighlight>
You can tell symbols how to react to the <tt>value:</tt> message, and then write &sup2;:
<syntaxhighlight lang="smalltalk">#( 1 2.0 'three') do: #displayNl.</syntaxhighlight>
2) actually most dialects already have it, and it is trivial to add, if it does not.
 
There is a huge number of additional enumeration messages implemented in Collection, from which Array inherits. Eg.:
<syntaxhighlight lang="smalltalk">#( 1 2 3 4 5 ) collect: [:n | n * n].</syntaxhighlight>
 
=={{header|Sparkling}}==
The <tt>foreach</tt> function calls the supplied callback on each element of the (possibly associative) array, passing it each key and the corresponding value:
<syntaxhighlight lang="sparkling">let numbers = { 1, 2, 3, 4 };
foreach(numbers, function(idx, num) {
print(num);
Line 3,192 ⟶ 3,397:
 
The <tt>map</tt> function applies the transform to each key-value pair and constructs a new array, of which the keys are the keys of the original array, and the corresponding values are the return values of each call to the transform function:
<syntaxhighlight lang="sparkling">let dict = { "foo": 42, "bar": 13, "baz": 37 };
let doubled = map(dict, function(key, val) {
return val * 2;
Line 3,200 ⟶ 3,405:
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
<syntaxhighlight lang="sql pl">
--#SET TERMINATOR @
 
Line 3,245 ⟶ 3,450:
 
=={{header|Standard ML}}==
<syntaxhighlight lang=Standard"standard MLml">
map f l
</syntaxhighlight>
i.e.
<syntaxhighlight lang=Standard"standard MLml">
map (fn x=>x+1) [1,2,3];; (* [2,3,4] *)
</syntaxhighlight>
Line 3,256 ⟶ 3,461:
There is no 'map' function in Mata, but it's easy to implement. Notice that you can only pass functions that are written in Mata, no builtin ones. For instance, the trigonometric functions (cos, sin) or the exponential are builtin. To pass a builtin function to another function, one needs to write a wrapper in Mata. See also Stata help about '''[https://www.stata.com/help.cgi?m2_pointers pointers]''' and '''[https://www.stata.com/help.cgi?m2_ftof passing functions to functions]'''. There are two versions of the function: one to return a numeric array, another to return a string array.
 
<syntaxhighlight lang="stata">function map(f,a) {
nr = rows(a)
nc = cols(a)
Line 3,291 ⟶ 3,496:
=={{header|SuperCollider}}==
Actually, there is a builtin <tt>squared</tt> operator:
<syntaxhighlight lang=SuperCollider"supercollider">[1, 2, 3].squared // returns [1, 4, 9]</syntaxhighlight>
Anything that is a <tt>Collection</tt> can be used with <tt>collect</tt>:
<syntaxhighlight lang=SuperCollider"supercollider">[1, 2, 3].collect { |x| x * x }</syntaxhighlight>
[[List Comprehension#SuperCollider|List comprehension]] combined with a higher-order function can also be used:
<syntaxhighlight lang=SuperCollider"supercollider">var square = { |x| x * x };
var map = { |fn, xs|
all {: fn.value(x), x <- xs };
Line 3,302 ⟶ 3,507:
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">func square(n: Int) -> Int {
return n * n
}
Line 3,317 ⟶ 3,522:
 
=={{header|Tailspin}}==
<syntaxhighlight lang="tailspin">
def numbers: [1,3,7,10];
 
Line 3,337 ⟶ 3,542:
 
If I wanted to call "<tt>myfunc</tt>" on each element of <tt>dat</tt> and <tt>dat</tt> were a list:
<syntaxhighlight lang="tcl">foreach var $dat {
myfunc $var
}</syntaxhighlight>
Line 3,343 ⟶ 3,548:
 
if <tt>dat</tt> were an (associative) array, however:
<syntaxhighlight lang="tcl">foreach name [array names dat] {
myfunc $dat($name)
}</syntaxhighlight>
 
More functional, with a simple <code>map</code> function:
<syntaxhighlight lang=Tcl"tcl">proc map {f list} {
set res {}
foreach e $list {lappend res [$f $e]}
Line 3,360 ⟶ 3,565:
=={{header|TI-89 BASIC}}==
 
<syntaxhighlight lang="ti89b">© For no return value
Define foreach(fe_cname,fe_list) = Prgm
Local fe_i
Line 3,390 ⟶ 3,595:
JavaScript alike:
 
<syntaxhighlight lang="javascript">var a = [1, 2, 3, 4, 5];
a.map(function(v) { return v * v; })
</syntaxhighlight>
 
Using short form of lambda notation:
<syntaxhighlight lang="javascript">var a = [1, 2, 3, 4, 5];
a.map( :v: v*v );
</syntaxhighlight>
Line 3,401 ⟶ 3,606:
=={{header|Toka}}==
 
<syntaxhighlight lang="toka">( array count function -- )
{
value| array fn |
Line 3,425 ⟶ 3,630:
Callbacks:
 
<syntaxhighlight lang=TorqueScript"torquescript">
function map(%array,%arrayCount,%function)
{
Line 3,438 ⟶ 3,643:
Now to set up an array:
 
<syntaxhighlight lang=TorqueScript"torquescript">
$array[0] = "Hello.";
$array[1] = "Hi.";
Line 3,446 ⟶ 3,651:
Now to call the function correctly:
 
<syntaxhighlight lang=TorqueScript"torquescript">
map("$array",3,"echo");
</syntaxhighlight>
Line 3,452 ⟶ 3,657:
Which should result in:
 
<syntaxhighlight lang=TorqueScript"torquescript">
=> Hello.
 
Line 3,464 ⟶ 3,669:
Print 1 through 10 out of a vector, using <code>prinl</code> the callback, right from the system shell command prompt:
 
<syntaxhighlight lang="bash">$ txr -e '[mapdo prinl #(1 2 3 4 5 6 7 8 9 10)]'
1
2
Line 3,482 ⟶ 3,687:
=={{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.
<syntaxhighlight lang="text">S = 5 ' Size of the array
 
For x = 0 To S - 1 ' Initialize array
Line 3,561 ⟶ 3,766:
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
<syntaxhighlight lang="bash">map() {
map_command=$1
shift
Line 3,572 ⟶ 3,777:
{{works with|pdksh}}
{{works with|zsh}}
<syntaxhighlight lang="bash">map() {
typeset command=$1
shift
Line 3,581 ⟶ 3,786:
 
{{works with|zsh}}
<syntaxhighlight lang="bash">map(){for i ($*[2,-1]) $1 $i}
a=(1 2 3)
map print $a</syntaxhighlight>
Line 3,588 ⟶ 3,793:
The * is a built-in map operator.
This example shows a map of the successor function over a list of natural numbers.
<syntaxhighlight lang=Ursala"ursala">#import nat
 
#cast %nL
Line 3,600 ⟶ 3,805:
=={{header|V}}==
apply squaring (dup *) to each member of collection
<syntaxhighlight lang="v">[1 2 3 4] [dup *] map</syntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
 
Line 3,633 ⟶ 3,838:
 
=====Implementation=====
<syntaxhighlight lang="vb">
class callback
dim sRule
Line 3,653 ⟶ 3,858:
 
=====Invocation=====
<syntaxhighlight lang="vb">
dim a1
dim cb
Line 3,680 ⟶ 3,885:
The result of evaluating the string will be the new value.
The list/dictionary is modified in place.
<syntaxhighlight lang="vim">echo map([10, 20, 30], 'v:val * v:val')
echo map([10, 20, 30], '"Element " . v:key . " = " . v:val')
echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:val)')
Line 3,702 ⟶ 3,907:
and System.Linq.Enumerable.ToArray(Of TSource)(IEnumerable(Of TSource)) eagerly converts the enumerable to an array.
 
<syntaxhighlight lang="vbnet">Module Program
Function OneMoreThan(i As Integer) As Integer
Return i + 1
Line 3,736 ⟶ 3,941:
=={{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)</syntaxhighlight>
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.
<syntaxhighlight lang="vorpal">A.map(F, x, y)</syntaxhighlight>
 
=={{header|Wart}}==
<syntaxhighlight lang="wart">map prn '(1 2 3 4 5)</syntaxhighlight>
 
{{Out}}
Line 3,752 ⟶ 3,957:
 
=={{header|WDTE}}==
<syntaxhighlight lang=WDTE"wdte">let a => import 'arrays';
let s => import 'stream';
 
Line 3,765 ⟶ 3,970:
 
=={{header|Wren}}==
<syntaxhighlight lang=ecmascript"wren">var arr = [1, 2, 3, 4, 5]
arr = arr.map { |x| x * 2 }.toList
arr = arr.map(Fn.new { |x| x / 2 }).toList
Line 3,780 ⟶ 3,985:
 
=={{header|XBS}}==
<syntaxhighlight lang="xbs">func map(arr:array,callback:function){
set newArr:array = [];
foreach(k,v as arr){
Line 3,802 ⟶ 4,007:
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">sub map(f$, t())
local i
 
Line 3,835 ⟶ 4,040:
 
=={{header|Yacas}}==
<syntaxhighlight lang=Yacas"yacas">Sin /@ {1, 2, 3, 4}
 
MapSingle(Sin, {1,2,3,4})
Line 3,843 ⟶ 4,048:
 
=={{header|Z80 Assembly}}==
<syntaxhighlight lang="z80">Array:
byte &01,&02,&03,&04,&05
Array_End:
Line 3,865 ⟶ 4,070:
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">pub fn main() !void {
var array = [_]i32{1, 2, 3};
apply(@TypeOf(array[0]), array[0..], func);
Line 3,882 ⟶ 4,087:
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">L(1,2,3,4,5).apply('+(5))</syntaxhighlight>
{{Out}}
<pre>
Line 3,889 ⟶ 4,094:
 
=={{header|zonnon}}==
<syntaxhighlight lang="zonnon">
module Main;
type
Line 3,936 ⟶ 4,141:
 
=={{header|ZX Spectrum Basic}}==
<syntaxhighlight lang="zxbasic">10 LET a$="x+x"
20 LET b$="x*x"
30 LET c$="x+x^2"
885

edits