I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)

# Apply a callback to an array

Apply a callback to an array
You are encouraged to solve this task according to the task description, using any language you may know.

Take a combined set of elements and apply a function to each element.

## 11l

Translation of: Kotlin
V array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]V arrsq = array.map(i -> i * i)print(arrsq)
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

## 6502 Assembly

For this example, assume both the source array and the destination have a size of 86 elements (memory offsets base+0x00 to base+0x55.) This was implemented in easy6502.

define SRC_LO  $00define SRC_HI$01 define DEST_LO $02define DEST_HI$03 define temp $04 ;temp storage used by foo ;some prep work since easy6502 doesn't allow you to define arbitrary bytes before runtime. SET_TABLE:TXASTA$1000,XINXBNE SET_TABLE	;stores the identity table at memory address $1000-$10FF CLEAR_TABLE:LDA #0STA $1200,XINXBNE CLEAR_TABLE;fills the range$1200-$12FF with zeroes. LDA #$10STA SRC_HILDA #$00STA SRC_LO;store memory address$1000 in zero page LDA #$12STA DEST_HILDA #$00STA DEST_LO;store memory address $1200 in zero page loop:LDA (SRC_LO),y ;load accumulator from memory address$1000+yJSR foo		;multiplies accumulator by 3.STA (DEST_LO),y ;store accumulator in memory address $1200+y INYCPY #$56 ;alternatively you can store a size variable and check that here instead.BCC loopBRK foo:STA tempASL		;double accumulatorCLCADC temp	;2a + a = 3aRTS
Output:
1200: 00 03 06 09 0c 0f 12 15 18 1b 1e 21 24 27 2a 2d
1210: 30 33 36 39 3c 3f 42 45 48 4b 4e 51 54 57 5a 5d
1220: 60 63 66 69 6c 6f 72 75 78 7b 7e 81 84 87 8a 8d
1230: 90 93 96 99 9c 9f a2 a5 a8 ab ae b1 b4 b7 ba bd
1240: c0 c3 c6 c9 cc cf d2 d5 d8 db de e1 e4 e7 ea ed
1250: f0 f3 f6 f9 fc ff


## 8th

The builtin word "a:map" does this:

 [ 1 , 2, 3 ]' n:sqra:map

That results in the array [1,4,9]

## ACL2

ACL2 does not have first-class functions; this is close, however:

(defun apply-to-each (xs)   (if (endp xs)       nil       (cons (fn-to-apply (first xs))             (sq-each (rest xs))))) (defun fn-to-apply (x)   (* x x))

## ActionScript

