Apply a callback to an array: Difference between revisions
jq |
No edit summary |
||
Line 2,250: | Line 2,250: | ||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
<lang smalltalk>#( 1 2 3 4 5 ) collect: [:n | n * n].</lang> |
<lang smalltalk>#( 1 2 3 4 5 ) collect: [:n | n * n].</lang> |
||
=={{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: |
|||
<lang sparkling>let numbers = { 1, 2, 3, 4 }; |
|||
foreach(numbers, function(idx, num) { |
|||
print(num); |
|||
});</lang> |
|||
The <tt>map</tt> function applies the transform to each key-value pair and constructs a new array, of which the keys are the keys of the original array, and the corresponding values are the return values of each call to the transform function: |
|||
<lang sparkling>let dict = { "foo": 42, "bar": 13, "baz": 37 }; |
|||
let doubled = map(dict, function(key, val) { |
|||
return val * 2; |
|||
});</lang> |
|||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
Revision as of 15:42, 28 July 2014
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
In this task, the goal is to take a combined set of elements and apply a function to each element.
ACL2
ACL2 does not have first-class functions; this is close, however:
<lang lisp>(defun sq-each (xs)
(if (endp xs) nil (cons (* (first xs) (first xs)) (sq-each (rest xs)))))</lang>
ActionScript
<lang 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); } }
}</lang>
Ada
<lang ada>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;</lang>
Aime
<lang aime>void map(list l, void (*fp) (object)) {
integer i;
i = 0; while (i < l_length(l)) {
fp(l_query(l, i)); i += 1;
}
}
void
out(object o)
{
o_integer(o); o_byte(10);
}
integer
main(void)
{
list l;
l_append(l, 0); l_append(l, 1); l_append(l, 2); l_append(l, 3);
map(l, out);
return 0;
}</lang>
ALGOL 68
<lang algol68> 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) )</lang>
Output:
array[ +1] = +1 array[ +2] = +4 array[ +3] = +9 array[ +4] = +16
AppleScript
<lang 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</lang>
If the callback would set arg's contents to "something"
, then alist
would be mutated.
AutoHotkey
<lang AutoHotkey>map("callback", "3,4,5")
callback(array){
Loop, Parse, array, `, MsgBox % (2 * A_LoopField)
}
map(callback, array){
%callback%(array)
}</lang>
AWK
<lang awk>$ awk 'func psqr(x){print x,x*x}BEGIN{split("1 2 3 4 5",a);for(i in a)psqr(a[i])}' 4 16 5 25 1 1 2 4 3 9</lang>
Babel
We can alter the list in place:
<lang babel>((main
{ (1 1 2 3 5 8 13 21) dup {double !} each {%d ' ' . <<} each})
(double { dup 2 * set }))</lang>
Or, we can leave the original list unmodified:
<lang babel>((main
{ (1 1 2 3 5 8 13 21) {double !} each collect ! {%d ' ' . <<} each})
(double { 2 * })
(collect { -1 take }))</lang>
Both versions produce the same output:
<lang babel>2 2 4 6 10 16 26 42 </lang>
Because lists and arrays are distinct in Babel, we can also do a similar procedure over an array, with the same results as above:
<lang babel>((main
{ [val 1 1 2 3 5 8 13 21] {double !} eachar collect ! {%d ' ' . <<} each})
(double { 2 * })
(collect { -1 take }))</lang>
BBC BASIC
<lang bbcbasic> 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
</lang> Produces this output:
1 1.41421356 1.73205081 2 2.23606798
Bracmat
<lang bracmat>( ( callbackFunction1
= location value . !arg:(?location,?value) & out$(str$(array[ !location "] = " !!value)) )
& ( callbackFunction2
= location value . !arg:(?location,?value) & !!value^2:?!value )
& ( map
= 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) & map$(array,4,callbackFunction1) & map$(array,4,callbackFunction2) & map$(array,4,callbackFunction1) );</lang> 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
<lang brat>#Print out each element in array [:a :b :c :d :e].each { element | p element }</lang>
Alternatively:
<lang brat>[:a :b :c :d :e].each ->p</lang>
C
callback.h <lang c>#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</lang>
callback.c <lang 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;
}</lang>
Output
array[0] = 1 array[1] = 2 array[2] = 3 array[3] = 4
C#
<lang csharp>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); }
}</lang>
This version uses the C# 3 lambda notation.
<lang csharp>int[] intArray = { 1, 2, 3, 4, 5 }; Array.ForEach(intArray, i => Console.WriteLine(i * i));</lang>
C++
C-Style Array
<lang cpp>#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</lang>
std::vector
<lang cpp>#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</lang>
More tricky with binary function <lang cpp>#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</lang>
Boost.Lambda
<lang cpp>using namespace std; using namespace boost::lambda; vector<int> ary(10); int i = 0; for_each(ary.begin(), ary.end(), _1 = ++var(i)); // init array transform(ary.begin(), ary.end(), ostream_iterator<int>(cout, " "), _1 * _1); // square and output</lang>
C++11
<lang cpp>#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;
}</lang>
Clean
Define a function and an initial (unboxed) array.
<lang clean>square x = x * x
values :: {#Int} values = {x \\ x <- [1 .. 10]}</lang>
One can easily define a map for arrays, which is overloaded and works for all kinds of arrays (lazy, strict, unboxed).
<lang clean>mapArray f array = {f x \\ x <-: array}</lang>
Apply the function to the initial array (using a comprehension) and print result.
<lang clean>Start :: {#Int} Start = mapArray square values</lang>
Clojure
<lang lisp>;; apply a named function, inc (map inc [1 2 3 4])</lang>
<lang lisp>;; apply a function (map (fn [x] (* x x)) [1 2 3 4])</lang>
<lang lisp>;; shortcut syntax for a function (map #(* % %) [1 2 3 4])</lang>
COBOL
Basic implementation of a map function: <lang cobol> 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 .</lang>
CoffeeScript
<lang coffeescript> map = (arr, f) -> (f(e) for e in arr) arr = [1, 2, 3, 4, 5] f = (x) -> x * x console.log map arr, f # prints [1, 4, 9, 16, 25] </lang>
Common Lisp
Imperative: print 1, 2, 3, 4 and 5:
<lang lisp>(map nil #'print #(1 2 3 4 5))</lang>
Functional: collect squares into new vector that is returned:
<lang lisp>(defun square (x) (* x x)) (map 'vector #'square #(1 2 3 4 5))</lang>
Destructive, like the Javascript example; add 1 to every slot of vector *a*:
<lang lisp>(defvar *a* (vector 1 2 3)) (map-into *a* #'1+ *a*)</lang>
Component Pascal
BlackBox Component Builder <lang oberon2> 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.
</lang>
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
D
<lang d>import std.stdio, std.algorithm;
void main() {
auto items = [1, 2, 3, 4, 5]; auto m = items.map!(x => x + 5)(); writeln(m);
}</lang>
- Output:
[6, 7, 8, 9, 10]
Delphi
<lang Delphi> // Declare the callback function procedure 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. </lang>
Déjà Vu
There is a map
builtin that does just this.
<lang dejavu>!. map @++ [ 1 4 8 ]
- implemented roughly like this:
- map f lst:
- ]
- for i in lst:
- f i
- [</lang>
- Output:
[ 2 5 9 ]
E
<lang e>def array := [1,2,3,4,5] def square(value) {
return value * value
}</lang>
Example of builtin iteration:
<lang e>def callback(index, value) {
println(`Item $index is $value.`)
} array.iterate(callback)</lang>
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).
<lang e>def map(func, collection) {
def output := [].diverge() for item in collection { output.push(func(item)) } return output.snapshot()
} println(map(square, array))</lang>
Efene
<lang efene>square = fn (N) {
N * N
}
- list comprehension
squares1 = fn (Numbers) {
[square(N) for N in Numbers]
}
- functional form
squares2a = fn (Numbers) {
lists.map(fn square:1, Numbers)
}
- functional form with lambda
squares2b = fn (Numbers) {
lists.map(fn (N) { N * N }, Numbers)
}
- no need for a function
squares3 = fn (Numbers) {
[N * N for N in Numbers]
}
@public run = 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)])
} </lang>
EGL
<lang 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 ); end end</lang>
Elena
<lang elena>#define system.
- symbol PrintSecondPower =
(:n) [ console writeLine:(n * n) ].
- symbol program =
[
#var anArray := (1, 2, 3, 4, 5, 6, 7, 8, 9, 10). control foreach:anArray &do:PrintSecondPower.
].</lang>
Erlang
A list would be more commonly used in Erlang rather than an array.
<lang Erlang> 1> L = [1,2,3]. [1,2,3] </lang>
You can use lists:foreach/2 if you just want to apply the callback to each element of the list.
<lang> 2> lists:foreach(fun(X) -> io:format("~w ",[X]) end, L). 1 2 3 ok </lang>
Or you can use lists:map/2 if you want to create a new list with the result of the callback on each element.
<lang Erlang> 3> lists:map(fun(X) -> X + 1 end, L). [2,3,4] </lang>
Or you can use lists:foldl/3 if you want to accumulate the result of the callback on each element into one value.
<lang Erlang> 4> lists:foldl(fun(X, Sum) -> X + Sum end, 0, L). 6 </lang>
Euphoria
<lang 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 result
end function
function add1(atom x)
return x + 1
end 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}</lang>
This is also "Example 2" in the Euphoria documentation for routine_id()
.
Note that this example will not work for multi-dimensional sequences.
Factor
Print each element squared: <lang factor>{ 1 2 3 4 } [ sq . ] each</lang>
Collect return values: <lang factor>{ 1 2 3 4 } [ sq ] map</lang>
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.
<lang fantom> 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) }
} </lang>
Output:
1 2 3 4 5 [1, 4, 9, 16, 25]
FBSL
User-defined mapping function: <lang qbasic>#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 ret END FUNCTION
FUNCTION Add42(n): RETURN n + 42: END FUNCTION</lang> Output:
43 44 45 Press any key to continue...
Standard MAP() function: <lang qbasic>#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 ", lang END SUB
SUB SpeakALanguage(lang) MAP(NameANumber, lang[0], 1 TO 10, lang[1]) PRINT LPAD("", 40, "-") END SUB</lang> 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.
<lang forth>: map ( addr n fn -- )
-rot cells bounds do i @ over execute i ! cell +loop ;</lang>
Example usage:
<lang forth>create data 1 , 2 , 3 , 4 , 5 , data 5 ' 1+ map \ adds one to each element of data</lang>
Fortran
Elemental functions.
<lang fortran>module arrCallback contains
elemental function cube( x ) implicit none real :: cube real, intent(in) :: x cube = x * x * x end function cube
end module arrCallback</lang>
<lang fortran>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 do
end program testAC</lang>
<lang fortran> program test C C-- Declare array:
integer a(5)
C C-- Fill it with Data
data a /45,22,67,87,98/
C C-- Do something with all elements (in this case: print their squares)
do i=1,5 print *,a(i)*a(i) end do
C
end</lang>
FP
<lang fp>{square * . [id, id]} & square: <1,2,3,4,5></lang>
Frink
<lang frink> f = {|x| x^2} // Anonymous function to square input a = [1,2,3,5,7] println[map[f, a]] </lang>
F#
Apply a named function to each member of the array. The result is a new array of the same size as the input. <lang fsharp>let evenp x = x % 2 = 0 let result = Array.map evenp [| 1; 2; 3; 4; 5; 6 |]</lang> The same can be done using anonymous functions, this time squaring the members of the input array. <lang fsharp>let result = Array.map (fun x -> x * x) [|1; 2; 3; 4; 5|]</lang> Use iter if the applied function does not return a value. <lang fsharp>Array.iter (fun x -> printfn "%d" x) [|1; 2; 3; 4; 5|]</lang>
GAP
<lang gap>a := [1 .. 4]; b := ShallowCopy(a);
- Apply and replace values
Apply(a, n -> n*n); a;
- [ 1, 4, 9, 16 ]
- Apply and don't change values
List(b, n -> n*n);
- [ 1, 4, 9, 16 ]
- Apply and don't return anything (only side effects)
Perform(b, Display); 1 2 3 4
b;
- [ 1 .. 4 ]</lang>
Go
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: <lang go>package main
import "fmt"
func main() {
for _, i := range []int{1, 2, 3, 4, 5} { fmt.Println(i * i) }
}</lang>
Alternatively though, an array-like type can be defined and callback-style methods can be defined on it to apply a function to the elements. <lang go>package main
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 }))
}</lang>
- Output:
1 4 9 16 25 [1 4 9 16 25]
Groovy
Print each value in a list <lang groovy>[1,2,3,4].each { println it }</lang>
Create a new list containing the squares of another list <lang groovy>[1,2,3,4].collect { it * it }</lang>
Haskell
List
<lang haskell>let square x = x*x let values = [1..10] map square values</lang>
Using list comprehension to generate a list of the squared values <lang haskell>[square x | x <- values]</lang>
Using function composition to create a function that will print the squares of a list <lang haskell>let printSquares = mapM_ (print.square) printSquares values</lang>
Array
<lang haskell>import Data.Array.IArray let square x = x*x let values = array (1,10) [(i,i)|i <- [1..10]] :: Array Int Int amap square values</lang>
Icon and Unicon
<lang icon>procedure main()
local lst lst := [10, 20, 30, 40] every callback(write,!lst)
end
procedure callback(p,arg)
return p(" -> ", arg)
end</lang>
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
<lang idl>b = a^3</lang>
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
<lang io>list(1,2,3,4,5) map(squared)</lang>
J
Solution: <lang j> "_1</lang>
Example: <lang j> callback =: *:
array =: 1 2 3 4 5 callback"_1 array
1 4 9 16 25</lang>
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
As of the current version of Java, you have to define an interface for each type of function you want to use. The next version of Java will introduce function types.
So if you want to perform an action (which doesn't return anything) on an array of int's:
<lang java>interface IntToVoid {
void run(int x);
}
for (int z : myIntArray) {
new IntToVoid() { public void run(int x) { System.out.println(x); } }.run(z);
}</lang>
Or if you want to perform "map" - return an array of the results of function applications:
<lang java>interface IntToInt {
int run(int x);
}
int[] result = new int[myIntArray.length]; for (int i = 0; i < myIntArray.length; i++) {
result[i] = new IntToInt() { public int run(int x) { return x * x; } }.run(myIntArray[i]);
}</lang>
JavaScript
ES3
<lang javascript>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; });</lang>
ES5
<lang javascript>[1, 2, 3, 4, 5].map(function(v) { return v * v; });</lang>
ES6
<lang javascript>[1, 2, 3, 4, 5].map(v => v * v);</lang>
The result is always:
[1, 4, 9, 16, 25]
Joy
<lang joy>[1 2 3 4 5] [dup *] map.</lang>
jq
Julia
<lang julia># Illustration of map/1 using the builtin filter: exp map(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 comprehension
reduce .[] as $n ([]; . + [ exp ])
- Elementwise operation
[.[] + 1 ] # add 1 to each element of the input array
</lang>Here is a transcript illustrating how the last of these jq expressions can be evaluated: <lang jq>$ jq -c ' [.[] + 1 ]' [0, 1 , 10] [1,2,11]</lang>
Julia
<lang julia> numbers = [1, 3, 5, 7]
square1 = [square(n) for n in numbers] # list comprehension
squares2a = map(square, numbers) # functional form
squares2b = map(x -> x*x, numbers) # functional form with `lambda`
- There is also extended block form for the map function
squares2c = map(numbers) do x sum = 0 for i = 1:x sum += x^2 #trivial, but you get the point end return sum end
squares3 = [n * n for n in numbers] # no need for a function,
squares4 = numbers .* numbers # element-wise operation
squares4a = numbers .^ 2 # most arithmetic operations can be done element-wise</lang>
Lang5
<lang lang5>: square(*) dup * ; [1 2 3 4 5] square . "\n" . [1 2 3 4 5] 'square apply . "\n" .</lang>
Lasso
<lang Lasso>define cube(n::integer) => #n*#n*#n
local( mynumbers = array(1, 2, 3, 4, 5), mycube = array )
- mynumbers -> foreach => {
#mycube -> insert(cube(#1)) }
- mycube</lang>
-> array(1, 8, 27, 64, 125)
Lisaac
<lang Lisaac>+ a : ARRAY(INTEGER); + b : {INTEGER;};
a := ARRAY(INTEGER).create 1 to 3; 1.to 3 do { i : INTEGER;
a.put i to i;
};
b := { arg : INTEGER;
(arg * arg).print; '\n'.print;
};
a.foreach b;</lang>
Logo
<lang logo>to square :x
output :x * :x
end show map "square [1 2 3 4 5] ; [1 4 9 16 25] show map [? * ?] [1 2 3 4 5] ; [1 4 9 16 25] foreach [1 2 3 4 5] [print square ?] ; 1 4 9 16 25, one per line</lang>
Lua
Say we have an array: <lang lua>myArray = {1, 2, 3, 4, 5}</lang> A map function for this would be <lang lua>map = function(f, data)
local result = {} for k,v in ipairs(data) do result[k] = f(v) end return result
end</lang> Together with our array and a square function this yields: <lang lua>myFunc = function(x) return x*x end
print(unpack( map(myFunc, myArray) )) --> 1 4 9 16 25</lang> If you used pairs() instead of ipairs(), this would even work on a hash table in general. However, remember that hash table do not have an implicit ordering on their elements, like arrays do, so pairs() is not guaranteed to return the elements in the same order as ipairs()
M4
<lang M4>define(`foreach', `pushdef(`$1')_foreach($@)popdef(`$1')')dnl define(`_arg1', `$1')dnl define(`_foreach', `ifelse(`$2', `()', `',
`define(`$1', _arg1$2)$3`'$0(`$1', (shift$2), `$3')')')dnl
dnl define(`apply',`foreach(`x',$1,`$2(x)')')dnl dnl define(`z',`eval(`$1*2') ')dnl apply(`(1,2,3)',`z')</lang>
Output:
2 4 6
Maple
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. <lang Maple> > map( sqrt, [ 1.1, 3.2, 5.7 ] );
[1.048808848, 1.788854382, 2.387467277]
> map( x -> x + 1, { 1, 3, 5 } );
{2, 4, 6}
> sqrt~( [ 1.1, 3.2, 5.7 ] );
[1.048808848, 1.788854382, 2.387467277]
> (x -> x + 1)~( { 1, 3, 5 } );
{2, 4, 6}
</lang> For Arrays (Vectors, Matrices, etc.) both map and trailing tilde also work, and by default create a new object, leaving the input Array unchanged. <lang Maple> > a := Array( [ 1.1, 3.2, 5.7 ] );
a := [1.1, 3.2, 5.7]
> sqrt~( a );
[1.048808848, 1.788854382, 2.387467277]
> a;
[1.1, 3.2, 5.7]
> map( sqrt, a );
[1.048808848, 1.788854382, 2.387467277]
> a;
[1.1, 3.2, 5.7]
</lang> However, since these are mutable data structures in Maple, it is possible to use map to modify its input according to the applied procedure. <lang Maple> > map[inplace]( sqrt, a );
[1.048808848, 1.788854382, 2.387467277]
> a;
[1.048808848, 1.788854382, 2.387467277]
</lang> The Array a has been modified.
It is also possible to pass additional arguments to the mapped procedure. <lang Maple> > map( `+`, [ 1, 2, 3 ], 3 );
[4, 5, 6]
</lang> Passing additional arguments *before* the arguments from the mapped data structure is achieved using map2, or the more general map[n] procedure. <lang Maple> > map2( `-`, 5, [ 1, 2, 3 ] );
[4, 3, 2]
> map[2]( `/`, 5, [ 1, 2, 3 ] );
[5, 5/2, 5/3]
</lang>
Mathematica
<lang Mathematica>(#*#)& /@ {1, 2, 3, 4}
Map[Function[#*#], {1, 2, 3, 4}]
Map[((#*#)&,{1,2,3,4}]
Map[Function[w,w*w],{1,2,3,4}]</lang>
MATLAB
There are two types of arrays in MATLAB: arrays and cell arrays. MATLAB includes two functions, one for each of these data types, that accomplish the specification for this task. For arrays, we use "arrayfun()"; for cell arrays we use "cellfun()".
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.
<lang MATLAB>>> array = [1 2 3 4 5]
array =
1 2 3 4 5
>> arrayfun(@sin,array)
ans =
Columns 1 through 4
0.841470984807897 0.909297426825682 0.141120008059867 -0.756802495307928
Column 5
-0.958924274663138
>> cellarray = {1,2,3,4,5}
cellarray =
[1] [2] [3] [4] [5]
>> cellfun(@tan,cellarray)
ans =
Columns 1 through 4
1.557407724654902 -2.185039863261519 -0.142546543074278 1.157821282349578
Column 5
-3.380515006246586</lang>
Maxima
<lang maxima>/* for lists or sets */
map(sin, [1, 2, 3, 4]); map(sin, {1, 2, 3, 4});
/* for matrices */
matrixmap(sin, matrix([1, 2], [2, 4]));</lang>
Modula-3
<lang modula3>MODULE Callback EXPORTS Main;
IMPORT IO, Fmt;
TYPE CallBack = PROCEDURE (a: CARDINAL; b: INTEGER);
Values = REF ARRAY OF INTEGER;
VAR sample := ARRAY [1..5] OF INTEGER {5, 4, 3, 2, 1};
callback := Display;
PROCEDURE Display(loc: CARDINAL; val: INTEGER) =
BEGIN IO.Put("array[" & Fmt.Int(loc) & "] = " & Fmt.Int(val * val) & "\n"); END Display;
PROCEDURE Map(VAR values: ARRAY OF INTEGER; size: CARDINAL; worker: CallBack) =
VAR lvalues := NEW(Values, size); BEGIN FOR i := FIRST(lvalues^) TO LAST(lvalues^) DO worker(i, values[i]); END; END Map;
BEGIN
Map(sample, NUMBER(sample), callback);
END Callback.</lang>
Nemerle
The Nemerle.Collections namespace defines the methods Iter() (if the function applied is void) and Map() (if the function applied returns a value). <lang Nemerle>def seg = array[1, 2, 3, 5, 8, 13]; def squares = seq.Map(x => x*x);</lang>
NewLISP
<lang NewLISP>> (map (fn (x) (* x x)) '(1 2 3 4)) (1 4 9 16) </lang>
Nial
<lang nial>each (* [first, first] ) 1 2 3 4 =1 4 9 16</lang>
Nimrod
<lang nimrod>var arr = [1,2,3,4] arr.map proc(some: var int) = echo(some, " squared = ", some*some)</lang>
- Output:
1 squared = 1 2 squared = 4 3 squared = 9 4 squared = 16
Objeck
<lang objeck> use Structure;
bundle Default {
class Test { function : Main(args : String[]) ~ Nil { Run(); }
function : native : Run() ~ Nil { values := IntVector->New([1, 2, 3, 4, 5]); squares := values->Apply(Square(Int) ~ Int); each(i : squares) { squares->Get(i)->PrintLine(); }; } function : Square(value : Int) ~ Int { return value * value; } }
} </lang>
OCaml
This function is part of the standard library:
<lang ocaml>Array.map</lang>
Usage example: <lang ocaml>let square x = x * x;; let values = Array.init 10 ((+) 1);; Array.map square values;;</lang>
Or with lists (which are more typical in OCaml): <lang ocaml>let values = [1;2;3;4;5;6;7;8;9;10];; List.map square values;;</lang>
Use iter if the applied function does not return a value.
<lang ocaml>Array.iter (fun x -> Printf.printf "%d" x) [|1; 2; 3; 4; 5|];;</lang> <lang ocaml>List.iter (fun x -> Printf.printf "%d" x) [1; 2; 3; 4; 5];;</lang>
with partial application we can also write:
<lang ocaml>Array.iter (Printf.printf "%d") [|1; 2; 3; 4; 5|];;</lang> <lang ocaml>List.iter (Printf.printf "%d") [1; 2; 3; 4; 5];;</lang>
Octave
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 arrayfun can be used.
<lang octave>function e = f(x, y)
e = x^2 + exp(-1/(y+1));
endfunction
% f([2,3], [1,4]) gives and error, but arrayfun(@f, [2, 3], [1,4]) % works</lang>
(The function f can be rewritten so that it can accept vectors as argument simply changing operators to their dot relatives: e = x.^2 + exp(-1 ./ (y.+1))
)
ooRexx
ooRexx doesn't directly support callbacks on array items, but this is pretty easy to implement using Routine objects. <lang ooRexx> start = .array~of("Rick", "Mike", "David", "Mark") new = map(start, .routines~reversit) call map new, .routines~sayit
-- a function to perform an iterated callback over an array
-- using the provided function. Returns an array containing
-- each function result
- routine map
use strict arg array, function resultArray = .array~new(array~items) do item over array resultArray~append(function~call(item)) end return resultArray
- routine reversit
use arg string return string~reverse
- routine sayit
use arg string say string return .true -- called as a function, so a result is required
</lang>
Order
Both sequences and tuples support the usual map operation seen in many functional languages. Sequences also support 8seq_for_each
, and a few variations, which returns 8nil
.
<lang c>#include <order/interpreter.h>
ORDER_PP( 8tuple_map(8fn(8X, 8times(8X, 8X)), 8tuple(1, 2, 3, 4, 5)) ) // -> (1,4,9,16,25)
ORDER_PP( 8seq_map(8fn(8X, 8times(8X, 8X)), 8seq(1, 2, 3, 4, 5)) ) // -> (1)(4)(9)(16)(25)
ORDER_PP( 8seq_for_each(8fn(8X, 8print(8X 8comma)), 8seq(1, 2, 3, 4, 5)) ) // prints 1,2,3,4,5, and returns 8nil</lang>
Oz
<lang oz>declare
fun{Square A} A*A end
Lst = [1 2 3 4 5] %% apply a PROCEDURE to every element {ForAll Lst Show}
%% apply a FUNCTION to every element Result = {Map Lst Square} {Show Result}</lang>
PARI/GP
<lang parigp>callback(n)=n+n; apply(callback, [1,2,3,4,5])</lang>
Pascal
See Delphi
Perl
<lang perl># create array my @a = (1, 2, 3, 4, 5);
- create callback function
sub mycallback {
return 2 * shift;
}
- use array indexing
for (my $i = 0; $i < scalar @a; $i++) {
print "mycallback($a[$i]) = ", mycallback($a[$i]), "\n";
}
- using foreach
foreach my $x (@a) {
print "mycallback($x) = ", mycallback($x), "\n";
}
- using map (useful for transforming an array)
my @b = map mycallback($_), @a; # @b is now (2, 4, 6, 8, 10)
- and the same using an anonymous function
my @c = map { $_ * 2 } @a; # @c is now (2, 4, 6, 8, 10)
- use a callback stored in a variable
my $func = \&mycallback; my @d = map $func->($_), @a; # @d is now (2, 4, 6, 8, 10)
- filter an array
my @e = grep { $_ % 2 == 0 } @a; # @e is now (2, 4)</lang>
Perl 6
<lang perl6>my $function = { 2 * $^x + 3 }; my @array = 1 .. 5;
- via map function
.say for map $function, @array;
- via map method
.say for @array.map($function);
- via for loop
for @array {
say $function($_);
}
- via the "hyper" metaoperator and method indirection
say @array».$function;</lang>
PHP
<lang php>function cube($n) {
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5); $b = array_map("cube", $a); print_r($b);</lang>
PicoLisp
<lang PicoLisp>: (mapc println (1 2 3 4 5)) # Print numbers 1 2 3 4 5 -> 5
- (mapcar '((N) (* N N)) (1 2 3 4 5)) # Calculate squares
-> (1 4 9 16 25)
- (mapcar ** (1 2 3 4 5) (2 .)) # Same, using a circular list
-> (1 4 9 16 25)
- (mapcar if '(T NIL T NIL) '(1 2 3 4) '(5 6 7 8)) # Conditional function
-> (1 6 3 8)</lang>
Pike
<lang pike>int cube(int n) {
return n*n*n;
}
array(int) a = ({ 1,2,3,4,5 }); array(int) b = cube(a[*]); // automap operator array(int) c = map(a, cube); // conventional map function</lang>
PL/I
<lang PL/I> declare x(5) initial (1,3,5,7,8);
x = sqrt(x); x = sin(x);</lang>
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. <lang plsql>-- Let's create a generic class with one method to be used as an interface: create or replace TYPE callback AS OBJECT (
-- A class needs at least one member even though we don't use it -- There's no generic OBJECT type, so let's call it NUMBER dummy NUMBER, -- Here's our function, and since PL/SQL doesn't have generics, -- let's use type NUMBER for our params MEMBER FUNCTION exec(n number) RETURN number
) NOT FINAL not instantiable; /
-- Now let's inherit from that, defining a class with one method. We'll have ours square a number. -- We can pass this class into any function that takes type callback: CREATE OR REPLACE TYPE CB_SQUARE under callback (
OVERRIDING MEMBER FUNCTION exec(n NUMBER) RETURN NUMBER
) / CREATE OR REPLACE TYPE BODY CB_SQUARE AS
OVERRIDING MEMBER FUNCTION exec(n NUMBER) RETURN NUMBER IS BEGIN RETURN n * n; END exec;
END; /
-- And a package to hold our test CREATE OR REPLACE PACKAGE PKG_CALLBACK AS
myCallback cb_square; TYPE intTable IS TABLE OF NUMBER INDEX BY BINARY_INTEGER; ints intTable; i PLS_INTEGER; procedure test_callback;
END PKG_CALLBACK; /
CREATE OR REPLACE PACKAGE BODY PKG_CALLBACK AS
-- Our generic mapping function that takes a "method" and a collection -- Note that it takes the generic callback type -- that doesn't know anything about squaring procedure do_callback(myCallback IN callback, ints IN OUT intTable) IS i PLS_INTEGER; myInt NUMBER; begin for i in 1 .. ints.count loop myInt := ints(i); -- PL/SQL call's the child's method ints(i) := myCallback.exec(myInt); END LOOP; end do_callback;
procedure test_callback IS BEGIN myCallback := cb_square(null); FOR i IN 1..5 LOOP ints(i) := i; END LOOP; do_callback(myCallback, ints); i := ints.FIRST; WHILE i IS NOT NULL LOOP DBMS_OUTPUT.put_line(ints(i)); i := ints.next(i); END LOOP; END test_callback;
END PKG_CALLBACK; /
BEGIN
PKG_CALLBACK.TEST_CALLBACK();
END; /</lang>
Pop11
<lang pop11>;;; Define a procedure define proc(x);
printf(x*x, '%p,');
enddefine;
- Create array
lvars ar = { 1 2 3 4 5};
- Apply procedure to array
appdata(ar, proc);</lang>
If one wants to create a new array consisting of transformed values then procedure mapdata may be more convenient.
PostScript
The forall
operator applies a procedure to each element of an array, a packed array or a string.
<lang postscript>[1 2 3 4 5] { dup mul = } forall</lang>
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 []
:
<lang postscript>[ [1 2 3 4 5] { dup mul } forall ]</lang>
<lang postscript> [1 2 3 4 5] {dup *} map </lang>
PowerShell
This can be done in PowerShell with the ForEach-Object
cmdlet which applies a scriptblock to each element of an array:
<lang powershell>1..5 | ForEach-Object { $_ * $_ }</lang>
To recreate a map function, found in other languages the same method applies:
<lang powershell>function map ([array] $a, [scriptblock] $s) {
$a | ForEach-Object $s
}</lang>
Prolog
Prolog doesn't have arrays, but we can do it with lists. This can be done in the console mode. <lang Prolog> ?- assert((fun(X, Y) :- Y is 2 * X)). true.
?- maplist(fun, [1,2,3,4,5], L). L = [2,4,6,8,10]. </lang>
PureBasic
<lang PureBasic>Procedure Cube(Array param.i(1))
Protected n.i For n = 0 To ArraySize(param()) Debug Str(param(n)) + "^3 = " + Str(param(n) * param(n) * param(n)) Next
EndProcedure
Dim AnArray.i(4)
For n = 0 To ArraySize(AnArray())
AnArray(n) = Random(99)
Next
Cube(AnArray()) </lang>
Python
<lang python>def square(n):
return n * n
numbers = [1, 3, 5, 7]
squares1 = [square(n) for n in numbers] # list comprehension
squares2a = map(square, numbers) # functional form
squares2b = map(lambda x: x*x, numbers) # functional form with `lambda`
squares3 = [n * n for n in numbers] # no need for a function,
# anonymous or otherwise
isquares1 = (n * n for n in numbers) # iterator, lazy
import itertools isquares2 = itertools.imap(square, numbers) # iterator, lazy</lang> To print squares of integers in the range from 0 to 9, type: <lang python>print " ".join(str(n * n) for n in range(10))</lang> Or: <lang python>print " ".join(map(str, map(square, range(10))))</lang> Result: <lang python>0 1 4 9 16 25 36 49 64 81</lang>
R
Many functions can take advantage of implicit vectorisation, e.g. <lang R>cube <- function(x) x*x*x elements <- 1:5 cubes <- cube(elements)</lang> Explicit looping over array elements is also possible. <lang R>cubes <- numeric(5) for(i in seq_along(cubes)) {
cubes[i] <- cube(elements[i])
}</lang> Loop syntax can often simplified using the *apply family of functions. <lang R>elements2 <- list(1,2,3,4,5) cubes <- sapply(elements2, cube)</lang> In each case above, the value of 'cubes' is
1 8 27 64 125
Racket
<lang racket>
- lang racket
- using the `for/vector' comprehension form
(for/vector ([i #(1 2 3 4 5)]) (sqr i))
- the usual functional `map'
(vector-map sqr #(1 2 3 4 5)) </lang>
Raven
<lang raven># To print the squared elements [1 2 3 4 5] each dup * print</lang>
<lang raven># To obtain a new array group [1 2 3 4 5] each
dup *
list</lang>
REBOL
<lang REBOL>REBOL [
Title: "Array Callback" Date: 2010-01-04 Author: oofoe 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]]</lang>
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
Using the array' library to multiply each value in an array by 10 and display the results:
<lang Retro>[ 1 2 3 4 5 ] ^array'fromQuote [ 10 * ] ^array'map ^array'display</lang>
Retro also provides ^array'apply for use when you don't want to alter the contents of the array:
<lang Retro>[ "Hello" "World" "Foo" ] ^array'fromQuote [ "%s " puts ] ^array'apply</lang>
REXX
<lang rexx>/*REXX program to apply a callback to a stemmed (REXX) array. */
a.=; b.= a.0= 0 a.1= 1 a.2= 2 a.3= 3 a.4= 4 a.5= 5 a.6= 6 a.7= 7 a.8= 8 a.9= 9
a.10=10
call listab 'before' call bangit 'a','b' /*factorialize the A array, store results in B */ call listab ' after' exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────BANGIT subroutine───────────────────*/ bangit: do i=0
_=value(arg(1)'.'i); if _== then return call value arg(2)'.'i,fact(_) end /*i*/
/*──────────────────────────────────FACT subroutine─────────────────────*/ fact: procedure; !=1; do j=2 to arg(1); !=!*j; end; return ! /*──────────────────────────────────LISTAB subroutine───────────────────*/ listab: do j=0 while a.j\==; say arg(1) 'a.'j"="a.j; end /*j*/ say; do k=0 while b.k\==; say arg(1) 'b.'k"="b.k; end /*k*/ return</lang> output
before a.0=0 before a.1=1 before a.2=2 before a.3=3 before a.4=4 before a.5=5 before a.6=6 before a.7=7 before a.8=8 before a.9=9 before a.10=10 after a.0=0 after a.1=1 after a.2=2 after a.3=3 after a.4=4 after a.5=5 after a.6=6 after a.7=7 after a.8=8 after a.9=9 after a.10=10 after b.0=1 after b.1=1 after b.2=2 after b.3=6 after b.4=24 after b.5=120 after b.6=720 after b.7=5040 after b.8=40320 after b.9=362880 after b.10=3628800
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:
<lang RLaB> >> 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
</lang>
This can be done on entry-by-entry basis, but one has to keep in mind that the 'for' or 'while' loops are slow in interpreted languages, and RLaB is no exception.
<lang RLaB> 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] ); }
} </lang>
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.
<lang RLaB> x = <<>>; for (i in 1:9) {
x.[i] = rand();
}
y = <<>>; for (i in members(x)) {
y.[i] = sin( x.[i] );
} </lang>
Ruby
You could use a traditional "for i in arr" approach like below: <lang ruby>for i in [1,2,3,4,5] do
puts i**2
end</lang>
Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk) <lang ruby>[1,2,3,4,5].each{ |i| puts i**2 }</lang>
To create a new array of each value squared <lang ruby>[1,2,3,4,5].map{ |i| i**2 }</lang>
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.
<lang Salmon>function apply(list, ageless to_apply)
(comprehend(x; list) (to_apply(x)));
function square(x) (x*x);
iterate(x; apply([0...9], square))
x!;</lang>
With short identifiers:
<lang Salmon>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!;</lang>
With the numbers given as a list of individual elements:
<lang Salmon>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!;</lang>
Sather
<lang 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;</lang>
Scala
<lang scala>val l = List(1,2,3,4) l.foreach {i => println(i)}</lang>
When the argument appears only once -as here, i appears only one in println(i) - it may be shortened to <lang scala>l.foreach(println(_))</lang> Same for an array <lang scala>val a = Array(1,2,3,4) a.foreach {i => println(i)} a.foreach(println(_)) // same as previous line</lang>
Or for an externally defined function: <lang scala>def doSomething(in: int) = {println("Doing something with "+in)} l.foreach(doSomething)</lang>
There is also a for syntax, which is internally rewritten to call foreach. A foreach method must be defined on a <lang scala>for(val i <- a) println(i)</lang>
It is also possible to apply a function on each item of an list to get a new list (same on array and most collections) <lang scala>val squares = l.map{i => i * i} //squares is List(1,4,9,16)</lang>
Or the equivalent for syntax, with the additional keyword yield, map is called instead of foreach <lang scala>val squares = for (val i <- l) yield i * i</lang>
Scheme
<lang scheme>(define (square n) (* n n)) (define x #(1 2 3 4 5)) (map square (vector->list x))</lang>
A single-line variation <lang scheme>(map (lambda (n) (* n n)) '(1 2 3 4 5))</lang>
For completeness, the map function (which is R5RS standard) can be coded as follows: <lang scheme>(define (map f L)
(if (null? L) L (cons (f (car L)) (map f (cdr L)))))</lang>
Sidef
Define a callback function: <lang ruby>func callback(i) { say i**2 };</lang>
Now, the function will get called for each element: <lang ruby>[1,2,3,4].each(callback);</lang>
Same as above, but with the function inlined: <lang ruby>[1,2,3,4].each{|i| say i**2 };</lang>
To create a new array of each value squared, we can use: <lang ruby>[1,2,3,4,5].map{|i| i**2 };</lang>
Slate
<lang slate>#( 1 2 3 4 5 ) collect: [| :n | n * n].</lang>
Smalltalk
<lang smalltalk>#( 1 2 3 4 5 ) collect: [:n | n * n].</lang>
Sparkling
The foreach function calls the supplied callback on each element of the (possibly associative) array, passing it each key and the corresponding value: <lang sparkling>let numbers = { 1, 2, 3, 4 }; foreach(numbers, function(idx, num) {
print(num);
});</lang>
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: <lang sparkling>let dict = { "foo": 42, "bar": 13, "baz": 37 }; let doubled = map(dict, function(key, val) {
return val * 2;
});</lang>
Standard ML
<lang Standard ML> map f l </lang> i.e. <lang Standard ML> map (fn x=>x+1) [1,2,3];; (* [2,3,4] *) </lang>
SuperCollider
Actually, there is a builtin squared operator: <lang SuperCollider>[1, 2, 3].squared; // returns [1, 4, 9]</lang> Anything that is a Collection can be used with collect: <lang SuperCollider>[1, 2, 3].collect({ arg x; x*x });</lang> List comprehension combined with a higher-order function can also be used: <lang SuperCollider>var square = {
arg x; x*x;
}; var map = {
arg fn, xs; all {: fn.value(x), x <- xs };
}; map.value(square,[1,2,3]);</lang>
Tcl
If I wanted to call "myfunc" on each element of dat and dat were a list: <lang tcl>foreach var $dat {
myfunc $var
}</lang> This does not retain any of the values returned by myfunc.
if dat were an (associative) array, however: <lang tcl>foreach name [array names dat] {
myfunc $dat($name)
}</lang>
More functional, with a simple map
function:
<lang Tcl>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</lang>
TI-89 BASIC
<lang ti89b>© For no return value Define foreach(fe_cname,fe_list) = Prgm
Local fe_i For fe_i,1,dim(fe_list) #fe_cname(fe_list[fe_i]) EndFor
EndPrgm
© For a list of results Define map(map_cnam,map_list) = seq(#map_cnam(map_list[map_i]),map_i,1,dim(map_list))
Define callback(elem) = Prgm
Disp elem
EndPrgm
foreach("callback", {1,2,3,4,5}) Disp map("√", {1,2,3,4,5})</lang>
Output:
TIScript
JavaScript alike:
<lang javascript>var a = [1, 2, 3, 4, 5]; a.map(function(v) { return v * v; }) </lang>
Using short form of lambda notation: <lang javascript>var a = [1, 2, 3, 4, 5]; a.map( :v: v*v ); </lang>
Toka
<lang 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 a 10 0 a array.put 11 1 a array.put 12 2 a array.put 13 3 a array.put 14 4 a array.put
( Add 1 to each item in the array ) a 5 [ 1 + ] map-array</lang>
TorqueScript
--Elm 03:41, 18 June 2012 (UTC)
Callbacks:
<lang TorqueScript> function map(%array,%arrayCount,%function) { for(%i=0;%i<%arrayCount;%i++) { eval("%a = "@%array@"["@%i@"];"); eval(""@%function@"("@%a@");"); } } </lang>
Now to set up an array:
<lang TorqueScript> $array[0] = "Hello."; $array[1] = "Hi."; $array[2] = "How are you?"; </lang>
Now to call the function correctly:
<lang TorqueScript> map("$array",3,"echo"); </lang>
Which should result in:
<lang TorqueScript> => Hello.
=> Hi.
=> How are you? </lang>
TXR
Print 1 through 10 out of a vector, using prinl
the callback, right from the system shell command prompt:
<lang bash>$ txr -e '[mapdo prinl #(1 2 3 4 5 6 7 8 9 10)]' 1 2 3 4 5 6 7 8 9 10</lang>
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.
UNIX Shell
<lang bash>map() { map_command=$1 shift for i do "$map_command" "$i"; done } list=1:2:3 (IFS=:; map echo $list)</lang>
<lang bash>map() { typeset command=$1 shift for i do "$command" "$i"; done } set -A ary 1 2 3 map print "${ary[@]}"</lang>
<lang bash>map(){for i ($*[2,-1]) $1 $i} a=(1 2 3) map print $a</lang>
Ursala
The * is a built-in map operator. This example shows a map of the successor function over a list of natural numbers. <lang Ursala>#import nat
- cast %nL
demo = successor* <325,32,67,1,3,7,315></lang> output:
<326,33,68,2,4,8,316>
V
apply squaring (dup *) to each member of collection <lang v>[1 2 3 4] [dup *] map</lang>
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
<lang vb> 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 function end class </lang>
Invocation
<lang vb> dim a1 dim cb set cb = new callback
cb.rule = "ucase(p1)" a1 = split("my dog has fleas", " " ) cb.applyTo a1 wscript.echo join( a1, " " )
cb.rule = "p1 ^ p1" a1 = array(1,2,3,4,5,6,7,8,9,10) cb.applyto a1 wscript.echo join( a1, ", " )
</lang>
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.
<lang vim>echo map([10, 20, 30], 'v:val * v:val')
echo map([10, 20, 30], '"Element " . v:key . " = " . v:val')
echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:val)')
echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:key)')</lang>
- 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'}
Vorpal
Given and array, A, and a function, F, mapping F over the elements of A is simple: <lang vorpal>A.map(F)</lang> 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. <lang vorpal>A.map(F, x, y)</lang>
Wart
<lang wart>map prn '(1 2 3 4 5)</lang>
Output:
1 2 3 4 5
zkl
<lang zkl>L(1,2,3,4,5).apply('+(5))</lang> Output:
L(6,7,8,9,10)
- Programming Tasks
- Basic language learning
- Iteration
- ACL2
- ACL2 examples needing attention
- Examples needing attention
- ActionScript
- Ada
- Aime
- ALGOL 68
- AppleScript
- AutoHotkey
- AWK
- Babel
- BBC BASIC
- Bracmat
- Brat
- C
- C sharp
- C++
- STL
- Boost
- Clean
- Clojure
- COBOL
- CoffeeScript
- Common Lisp
- Component Pascal
- D
- Delphi
- Déjà Vu
- E
- Efene
- EGL
- Elena
- Erlang
- Euphoria
- Factor
- Fantom
- FBSL
- Forth
- Fortran
- FP
- Frink
- F Sharp
- GAP
- Go
- Groovy
- Haskell
- Icon
- Unicon
- IDL
- Io
- J
- Java
- JavaScript
- Joy
- Jq
- Julia
- Lang5
- Lasso
- Lisaac
- Logo
- Lua
- M4
- Maple
- Mathematica
- MATLAB
- Maxima
- Modula-3
- Nemerle
- NewLISP
- Nial
- Nimrod
- Objeck
- OCaml
- Octave
- OoRexx
- Order
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- Pike
- PL/I
- PL/SQL
- Pop11
- PostScript
- Initlib
- PowerShell
- Prolog
- PureBasic
- Python
- R
- Racket
- Raven
- REBOL
- Retro
- REXX
- RLaB
- Ruby
- Salmon
- Sather
- Scala
- Scheme
- Sidef
- Slate
- Smalltalk
- Sparkling
- Standard ML
- SuperCollider
- Tcl
- TI-89 BASIC
- TIScript
- Toka
- TorqueScript
- TXR
- UNIX Shell
- Ursala
- V
- VBScript
- Vim Script
- Vorpal
- Wart
- Zkl
- Gnuplot/Omit
- LaTeX/Omit
- Make/Omit
- NSIS/Omit
- PlainTeX/Omit