package{    public class ArrayCallback    {        public function main():void        {            var nums:Array = new Array(1, 2, 3);            nums.map(function(n:Number, index:int, arr:Array):void { trace(n * n * n); });             // You can also pass a function reference            nums.map(cube);        }         private function cube(n:Number, index:int, arr:Array):void        {            trace(n * n * n);        }    }}

Works with: GNAT version GPL 2005
with Ada.Text_Io; with Ada.Integer_text_IO;  procedure Call_Back_Example is    -- Purpose: Apply a callback to an array    -- Output: Prints the squares of an integer array to the console     -- Define the callback procedure    procedure Display(Location : Positive; Value : Integer) is    begin       Ada.Text_Io.Put("array(");       Ada.Integer_Text_Io.Put(Item => Location, Width => 1);       Ada.Text_Io.Put(") = ");       Ada.Integer_Text_Io.Put(Item => Value * Value, Width => 1);       Ada.Text_Io.New_Line;    end Display;     -- Define an access type matching the signature of the callback procedure    type Call_Back_Access is access procedure(L : Positive; V : Integer);     -- Define an unconstrained array type    type Value_Array is array(Positive range <>) of Integer;     -- Define the procedure performing the callback    procedure Map(Values : Value_Array; Worker : Call_Back_Access) is    begin       for I in Values'range loop          Worker(I, Values(I));       end loop;    end Map;     -- Define and initialize the actual array    Sample : Value_Array := (5,4,3,2,1);  begin    Map(Sample, Display'access);    end Call_Back_Example;

## Aime

voidmap(list l, void (*fp)(object)){    l.ucall(fp, 0);} voidout(object o){    o_(o, "\n");} integermain(void){    list(0, 1, 2, 3).map(out);     return 0;}

## ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
 PROC call back proc = (INT location, INT value)VOID: (   printf(($"array["g"] = "gl$, location, value)) );  PROC map = (REF[]INT array, PROC (INT,INT)VOID call back)VOID: (   FOR i FROM LWB array TO UPB array DO      call back(i, array[i])   OD );  main: (   [4]INT array := ( 1, 4, 9, 16 );   map(array, call back proc) )
Output:
array[         +1] =          +1
array[         +2] =          +4
array[         +3] =          +9
array[         +4] =         +16


## ALGOL W

begin    procedure printSquare ( integer value x ) ; writeon( i_w := 1, s_w := 0, " ", x * x );    % applys f to each element of a from lb to ub (inclusive) %    procedure applyI ( procedure f; integer array a ( * ); integer value lb, ub ) ;        for i := lb until ub do f( a( i ) );    % test applyI %    begin        integer array a ( 1 :: 3 );        a( 1 ) := 1; a( 2 ) := 2; a( 3 ) := 3;        applyI( printSquare, a, 1, 3 )    endend.

## APL

By default functions in APL work on arrays as it is an array oriented language. Some examples:

    - 1 2 3¯1 ¯2 ¯3    2 * 1 2 3 42 4 8 16    2 × ⍳42 4 6 8    3 * 3 3 ⍴ ⍳9   3    9    27  81  243   7292187 6561 19683

## AppleScript

on callback for arg    -- Returns a string like "arc has 3 letters"    arg & " has " & (count arg) & " letters"end callback set alist to {"arc", "be", "circle"}repeat with aref in alist    -- Passes a reference to some item in alist    -- to callback, then speaks the return value.    say (callback for aref)end repeat

If the callback would set arg's contents to "something", then alist would be mutated.

For a more general implementation of map(function, list), foldl(function, startValue, list), and filter(predicate, list), we could write:

on run     set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}     {map(square, xs), ¬        filter(even, xs), ¬        foldl(add, 0, xs)}     --> {{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}, {2, 4, 6, 8, 10}, 55}   end run -- square :: Num -> Num -> Numon square(x)    x * xend square -- add :: Num -> Num -> Numon add(a, b)    a + bend add -- even :: Int -> Boolon even(x)    0 = x mod 2end even  -- GENERIC HIGHER ORDER FUNCTIONS -- filter :: (a -> Bool) -> [a] -> [a]on filter(f, xs)    tell mReturn(f)        set lst to {}        set lng to length of xs        repeat with i from 1 to lng            set v to item i of xs            if |λ|(v, i, xs) then set end of lst to v        end repeat        return lst    end tellend filter -- foldl :: (a -> b -> a) -> a -> [b] -> aon foldl(f, startValue, xs)    tell mReturn(f)        set v to startValue        set lng to length of xs        repeat with i from 1 to lng            set v to |λ|(v, item i of xs, i, xs)        end repeat        return v    end tellend foldl -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: First-class m => (a -> b) -> m (a -> b)on mReturn(f)    if class of f is script then        f    else        script            property |λ| : f        end script    end ifend mReturn -- map :: (a -> b) -> [a] -> [b]on map(f, xs)    tell mReturn(f)        set lng to length of xs        set lst to {}        repeat with i from 1 to lng            set end of lst to |λ|(item i of xs, i, xs)        end repeat        return lst    end tellend map
Output:
{{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}, {2, 4, 6, 8, 10}, 55}

## Arturo

arr: [1 2 3 4 5] print map arr => [2*]
Output:
2 4 6 8 10

## AutoHotkey

map("callback", "3,4,5") callback(array){  Loop, Parse, array, ,    MsgBox % (2 * A_LoopField)} map(callback, array){  %callback%(array)}

## AWK

$awk 'func psqr(x){print x,x*x}BEGIN{split("1 2 3 4 5",a);for(i in a)psqr(a[i])}'4 165 251 12 43 9 ## Babel Let us define a squaring operator: sq { dup * } < Now, we apply the sq operator over a list and display the result using the lsnum utility: ( 0 1 1 2 3 5 8 13 21 34 ) { sq ! } over ! lsnum ! Output: ( 0 1 1 4 9 25 64 169 441 1156 ) ## BBC BASIC  DIM a(4) a() = 1, 2, 3, 4, 5 PROCmap(a(), FNsqrt()) FOR i = 0 TO 4 PRINT a(i) NEXT END DEF FNsqrt(n) = SQR(n) DEF PROCmap(array(), RETURN func%) LOCAL I% FOR I% = 0 TO DIM(array(),1) array(I%) = FN(^func%)(array(I%)) NEXT ENDPROC  Output:  1 1.41421356 1.73205081 2 2.23606798  ## Bracmat ( ( callbackFunction1 = location value . !arg:(?location,?value) & out$(str$(array[ !location "] = " !!value)) )& ( callbackFunction2 = location value . !arg:(?location,?value) & !!value^2:?!value )& ( mapar = arr len callback i . !arg:(?arr,?len,?callback) & 0:?i & whl ' ( !i:<!len & !callback$(!i,!i$!arr) & 1+!i:?i ) )& tbl$(array,4)& 1:?(0$array)& 2:?(1$array)& 3:?(2$array)& 4:?(3$array)& mapar$(array,4,callbackFunction1)& mapar$(array,4,callbackFunction2)& mapar$(array,4,callbackFunction1)); Output: array[0] = 1 array[1] = 2 array[2] = 3 array[3] = 4 array[0] = 1 array[1] = 4 array[2] = 9 array[3] = 16 ## Brat #Print out each element in array[:a :b :c :d :e].each { element | p element} Alternatively: [:a :b :c :d :e].each ->p ## C callback.h #ifndef CALLBACK_H#define CALLBACK_H /* * By declaring the function in a separate file, we allow * it to be used by other source files. * * It also stops ICC from complaining. * * If you don't want to use it outside of callback.c, this * file can be removed, provided the static keyword is prepended * to the definition. */void map(int* array, int len, void(*callback)(int,int)); #endif callback.c #include <stdio.h>#include "callback.h" /* * We don't need this function outside of this file, so * we declare it static. */static void callbackFunction(int location, int value){ printf("array[%d] = %d\n", location, value);} void map(int* array, int len, void(*callback)(int,int)){ int i; for(i = 0; i < len; i++) { callback(i, array[i]); }} int main(){ int array[] = { 1, 2, 3, 4 }; map(array, 4, callbackFunction); return 0;} Output:  array[0] = 1 array[1] = 2 array[2] = 3 array[3] = 4  ## C# Works with: C# version 3.0+ This version uses the C# 3 lambda notation. int[] intArray = { 1, 2, 3, 4, 5 };// Simplest method: LINQ, functionalint[] squares1 = intArray.Select(x => x * x).ToArray(); // Slightly fancier: LINQ, query expressionint[] squares2 = (from x in intArray select x * x).ToArray(); // Or, if you only want to call a function on each element, just use foreachforeach (var i in intArray) Console.WriteLine(i * i); Works with: C# version 2.0+ Works with: Visual C# version 2005 using System; static class Program{ // Purpose: Apply a callback (or anonymous method) to an Array // Output: Prints the squares of an int array to the console. // Compiler: Visual Studio 2005 // Framework: .net 2 [STAThread] public static void Main() { int[] intArray = { 1, 2, 3, 4, 5 }; // Using a callback, Console.WriteLine("Printing squares using a callback:"); Array.ForEach<int>(intArray, PrintSquare); // or using an anonymous method: Console.WriteLine("Printing squares using an anonymous method:"); Array.ForEach<int> ( intArray, delegate(int value) { Console.WriteLine(value * value); }); } public static void PrintSquare(int value) { Console.WriteLine(value * value); }} ## C++ Works with: g++ version 4.1.1 ### C-Style Array #include <iostream> //cout for printing#include <algorithm> //for_each defined here //create the function (print the square)void print_square(int i) { std::cout << i*i << " ";} int main() { //create the array int ary[]={1,2,3,4,5}; //stl for_each std::for_each(ary,ary+5,print_square); return 0;}//prints 1 4 9 16 25 ### std::vector Library: STL #include <iostream> // cout for printing#include <algorithm> // for_each defined here#include <vector> // stl vector class // create the function (print the square)void print_square(int i) { std::cout << i*i << " ";} int main() { // create the array std::vector<int> ary; ary.push_back(1); ary.push_back(2); ary.push_back(3); ary.push_back(4); ary.push_back(5); // stl for_each std::for_each(ary.begin(),ary.end(),print_square); return 0;}//prints 1 4 9 16 25 More tricky with binary function #include <iostream> // cout for printing#include <algorithm> // for_each defined here#include <vector> // stl vector class#include <functional> // bind and ptr_fun // create a binary function (print any two arguments together)template<class type1,class type2>void print_juxtaposed(type1 x, type2 y) { std::cout << x << y;} int main() { // create the array std::vector<int> ary; ary.push_back(1); ary.push_back(2); ary.push_back(3); ary.push_back(4); ary.push_back(5); // stl for_each, using binder and adaptable unary function std::for_each(ary.begin(),ary.end(),std::bind2nd(std::ptr_fun(print_juxtaposed<int,std::string>),"x ")); return 0;}//prints 1x 2x 3x 4x 5x ### Boost.Lambda Library: Boost using namespace std;using namespace boost::lambda;vector<int> ary(10);int i = 0;for_each(ary.begin(), ary.end(), _1 = ++var(i)); // init arraytransform(ary.begin(), ary.end(), ostream_iterator<int>(cout, " "), _1 * _1); // square and output ### C++11 #include <vector>#include <iostream>#include <algorithm>#include <iterator> int main() { std::vector<int> intVec(10); std::iota(std::begin(intVec), std::end(intVec), 1 ); // Fill the vector std::transform(std::begin(intVec) , std::end(intVec), std::begin(intVec), [](int i) { return i * i ; } ); // Transform it with closures std::copy(std::begin(intVec), end(intVec) , std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; return 0;} ## Clean Define a function and an initial (unboxed) array. square x = x * x values :: {#Int}values = {x \\ x <- [1 .. 10]} One can easily define a map for arrays, which is overloaded and works for all kinds of arrays (lazy, strict, unboxed). mapArray f array = {f x \\ x <-: array} Apply the function to the initial array (using a comprehension) and print result. Start :: {#Int}Start = mapArray square values ## Clio Math operations [1 2 3 4] * 2 + 1 -> print Quick functions [1 2 3 4] -> * n: n * 2 + 1 -> print Anonymous function [1 2 3 4] -> * fn n: n * 2 + 1 -> print Named function fn double-plus-one n: n * 2 + 1 [1 2 3 4] -> * double-plus-one -> print ## Clojure ;; apply a named function, inc(map inc [1 2 3 4]) ;; apply a function(map (fn [x] (* x x)) [1 2 3 4]) ;; shortcut syntax for a function(map #(* % %) [1 2 3 4]) ## CLU % This procedure will call a given procedure with each element% of the given array. Thanks to CLU's type parameterization,% it will work for any type of element.apply_to_all = proc [T: type] (a: array[T], f: proctype(int,T)) for i: int in array[T]$indexes(a) do        f(i, a[i])    endend apply_to_all % Callbacks for both string and intshow_int = proc (i, val: int)    po: stream := stream$primary_output() stream$putl(po, "array[" || int$unparse(i) || "] = " || int$unparse(val));end show_int show_string = proc (i: int, val: string)    po: stream := stream$primary_output() stream$putl(po, "array[" || int$unparse(i) || "] = " || val);end show_string % Here's how to use themstart_up = proc () po: stream := stream$primary_output()     ints: array[int] := array[int]$[2, 3, 5, 7, 11] strings: array[string] := array[string]$        ["enemy", "lasagna", "robust", "below", "wax"]     stream$putl(po, "Ints: ") apply_to_all[int](ints, show_int) stream$putl(po, "\nStrings: ")    apply_to_all[string](strings, show_string)end start_up
Output:
Ints:
array[1] = 2
array[2] = 3
array[3] = 5
array[4] = 7
array[5] = 11

Strings:
array[1] = enemy
array[2] = lasagna
array[3] = robust
array[4] = below
array[5] = wax

## COBOL

Basic implementation of a map function:

       IDENTIFICATION DIVISION.       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.        01  Func-Id PIC X(30).        PROCEDURE DIVISION USING Table-Param Func-Id.           PERFORM VARYING I FROM 1 BY 1 UNTIL Table-Size < I               CALL Func-Id USING BY REFERENCE Table-Values (I)           END-PERFORM            GOBACK           .

## CoffeeScript

 map = (arr, f) -> (f(e) for e in arr)arr = [1, 2, 3, 4, 5]f = (x) -> x * xconsole.log map arr, f # prints [1, 4, 9, 16, 25] 

## Common Lisp

Imperative: print 1, 2, 3, 4 and 5:

(map nil #'print #(1 2 3 4 5))

Functional: collect squares into new vector that is returned:

(defun square (x) (* x x))(map 'vector #'square #(1 2 3 4 5))

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

(defvar *a* (vector 1 2 3))(map-into *a* #'1+ *a*)

## Component Pascal

BlackBox Component Builder

 MODULE Callback;IMPORT StdLog; TYPE	Callback = PROCEDURE (x: INTEGER;OUT doubled: INTEGER);	Callback2 = PROCEDURE (x: INTEGER): INTEGER; 	PROCEDURE Apply(proc: Callback; VAR x: ARRAY OF INTEGER);	VAR		i: INTEGER;	BEGIN		FOR i := 0 TO LEN(x) - 1 DO;			proc(x[i],x[i]);		END	END Apply; 	PROCEDURE Apply2(func: Callback2; VAR x: ARRAY OF INTEGER);	VAR		i: INTEGER;	BEGIN		FOR i := 0 TO LEN(x) - 1 DO;			x[i] := func(x[i]);		END	END Apply2; 	PROCEDURE Double(x: INTEGER; OUT y: INTEGER);	BEGIN			y := x * x;	END Double; 	PROCEDURE Double2(x: INTEGER): INTEGER;	BEGIN		RETURN x * x	END Double2; 	PROCEDURE Do*;	VAR		i: INTEGER;		ary: ARRAY 10 OF INTEGER;  	BEGIN		FOR i := 0 TO LEN(ary) - 1 DO ary[i] := i END;		Apply(Double,ary);		FOR i := 0 TO LEN(ary) - 1 DO			StdLog.Int(ary[i]);StdLog.Ln		END;		StdLog.Ln;		Apply2(Double2,ary);		FOR  i := 0 TO LEN(ary) - 1 DO		        StdLog.Int(ary[i]);StdLog.Ln		END	END Do;END Callback. 

Execute: ^Q Callback.Do

Output:
 0
1
4
9
16
25
36
49
64
81

0
1
16
81
256
625
1296
2401
4096
6561


## Crystal

Calling with a block

values = [1, 2, 3] new_values = values.map do |number|  number * 2end puts new_values  #=> [2, 4, 6]

Calling with a function/method

values = [1, 2, 3] def double(number)  number * 2end # the ->double(Int32) syntax creates a proc from a function/method. argument types must be specified.# the &proc syntax passes a proc as a block.# combining the two passes a function/method as a blocknew_values = values.map &->double(Int32) puts new_values  #=> [2, 4, 6]

## D

import std.stdio, std.algorithm; void main() {    auto items = [1, 2, 3, 4, 5];    auto m = items.map!(x => x + 5)();    writeln(m);}
Output:
[6, 7, 8, 9, 10]

## Delphi

 // Declare the callback functionprocedure callback(const AInt:Integer);begin  WriteLn(AInt);end; const  // Declare a static array  myArray:Array[0..4] of Integer=(1,4,6,8,7);var  // Declare interator variable  i:Integer;begin  // Iterate the array and apply callback  for i:=0 to length(myArray)-1 do    callback(myArray[i]);end. 

## Dyalect

func Array.select(pred) {    for x in this when pred(x) {        yield x    }} var arr = [1, 2, 3, 4, 5]var squares = arr.select(x => x * x) print(squares)

## Déjà Vu

There is a map builtin that does just this.

!. map @++ [ 1 4 8 ] #implemented roughly like this:#map f lst:#    ]#    for i in lst:#         f i#    [
Output:
[ 2 5 9 ]

## E

def array := [1,2,3,4,5]def square(value) {     return value * value}

Example of builtin iteration:

def callback(index, value) {     println(Item $index is$value.)}array.iterate(callback)

There is no built-in map function yet. The following is one of the ways one could be implemented, returning a plain list (which is usually an array in implementation).

def map(func, collection) {    def output := [].diverge()    for item in collection {        output.push(func(item))    }    return output.snapshot()}println(map(square, array))

## EchoLisp

 (vector-map sqrt #(0 4 16 49))    → #( 0 2 4 7);; or(map exp #(0 1 2))    → #( 1 2.718281828459045 7.38905609893065);; or(for/vector ([elem #(2 3 4)] [i (in-naturals)]) (printf "v[%d] = %a" i elem) (* elem elem))v[0] = 2v[1] = 3v[2] = 4    → #( 4 9 16) 

## Efene

square = fn (N) {    N * N} # list comprehensionsquares1 = fn (Numbers) {    [square(N) for N in Numbers]} # functional formsquares2a = fn (Numbers) {    lists.map(fn square:1, Numbers)} # functional form with lambdasquares2b = fn (Numbers) {    lists.map(fn (N) { N * N }, Numbers)} # no need for a functionsquares3 = fn (Numbers) {    [N * N for N in Numbers]} @publicrun = fn () {    Numbers = [1, 3, 5, 7]    io.format("squares1 : ~p~n", [squares1(Numbers)])    io.format("squares2a: ~p~n", [squares2a(Numbers)])    io.format("squares2b: ~p~n", [squares2b(Numbers)])    io.format("squares3 : ~p~n", [squares3(Numbers)])} 

## EGL

delegate callback( i int ) returns( int ) end program ApplyCallbackToArray	function main()		values int[] = [ 1, 2, 3, 4, 5 ]; 		func callback = square;		for ( i int to values.getSize() )			values[ i ] = func( values[ i ] );		end 		for ( i int to values.getSize() )			SysLib.writeStdout( values[ i ] );		end	end 	function square( i int ) returns( int )		return( i * i );	endend

## Elena

ELENA 5.0 :

import system'routines; PrintSecondPower(n){ console.writeLine(n * n) } public program(){    new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.forEach:PrintSecondPower}

## Elixir

 Enum.map([1, 2, 3], fn(n) -> n * 2 end)Enum.map [1, 2, 3], &(&1 * 2) 
Output:
[2, 4, 6]


## Erlang

A list would be more commonly used in Erlang rather than an array.

 1> L = [1,2,3].[1,2,3] 

You can use lists:foreach/2 if you just want to apply the callback to each element of the list.

 2> lists:foreach(fun(X) -> io:format("~w ",[X]) end, L).1 2 3 ok 

Or you can use lists:map/2 if you want to create a new list with the result of the callback on each element.

 3> lists:map(fun(X) -> X + 1 end, L).[2,3,4] 

Or you can use lists:foldl/3 if you want to accumulate the result of the callback on each element into one value.

 4> lists:foldl(fun(X, Sum) -> X + Sum end, 0, L).6 

## ERRE

 PROGRAM CALLBACK !! for rosettacode.org! DIM A[5] FUNCTION CBACK(X)   CBACK=2*X-1END FUNCTION PROCEDURE PROCMAP(ZETA,DUMMY(X)->OUTP)   OUTP=DUMMY(ZETA)END PROCEDURE BEGIN   A[1]=1  A[2]=2   A[3]=3  A[4]=4  A[5]=5   FOR I%=1 TO 5 DO      PROCMAP(A[I%],CBACK(X)->OUTP)      PRINT(OUTP;)   END FOR   PRINTEND PROGRAM 

This example shows how to pass a function to a procedure.

Output:
  1  3  5  7  9


## Euphoria

function apply_to_all(sequence s, integer f)    -- apply a function to all elements of a sequence    sequence result    result = {}    for i = 1 to length(s) do	-- we can call add1() here although it comes later in the program	result = append(result, call_func(f, {s[i]}))    end for    return resultend function function add1(atom x)    return x + 1end function -- add1() is visible here, so we can ask for its routine id? apply_to_all({1, 2, 3}, routine_id("add1"))-- displays {2,3,4}

This is also "Example 2" in the Euphoria documentation for routine_id(). Note that this example will not work for multi-dimensional sequences.

## F#

Apply a named function to each member of the array. The result is a new array of the same size as the input.

let evenp x = x % 2 = 0let result = Array.map evenp [| 1; 2; 3; 4; 5; 6 |]

The same can be done using anonymous functions, this time squaring the members of the input array.

let result = Array.map (fun x -> x * x) [|1; 2; 3; 4; 5|]

Use iter if the applied function does not return a value.

Array.iter (fun x -> printfn "%d" x) [|1; 2; 3; 4; 5|]

## Factor

Print each element squared:

{ 1 2 3 4 } [ sq . ] each

Collect return values:

{ 1 2 3 4 } [ sq ] map

## Fantom

In Fantom, functions can be passed to a collection iterator, such as 'each'. 'map' is used similarly, and the results are collected into a list.

 class Main{  public static Void main ()  {    [1,2,3,4,5].each |Int i| { echo (i) }    Int[] result := [1,2,3,4,5].map |Int i->Int| { return i * i }    echo (result)   }} 
Output:
1
2
3
4
5
[1, 4, 9, 16, 25]


## FBSL

User-defined mapping function:

#APPTYPE CONSOLE FOREACH DIM e IN MyMap(Add42, {1, 2, 3})	PRINT e, " ";NEXT PAUSE FUNCTION MyMap(f, a)	DIM ret[]	FOREACH DIM e IN a		ret[] = f(e)	NEXT	RETURN retEND FUNCTION FUNCTION Add42(n): RETURN n + 42: END FUNCTION
Output:
43 44 45
Press any key to continue...

Standard MAP() function:

#APPTYPE CONSOLE DIM languages[] = {{"English", {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}}, _		  {"French", {"un", "deux", "trois", "quatre", "cinq", "six", "sept", "huit", "neuf", "dix"}}} MAP(SpeakALanguage, languages) PAUSE SUB NameANumber(lang, nb, number)	PRINT "The number ", nb, " is called ", STRENC(number), " in ", langEND SUB SUB SpeakALanguage(lang)	MAP(NameANumber, lang[0], 1 TO 10, lang[1])	PRINT LPAD("", 40, "-")END SUB
Output:
The number 1 is called "one" in English
The number 2 is called "two" in English
The number 3 is called "three" in English
The number 4 is called "four" in English
The number 5 is called "five" in English
The number 6 is called "six" in English
The number 7 is called "seven" in English
The number 8 is called "eight" in English
The number 9 is called "nine" in English
The number 10 is called "ten" in English
----------------------------------------
The number 1 is called "un" in French
The number 2 is called "deux" in French
The number 3 is called "trois" in French
The number 4 is called "quatre" in French
The number 5 is called "cinq" in French
The number 6 is called "six" in French
The number 7 is called "sept" in French
The number 8 is called "huit" in French
The number 9 is called "neuf" in French
The number 10 is called "dix" in French
----------------------------------------
Press any key to continue...

## Forth

This is a word that will call a given function on each cell in an array.

: map ( addr n fn -- )   -rot cells bounds do  i @ over execute i !  cell +loop ;
Example usage:
create data 1 , 2 , 3 , 4 , 5 ,data 5 ' 1+ map  \ adds one to each element of data

## Fortran

Elemental functions.

Works with: Fortran version ISO 95 and later
module arrCallbackcontains    elemental function cube( x )        implicit none        real :: cube        real, intent(in) :: x        cube = x * x * x    end function cubeend module arrCallback
program testAC    use arrCallback    implicit none    integer :: i, j    real, dimension(3,4) :: b, &        a = reshape( (/ ((10 * i + j, i = 1, 3), j = 1, 4) /), (/ 3,4 /) )     do i = 1, 3        write(*,*) a(i,:)    end do     b = cube( a )  ! Applies CUBE to every member of a,                   ! and stores each result in the equivalent element of b    do i = 1, 3        write(*,*) b(i,:)    end doend program testAC
Works with: ANSI FORTRAN version 77 (with MIL-STD-1753 structured DO) and later
      program testCC--   Declare array:      integer a(5)CC--   Fill it with Data      data a /45,22,67,87,98/CC--   Do something with all elements (in this case: print their squares)      do i=1,5        print *,a(i)*a(i)      end doC      end

## FP

{square * . [id, id]}& square: <1,2,3,4,5>

## FreeBASIC

' FB 1.05.0 Win64 Sub PrintEx(n As Integer)  Print n, n * n, n * n * nEnd Sub Sub Proc(a() As Integer, callback As Sub(n As Integer))  For i As Integer = LBound(a) To UBound(a)    callback(i)  NextEnd Sub Dim a(1 To 10) As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}Print " n", "n^2", "n^3"Print " -", "---", "---"Proc(a(), @PrintEx)PrintPrint "Press any key to quit the program"Sleep
Output:
 n            n^2           n^3
-            ---           ---
1             1             1
2             4             8
3             9             27
4             16            64
5             25            125
6             36            216
7             49            343
8             64            512
9             81            729
10            100           1000


## Frink

 f = {|x| x^2}   // Anonymous function to square inputa = [1,2,3,5,7]println[map[f, a]] 

## FunL

[1, 2, 3].foreach( println ) [1, 2, 3].foreach( a -> println(2a) )
Output:
1
2
3
2
4
6


## Futhark

 map f l 

e.g.

 map (\x->x+1) [1,2,3] -- [2,3,4] 

or equivalently

 map (+1) [1,2,3] -- [2,3,4] 

## Fōrmulæ

Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.

Programs in Fōrmulæ are created/edited online in its website, 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.

## GAP

a := [1 .. 4];b := ShallowCopy(a); # Apply and replace valuesApply(a, n -> n*n);a;# [ 1, 4, 9, 16 ] # Apply and don't change valuesList(b, n -> n*n);# [ 1, 4, 9, 16 ] # Apply and don't return anything (only side effects)Perform(b, Display);1234 b;# [ 1 .. 4 ]

## Go

Translation of: Ruby

The task was originally written with a Ruby example, so here are Go versions of the current Ruby examples.

Perhaps in contrast to Ruby, it is idiomatic in Go to use the for statement:

package main import "fmt" func main() {    for _, i := range []int{1, 2, 3, 4, 5} {        fmt.Println(i * i)    }}

Alternatively though, an array-like type can be defined and callback-style methods can be defined on it to apply a function to the elements.

package main import "fmt" type intSlice []int func (s intSlice) each(f func(int)) {    for _, i := range s {        f(i)    }} func (s intSlice) Map(f func(int) int) intSlice {    r := make(intSlice, len(s))    for j, i := range s {        r[j] = f(i)    }    return r} func main() {    s := intSlice{1, 2, 3, 4, 5}     s.each(func(i int) {        fmt.Println(i * i)    })     fmt.Println(s.Map(func(i int) int {        return i * i    }))}
Output:
1
4
9
16
25
[1 4 9 16 25]


## Groovy

Print each value in a list

[1,2,3,4].each { println it }

Create a new list containing the squares of another list

[1,2,3,4].collect { it * it }

### List

Works with: GHC
let square x = x*xlet values = [1..10]map square values

Using list comprehension to generate a list of the squared values

[square x | x <- values]

More directly

[1 .. 10] >>= pure . (^ 2)

Or with one less layer of monadic wrapping

(^ 2) <$> [1..10] Using function composition to create a function that will print the squares of a list let printSquares = mapM_ (print.square)printSquares values ### Array Works with: GHC version 7.10.3 import Data.Array (Array, listArray) square :: Int -> Intsquare x = x * x values :: Array Int Intvalues = listArray (1, 10) [1 .. 10] main :: IO ()main = print$ fmap square values
Output:
array (1,10) [(1,1),(2,4),(3,9),(4,16),(5,25),(6,36),(7,49),(8,64),(9,81),(10,100)]

## Icon and Unicon

procedure main()   local lst   lst := [10, 20, 30, 40]   every callback(write,!lst)end procedure callback(p,arg)   return p(" -> ", arg)end

## IDL

Hard to come up with an example that isn't completely contrived. IDL doesn't really distinguish between a scalar and an array; thus

b = a^3

will yield a scalar if a is scalar or a vector if a is a vector or an n-dimensional array if a is an n-dimensional array

## Io

list(1,2,3,4,5) map(squared)

## J

Solution:

   "_1

Example:

   callback =:  *:   array    =:  1 2 3 4 5    callback"_1 array1 4 9 16 25

But note that this is a trivial example since *: 1 2 3 4 5 would get the same result. Then again, this is something of a trivial exercise in J since all of J is designed around the idea of applying functions usefully to arrays.

## Java

Up to Java 7, you have to define an interface for each type of function you want to use. The IntConsumer performs an action (which doesn't return anything) on an array of ints, while the IntToInt is used to replace the array values.

public class ArrayCallback7 {     interface IntConsumer {        void run(int x);    }     interface IntToInt {        int run(int x);    }     static void forEach(int[] arr, IntConsumer consumer) {        for (int i : arr) {            consumer.run(i);        }    }     static void update(int[] arr, IntToInt mapper) {        for (int i = 0; i < arr.length; i++) {            arr[i] = mapper.run(arr[i]);        }    }     public static void main(String[] args) {        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};         forEach(numbers, new IntConsumer() {            public void run(int x) {                System.out.println(x);            }        });         update(numbers, new IntToInt() {            @Override            public int run(int x) {                return x * x;            }        });         forEach(numbers, new IntConsumer() {            public void run(int x) {                System.out.println(x);            }        });    }}

Using Java 8 streams:

Works with: Java version 8
import java.util.Arrays; public class ArrayCallback {     public static void main(String[] args) {        int[] myIntArray = {1, 2, 3, 4, 5};         int sum = Arrays.stream(myIntArray)                .map(x -> {                    int cube = x * x * x;                    System.out.println(cube);                    return cube;                })                .reduce(0, (left, right) -> left + right); // <-- could substitute .sum() for .reduce(...) here.        System.out.println("sum: " + sum);    }}

## JavaScript

### ES3

function map(a, func) {  var ret = [];  for (var i = 0; i < a.length; i++) {    ret[i] = func(a[i]);  }  return ret;} map([1, 2, 3, 4, 5], function(v) { return v * v; });

### ES5

[1, 2, 3, 4, 5].map(function(v) { return v * v; });

### ES6

[1, 2, 3, 4, 5].map(v => v * v);

The result is always:

[1, 4, 9, 16, 25]

## Joy

[1 2 3 4 5] [dup *] map.

## jq

# Illustration of map/1 using the builtin filter: expmap(exp)  # exponentiate each item in the input list # A compound expression can be specified as the argument to map, e.g.map( (. * .) + sqrt ) # x*x + sqrt(x) # The compound expression can also be a composition of filters, e.g.map( sqrt|floor )     # the floor of the sqrt # Array comprehensionreduce .[] as $n ([]; . + [ exp ]) # Elementwise operation [.[] + 1 ] # add 1 to each element of the input array  Here is a transcript illustrating how the last of these jq expressions can be evaluated: $ jq -c ' [.[] + 1 ]'[0, 1 , 10][1,2,11]

## Jsish

/* Apply callback, in Jsish using array.map() */;[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; }); /*=!EXPECTSTART!=[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; }) ==> [ 1, 4, 9, 16, 25 ]=!EXPECTEND!=*/
Output:

## Raven

# To print the squared elements[1 2 3 4 5] each dup * print
# To obtain a new arraygroup [1 2 3 4 5] each  dup *list

## REBOL

rebol [    Title: "Array Callback"    URL: http://rosettacode.org/wiki/Apply_a_callback_to_an_Array] map: func [	"Apply a function across an array."	f [native! function!] "Function to apply to each element of array."	a [block!] "Array to process."	/local x][x: copy []  forall a [append x do [f a/1]]  x] square: func [x][x * x] ; Tests: assert: func [code][print [either do code ["  ok"]["FAIL"]  mold code]] print "Simple loop, modify in place:"assert [[1 100 81] = (a: [1 10 9]  forall a [a/1: square a/1]  a)] print [crlf "Functional style with 'map':"]assert [[4 16 36] = map :square [2 4 6]] print [crlf "Applying native function with 'map':"]assert [[2 4 6] = map :square-root [4 16 36]]
Output:
Simple loop, modify in place:
ok [[1 100 81] = (a: [1 100 81] forall a [a/1: square a/1] a)]

Functional style with 'map':
ok [[4 16 36] = map :square [2 4 6]]

Applying native function with 'map':
ok [[2 4 6] = map :square-root [4 16 36]]

## Retro

Retro provides a variety of array words. Using these to multiply each value in an array by 10 and display the results:

{ #1 #2 #3 #4 #5 } [ #10 * ] a:map [ n:put sp ] a:for-each

/*REXX program applies a  callback  to an array  (using factorials for a demonstration).*/numeric digits 100                               /*be able to display some huge numbers.*/parse arg # .                                    /*obtain an optional value from the CL.*/a.=                                              /*initialize the array  A  to all nulls*/if #=='' | #==","  then #= 12                    /*Not assigned?  Then use default value*/                        do j=0  to #;   a.j= j   /*assign the integer   J  ───►   A.j   */                        end   /*j*/              /*array  A  will have N values: 0 ──► #*/ call listA   'before callback'                   /*display  A  array before the callback*/say                                              /*display a blank line for readability.*/say '      ··· applying callback to array A ···' /*display what is about to happen to B.*/say                                              /*display a blank line for readability.*/call bangit  'a'                                 /*factorialize (the values) of A array.*/                                                 /*    store the results  ───►  array B.*/call listA   ' after callback'                   /*display  A  array after the callback.*/exit 0                                           /*stick a fork in it,  we're all done. *//*──────────────────────────────────────────────────────────────────────────────────────*/bangit:   do v=0;  $= value(arg(1)'.'v); if$=='' then return  /*No value?  Then return*/          call value arg(1)'.'v, fact($) /*assign a value (a factorial) to array*/ end /*i*//*──────────────────────────────────────────────────────────────────────────────────────*/fact: procedure; arg x; != 1; do f=2 to x; != !*f; end; /*f*/; return !listA: do k=0 while a.k\==''; say arg(1) 'a.'k"=" a.k; end /*k*/; return output when using the default input: before callback a.0= 0 before callback a.1= 1 before callback a.2= 2 before callback a.3= 3 before callback a.4= 4 before callback a.5= 5 before callback a.6= 6 before callback a.7= 7 before callback a.8= 8 before callback a.9= 9 before callback a.10= 10 before callback a.11= 11 before callback a.12= 12 ··· applying callback to array A ··· after callback a.0= 1 after callback a.1= 1 after callback a.2= 2 after callback a.3= 6 after callback a.4= 24 after callback a.5= 120 after callback a.6= 720 after callback a.7= 5040 after callback a.8= 40320 after callback a.9= 362880 after callback a.10= 3628800 after callback a.11= 39916800 after callback a.12= 479001600  ## Ring  for x in [1,2,3,4,5] x = x*xnext  ## RLaB RLaB has two type of arrays: 'standard' or 1-dimensional, that can be a row- or a column-vectory; and, 'associative' which are called lists. For standard array its entry identifier (index) is an integer in range 1:N where N is the size of the array. For associative array its entry identifier is a string consisting of printable ASCII characters. All scalar mathematical functions are 'matrix-optimized' meaning that if the argument to a function is a matrix, then the return value of the function is a matrix of the same size as the input argument, where the function is applied to the individual entries of the matrix. Consider an example:  >> x = rand(2,4) 0.707213207 0.275298961 0.396757763 0.232312312 0.215619868 0.207078017 0.565700032 0.666090571>> sin(x) 0.649717845 0.271834652 0.386430003 0.230228332 0.213952984 0.205601224 0.536006923 0.617916954  This can be done on entry-by-entry basis, but one has to keep in mind that the 'for' or 'while' loops are slow in interpreted languages, and RLaB is no exception.  x = rand(2,4);y = zeros(2,4);for (i in 1:2){ for (j in 1:4) { y[i;j] = sin( x[i;j] ); }}  The functions can take lists as arguments, but then it has to be specified within the body of the function what to do with the list elements. Given a list call it 'x' there is a RLaB function 'members' which returns a string vector with the names of the elements of the list.  x = <<>>;for (i in 1:9){ x.[i] = rand();} y = <<>>;for (i in members(x)){ y.[i] = sin( x.[i] );}  ## Ruby You could use a traditional "for i in arr" approach like below: for i in [1,2,3,4,5] do puts i**2end Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk) [1,2,3,4,5].each{ |i| puts i**2 } To create a new array of each value squared [1,2,3,4,5].map{ |i| i**2 } ## Rust fn echo(n: &i32) { println!("{}", n);} fn main() { let a: [i32; 5]; a = [1, 2, 3, 4, 5]; let _: Vec<_> = a.into_iter().map(echo).collect();} ## Salmon These examples apply the square function to a list of the numbers from 0 through 9 to produce a new list of their squares, then iterate over the resulting list and print the squares. function apply(list, ageless to_apply) (comprehend(x; list) (to_apply(x))); function square(x) (x*x); iterate(x; apply([0...9], square)) x!; With short identifiers: include "short.salm"; fun apply(list, ageless to_apply) (comp(x; list) (to_apply(x))); fun square(x) (x*x); iter(x; apply([0...9], square)) x!; With the numbers given as a list of individual elements: function apply(list, to_apply) (comprehend(x; list) (to_apply(x))); function square(x) (x*x); iterate(x; apply([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], square)) x!; ## Sather class MAIN is do_something(i:INT):INT is return i * i; end; main is a:ARRAY{INT} := |1, 2, 3, 4, 5|; -- we use an anonymous closure to apply our do_something "callback" a.map(bind(do_something(_))); loop #OUT + a.elt! + "\n"; end; end;end; ## Scala val l = List(1,2,3,4)l.foreach {i => println(i)} When the argument appears only once -as here, i appears only one in println(i) - it may be shortened to l.foreach(println(_)) Same for an array val a = Array(1,2,3,4)a.foreach {i => println(i)}a.foreach(println(_)) '' // same as previous line'' Or for an externally defined function: def doSomething(in: int) = {println("Doing something with "+in)}l.foreach(doSomething) There is also a for syntax, which is internally rewritten to call foreach. A foreach method must be defined on a for(val i <- a) println(i) It is also possible to apply a function on each item of an list to get a new list (same on array and most collections) val squares = l.map{i => i * i} ''//squares is'' List(1,4,9,16) Or the equivalent for syntax, with the additional keyword yield, map is called instead of foreach val squares = for (val i <- l) yield i * i ## Scheme (define (square n) (* n n))(define x #(1 2 3 4 5))(map square (vector->list x)) A single-line variation (map (lambda (n) (* n n)) '(1 2 3 4 5)) For completeness, the map function (which is R5RS standard) can be coded as follows: (define (map f L) (if (null? L) L (cons (f (car L)) (map f (cdr L))))) ## SenseTalk  put each item in [1,2,3,5,9,14,24] squared put myFunc of each for each item of [1,2,3,5,9,14,24] to handle myFunc of num return 2*num + 1end myFunc Output: (1,4,9,25,81,196,576)(3,5,7,11,19,29,49) ## Sidef Defining a callback function: func callback(i) { say i**2 } The function will get called for each element: [1,2,3,4].each(callback) Same as above, but with the function inlined: [1,2,3,4].each{|i| say i**2 } For creating a new array, we can use the Array.map method: [1,2,3,4,5].map{|i| i**2 } ## Simula BEGIN ! APPLIES A CALLBACK FUNCTION TO AN ARRAY ; PROCEDURE APPLY(ARR, FUN); REAL ARRAY ARR; PROCEDURE FUN IS REAL PROCEDURE FUN(X); REAL X;; BEGIN INTEGER I; FOR I := LOWERBOUND(ARR, 1) STEP 1 UNTIL UPPERBOUND(ARR, 1) DO ARR(I) := FUN(ARR(I)); END APPLY; ! CALLBACK ; REAL PROCEDURE SQUARE(X); REAL X; SQUARE := X * X; REAL ARRAY A(1:5); INTEGER I; FOR I := 1 STEP 1 UNTIL 5 DO A(I) := I; APPLY(A, SQUARE); FOR I := 1 STEP 1 UNTIL 5 DO OUTFIX(A(I), 2, 8); OUTIMAGE; END. Output:  1.00 4.00 9.00 16.00 25.00  ## Slate #( 1 2 3 4 5 ) collect: [| :n | n * n]. ## Smalltalk #( 1 2.0 'three') do: [:each | each displayNl]. You can tell symbols how to react to the value: message, and then write ²: #( 1 2.0 'three') do: #displayNl. 2) actually most dialects already have it, and it is trivial to add, if it does not. There is a huge number of additional enumeration messages implemented in Collection, from which Array inherits. Eg.: #( 1 2 3 4 5 ) collect: [:n | n * n]. ## Sparkling The foreach function calls the supplied callback on each element of the (possibly associative) array, passing it each key and the corresponding value: let numbers = { 1, 2, 3, 4 };foreach(numbers, function(idx, num) { print(num);}); The map function applies the transform to each key-value pair and constructs a new array, of which the keys are the keys of the original array, and the corresponding values are the return values of each call to the transform function: let dict = { "foo": 42, "bar": 13, "baz": 37 };let doubled = map(dict, function(key, val) { return val * 2;}); ## SQL PL Works with: Db2 LUW version 9.7 or higher. With SQL PL:  --#SET TERMINATOR @ SET SERVEROUTPUT ON @ BEGIN DECLARE TYPE NUMBERS AS SMALLINT ARRAY[5]; DECLARE NUMBERS NUMBERS; DECLARE I SMALLINT; SET I = 1; WHILE (I <= 5) DO SET NUMBERS[I] = I; SET I = I + 1; END WHILE; BEGIN DECLARE PROCEDURE PRINT_SQUARE ( IN VALUE SMALLINT ) BEGIN CALL DBMS_OUTPUT.PUT(VALUE * VALUE || ' '); END; SET I = 1; WHILE (I <= 5) DO CALL PRINT_SQUARE(NUMBERS[I]); SET I = I + 1; END WHILE; CALL DBMS_OUTPUT.PUT_LINE(''); END;END @  Output: db2 [email protected] db2 => BEGIN ... db2 (cont.) => END @ DB20000I The SQL command completed successfully. 1 4 9 16 25  ## Standard ML  map f l  i.e.  map (fn x=>x+1) [1,2,3];; (* [2,3,4] *)  ## Stata There is no 'map' function in Mata, but it's easy to implement. Notice that you can only pass functions that are written in Mata, no builtin ones. For instance, the trigonometric functions (cos, sin) or the exponential are builtin. To pass a builtin function to another function, one needs to write a wrapper in Mata. See also Stata help about pointers and passing functions to functions. There are two versions of the function: one to return a numeric array, another to return a string array. function map(f,a) { nr = rows(a) nc = cols(a) b = J(nr,nc,.) for (i=1;i<=nr;i++) { for (j=1;j<=nc;j++) b[i,j] = (*f)(a[i,j]) } return(b)} function maps(f,a) { nr = rows(a) nc = cols(a) b = J(nr,nc,"") for (i=1;i<=nr;i++) { for (j=1;j<=nc;j++) b[i,j] = (*f)(a[i,j]) } return(b)} function square(x) { return(x*x)} Output : map(&square(),(1,2,3\4,5,6)) 1 2 3 +----------------+ 1 | 1 4 9 | 2 | 16 25 36 | +----------------+ ## SuperCollider Actually, there is a builtin squared operator: [1, 2, 3].squared // returns [1, 4, 9] Anything that is a Collection can be used with collect: [1, 2, 3].collect { |x| x * x } List comprehension combined with a higher-order function can also be used: var square = { |x| x * x };var map = { |fn, xs| all {: fn.value(x), x <- xs };};map.value(square, [1, 2, 3]); ## Swift func square(n: Int) -> Int { return n * n} let numbers = [1, 3, 5, 7] let squares1a = numbers.map(square) // map method on array let squares1b = numbers.map {x in x*x} // map method on array with anonymous function let squares1b = numbers.map {$0 * $0 } // map method on array with anonymous function and unnamed parameters let isquares1 = numbers.lazy.map(square) // lazy sequence ## Tailspin  def numbers: [1,3,7,10]; templates cube$ * $*$ !end cube // Using inline array templates (which also allows access to index by $i)$numbers -> \[i]($*$i !\) -> !OUT::write$numbers -> \[i]($ * $!\) -> !OUT::write$numbers -> \[i]($-> cube !\) -> !OUT::write // Using array literal and deconstructor[$numbers... -> $*$ ] -> !OUT::write[ $numbers... -> cube ] -> !OUT::write  ## Tcl If I wanted to call "myfunc" on each element of dat and dat were a list: foreach var$dat {    myfunc $var} This does not retain any of the values returned by myfunc. if dat were an (associative) array, however: foreach name [array names dat] { myfunc$dat($name)} More functional, with a simple map function: proc map {f list} { set res {} foreach e$list {lappend res [$f$e]}   return $res}proc square x {expr {$x*$x}} % map square {1 2 3 4 5}1 4 9 16 25 ## TI-89 BASIC © For no return valueDefine foreach(fe_cname,fe_list) = Prgm Local fe_i For fe_i,1,dim(fe_list) #fe_cname(fe_list[fe_i]) EndForEndPrgm © For a list of resultsDefine map(map_cnam,map_list) = seq(#map_cnam(map_list[map_i]),map_i,1,dim(map_list)) Define callback(elem) = Prgm Disp elemEndPrgm foreach("callback", {1,2,3,4,5})Disp map("√", {1,2,3,4,5}) Output: ${\displaystyle 1}$ ${\displaystyle 2}$ ${\displaystyle 3}$ ${\displaystyle 4}$ ${\displaystyle 5}$ ${\displaystyle {\begin{Bmatrix}1&{\sqrt {2}}&{\sqrt {3}}&2&{\sqrt {5}}\end{Bmatrix}}}$ ## TIScript JavaScript alike: var a = [1, 2, 3, 4, 5];a.map(function(v) { return v * v; })  Using short form of lambda notation: var a = [1, 2, 3, 4, 5];a.map( :v: v*v );  ## Toka ( array count function -- ){ value| array fn | [ i array ] is I [ to fn swap to array 0 swap [ I array.get :stack fn invoke I array.put ] countedLoop ]} is map-array ( Build an array )5 cells is-array a10 0 a array.put11 1 a array.put12 2 a array.put13 3 a array.put14 4 a array.put ( Add 1 to each item in the array )a 5 [ 1 + ] map-array ## TorqueScript --Elm 03:41, 18 June 2012 (UTC) Callbacks:  function map(%array,%arrayCount,%function){ for(%i=0;%i<%arrayCount;%i++) { eval("%a = "@%[email protected]"["@%[email protected]"];"); eval(""@%[email protected]"("@%[email protected]");"); }}  Now to set up an array: $array[0] = "Hello.";$array[1] = "Hi.";$array[2] = "How are you?";

Now to call the function correctly:

 map("$array",3,"echo");  Which should result in:  => Hello. => Hi. => How are you?  ## TXR Print 1 through 10 out of a vector, using prinl the callback, right from the system shell command prompt: $ txr -e '[mapdo prinl #(1 2 3 4 5 6 7 8 9 10)]'12345678910

mapdo is like mapcar but doesn't accumulate a list, suitable for imperative programming situations when the function is invoked to perform a side effect.

TXR extends Lisp list processing primitives to work with vectors and strings also, which is why mapdo cheerfully traverses a vector.

## uBasic/4tH

We cannot transfer the array address, since uBasic/4tH has only got one, but we can transfer the function pointer and size.

S = 5                                  ' Size of the array For x = 0 To S - 1                     ' Initialize array  @(x) = x + 1Next Proc _MapArray (_SquareRoot, S)        ' Call mapping procedure For x = 0 To S - 1                     ' Print results  Print "SQRT(";x+1;") = ";Using "#.####";@(x)Next For x = 0 To S - 1                     ' Reinitialize array  @(x) = x + 1Next Proc _MapArray (_Cosine, S)            ' Call mapping procedure Print : For x = 0 To S - 1             ' Print results  Print "COS(";x+1;") = ";Using "#.####";@(x)Next End  _MapArray Param(2)                     ' Param(1) = function  Local (1)                            ' Param(2) = array size   For [email protected] = 0 To [email protected] - 1    @([email protected]) = FUNC([email protected](@([email protected])))  NextReturn  _SquareRoot Param (1)                  ' This is an integer SQR subroutine  Local (2)   [email protected] = (10^(4*2)) * [email protected]                 ' Output is scaled by 10^4  [email protected] = [email protected]   Do    [email protected] = ([email protected] + ([email protected] / [email protected]))/2  Until (Abs([email protected] - [email protected]) < 2)    [email protected] = [email protected]  Loop Return ([email protected])  _Cosine Param(1)                       ' This is an integer COS subroutine  Push Abs(([email protected]*10000)%62832)           ' Output is scaled by 10^4  If Tos()>31416 Then Push 62832-Pop()  Let [email protected]=Tos()>15708  If [email protected] Then Push 31416-Pop()  Push Tos()  Push (Pop()*Pop())/10000  Push 10000+((10000*-(Tos()/56))/10000)  Push 10000+((Pop()*-(Tos()/30))/10000)  Push 10000+((Pop()*-(Tos()/12))/10000)  Push 10000+((Pop()*-(Pop()/2))/10000)  If [email protected] Then Push -Pop()               ' Result is directly transferredReturn                                 ' through the stack
Output:
SQRT(1) = 1.0000
SQRT(2) = 1.4142
SQRT(3) = 1.7320
SQRT(4) = 2.0000
SQRT(5) = 2.2360

COS(1) = 0.5403
COS(2) = -0.4162
COS(3) = -0.9901
COS(4) = -0.6537
COS(5) = 0.2837

0 OK, 0:514

## UNIX Shell

Works with: Bourne Shell
map() {	map_command=$1 shift for i do "$map_command" "$i"; done}list=1:2:3(IFS=:; map echo$list)
Works with: ksh93
Works with: pdksh
Works with: zsh
map() {	typeset command=$1 shift for i do "$command" "$i"; done}set -A ary 1 2 3map print "${ary[@]}"
Works with: zsh
map(){for i ($*[2,-1])$1 $i}a=(1 2 3)map print$a

## Ursala

The * is a built-in map operator. This example shows a map of the successor function over a list of natural numbers.

#import nat #cast %nL demo = successor* <325,32,67,1,3,7,315>
Output:
<326,33,68,2,4,8,316>


## V

apply squaring (dup *) to each member of collection

[1 2 3 4] [dup *] map

## VBA

 Option Explicit Sub Main()Dim arr, i    'init    arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)     'Loop and apply a function (Fibonacci) to each element    For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next     'return    Debug.Print Join(arr, ", ")End Sub Private Function Fibonacci(N) As Variant    If N <= 1 Then        Fibonacci = N    Else        Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)    End IfEnd Function
Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55

## VBScript

I really have my doubts as to whether this really counts as a callback. I used the same thing in the solution to Amb.

##### Implementation
 class callback	dim sRule 	public property let rule( x )		sRule = x	end property 	public default function applyTo(a)		dim p1		for i = lbound( a ) to ubound( a )			p1 = a( i )			a( i ) = eval( sRule )		next		applyTo = a	end functionend class
##### Invocation
 dim a1dim cbset cb = new callback cb.rule = "ucase(p1)"a1 = split("my dog has fleas", " " )cb.applyTo a1wscript.echo join( a1, " " ) cb.rule = "p1 ^ p1"a1 = array(1,2,3,4,5,6,7,8,9,10)cb.applyto a1wscript.echo join( a1, ", " )
Output:
MY DOG HAS FLEAS
1, 4, 27, 256, 3125, 46656, 823543, 16777216, 387420489, 10000000000


## Vim Script

map() works with lists and dictionaries. The second argument is an expression string where v:val is replaced by the current value and v:key by the current key (for lists the key is the index). The result of evaluating the string will be the new value. The list/dictionary is modified in place.

echo map([10, 20, 30], 'v:val * v:val')echo map([10, 20, 30], '"Element " . v:key . " = " . v:val')echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:val)')echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:key)')
Output:
[100, 400, 900]
['Element 0 = 10', 'Element 1 = 20', 'Element 2 = 30']
{'a': 'FOO', 'b': 'BAR', 'c': 'BAZ'}
{'a': 'A', 'b': 'B', 'c': 'C'}

## Visual Basic .NET

Compiler: >= Visual Studio 2008

The .NET framework has got us covered.

System.Array.ForEach(T(), Action(Of T)) maps a non-value-returning callback,

System.Linq.Enumerable.Select(Of TSource,TResult)(IEnumerable(Of TSource), Func(Of TSource, TResult)) provides a way to lazily map a function, resulting in an IEnumerable(Of T),

and System.Linq.Enumerable.ToArray(Of TSource)(IEnumerable(Of TSource)) eagerly converts the enumerable to an array.

Module Program    Function OneMoreThan(i As Integer) As Integer        Return i + 1    End Function     Sub Main()        Dim source As Integer() = {1, 2, 3}         ' Create a delegate from an existing method.        Dim resultEnumerable1 = source.Select(AddressOf OneMoreThan)         ' The above is just syntax sugar for this; extension methods can be called as if they were instance methods of the first parameter.        resultEnumerable1 = Enumerable.Select(source, AddressOf OneMoreThan)         ' Or use an anonymous delegate.        Dim resultEnumerable2 = source.Select(Function(i) i + 1)         ' The sequences are the same.         Console.WriteLine(Enumerable.SequenceEqual(resultEnumerable1, resultEnumerable2))         Dim resultArr As Integer() = resultEnumerable1.ToArray()         Array.ForEach(resultArr, AddressOf Console.WriteLine)    End SubEnd Module
Output:
True
2
3
4

## Vorpal

Given and array, A, and a function, F, mapping F over the elements of A is simple:

A.map(F)

If F takes 2 arguments, x and , then simply pass them to map. They will be passed to F when as it is applied to each element of A.

A.map(F, x, y)

## Wart

map prn '(1 2 3 4 5)
Output:
1
2
3
4
5

## WDTE

let a => import 'arrays';let s => import 'stream'; let example => [3; 5; 2]; let double => a.stream example-> s.map (* 2)-> s.collect;

In WDTE, mapping can be accomplished using the stream module. Streams are essentially lazy iterators. The arrays module provides a function for creating a stream from an array, and then the stream module's functions can be used to perform a map operation. collect runs the iteration, collecting the elements yielded in a new array.

## Wren

var arr = [1, 2, 3, 4, 5]arr = arr.map { |x| x * 2 }.toListarr = arr.map(Fn.new { |x| x / 2 }).toListarr.each { |x| System.print(x) }
Output:
1
2
3
4
5


## XBS

func map(arr:array,callback:function){	set newArr:array = [];	foreach(k,v as arr){		newArr:[k]=callback(v,k,arr);	}	send newArr;} set arr:array = [1,2,3,4,5];set result:array = map(arr,func(v){	send v*2;}); log(arr::join(", "));log(result::join(", "));
Output:
1, 2, 3, 4, 5
2, 4, 6, 8, 10


## Yabasic

sub map(f$, t()) local i for i = 1 to arraysize(t(), 1) t(i) = execute(f$, t(i))    next iend sub sub add1(x)    return x + 1end sub sub square(x)    return x * xend sub dim t(10) for i = 1 to 10    t(i) = i    print t(i), "\t";next iprint //map("add1", t())map("square", t()) for i = 1 to 10    print t(i), "\t";next iprint

## Yacas

Sin /@ {1, 2, 3, 4} MapSingle(Sin, {1,2,3,4}) MapSingle({{x}, x^2}, {1,2,3,4})

## Z80 Assembly

Array:byte &01,&02,&03,&04,&05Array_End: foo:ld hl,Arrayld b,Array_End-Array ;ld b,5 bar:inc (hl)inc (hl)inc (hl)inc hl     ;next entry in arraydjnz bar
Output:

The program above doesn't show the new values but here they are:

&04,&05,&06,&07,&08


## zkl

L(1,2,3,4,5).apply('+(5))
Output:
L(6,7,8,9,10)


## zonnon

 module Main;type	Callback = procedure (integer): integer;	Vector = array {math} * of integer; procedure Power(i:integer):integer;begin	return i*i;end Power; procedure Map(x: Vector;p: Callback): Vector;var	i: integer;	r: Vector;begin	r := new Vector(len(x));	for i := 0 to len(x) - 1 do			r[i] := p(i);	end;	return rend Map; procedure Write(x: Vector);var	i: integer;begin	for i := 0 to len(x) - 1 do		write(x[i]:4)	end;	writelnend Write; var	x,y: Vector; begin	x := [1,2,3,4,5];	Write(Map(x,Power))end Main.
Output:
   0   1   4   9  16


## ZX Spectrum Basic

10 LET a$="x+x"20 LET b$="x*x"30 LET c$="x+x^2"40 LET f$=c$: REM Assign a$, b$or c$150 FOR i=1 TO 5160 READ x170 PRINT x;" = ";VAL f\$180 NEXT i190 STOP 200 DATA 2,5,6,10,100