Apply a callback to an array: Difference between revisions
→{{header|langur}}
Puppydrum64 (talk | contribs) |
Langurmonkey (talk | contribs) |
||
(43 intermediate revisions by 29 users not shown) | |||
Line 1:
[[Category:Iteration]]
{{task|Basic language learning}}
;Task:
Line 8:
=={{header|11l}}==
{{trans|Kotlin}}
<
V arrsq = array.map(i -> i * i)
print(arrsq)</
{{out}}
<pre>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</pre>
Line 17:
For this example, assume both the source array and the destination have a size of 86 elements (memory offsets base+0x00 to base+0x55.)
This was implemented in easy6502.
<
define SRC_HI $01
Line 70:
CLC
ADC temp ;2a + a = 3a
RTS</
{{out}}
Line 81 ⟶ 83:
1250: f0 f3 f6 f9 fc ff
</pre>
=={{header|68000 Assembly}}==
{{trans|11l}}
The following assumes all code/data is stored/executed in RAM and is therefore mutable.
<syntaxhighlight lang="68000devpac">LEA MyArray,A0
MOVE.W #(MyArray_End-MyArray)-1,D7 ;Len(MyArray)-1
MOVEQ #0,D0 ;sanitize D0-D2 to ensure nothing from any previous work will affect our math.
MOVEQ #0,D1
MOVEQ #0,D2
loop:
MOVE.B (A0),D0
MOVE.B D0,D1
MOVE.B D0,D2
MULU D1,D2
MOVE.B D2,(A0)+
dbra d7,loop
jmp * ;halt the CPU
MyArray:
DC.B 1,2,3,4,5,6,7,8,9,10
MyArray_End:</syntaxhighlight>
=={{header|8th}}==
The builtin word "a:map" does this:
<
[ 1 , 2, 3 ]
' n:sqr
a:map
</syntaxhighlight>
That results in the array [1,4,9]
Line 96 ⟶ 120:
ACL2 does not have first-class functions; this is close, however:
<
(if (endp xs)
nil
Line 104 ⟶ 128:
(defun fn-to-apply (x)
(* x x))
</syntaxhighlight>
=={{header|ActionScript}}==
<
{
public class ArrayCallback
Line 125 ⟶ 149:
}
}
}</
=={{header|Ada}}==
{{works with|GNAT|GPL 2005}}
<
with Ada.Integer_text_IO;
Line 165 ⟶ 189:
begin
Map(Sample, Display'access);
end Call_Back_Example;</
=={{header|Aime}}==
<
map(list l, void (*fp)(object))
{
Line 186 ⟶ 210:
return 0;
}</
=={{header|ALGOL 68}}==
Line 193 ⟶ 217:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<
(
printf(($"array["g"] = "gl$, location, value))
Line 209 ⟶ 233:
[4]INT array := ( 1, 4, 9, 16 );
map(array, call back proc)
)</
{{Out}}
Line 220 ⟶ 244:
=={{header|ALGOL W}}==
<
procedure printSquare ( integer value x ) ; writeon( i_w := 1, s_w := 0, " ", x * x );
% applys f to each element of a from lb to ub (inclusive) %
Line 231 ⟶ 255:
applyI( printSquare, a, 1, 3 )
end
end.</
=={{header|APL}}==
By default functions in APL work on arrays as it is an array oriented language. Some examples:
<
¯1 ¯2 ¯3
2 * 1 2 3 4
Line 246 ⟶ 270:
81 243 729
2187 6561 19683
</syntaxhighlight>
=={{header|AppleScript}}==
<
-- Returns a string like "arc has 3 letters"
arg & " has " & (count arg) & " letters"
Line 259 ⟶ 283:
-- to callback, then speaks the return value.
say (callback for aref)
end repeat</
If the callback would <code>set arg's contents to "something"</code>, then <code>alist</code> would be mutated.
Line 266 ⟶ 290:
For a more general implementation of '''map(function, list)''', '''foldl(function, startValue, list)''', and '''filter(predicate, list)''', we could write:
<
set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Line 343 ⟶ 367:
return lst
end tell
end map</
{{Out}}
<pre>{{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}, {2, 4, 6, 8, 10}, 55}</pre>
=={{header|Arturo}}==
<
print map arr => [2*&]</
{{out}}
Line 357 ⟶ 381:
=={{header|AutoHotkey}}==
<
callback(array){
Line 366 ⟶ 390:
map(callback, array){
%callback%(array)
}</
=={{header|AWK}}==
<
4 16
5 25
1 1
2 4
3 9</
=={{header|Babel}}==
Line 380 ⟶ 404:
Let us define a squaring operator:
<
Now, we apply the sq operator over a list and display the result using the lsnum utility:
<
{{Out}}
Line 391 ⟶ 415:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
a() = 1, 2, 3, 4, 5
PROCmap(a(), FNsqrt())
Line 407 ⟶ 431:
NEXT
ENDPROC
</syntaxhighlight>
{{Out}}
<pre>
Line 416 ⟶ 440:
2.23606798
</pre>
=={{header|Binary Lambda Calculus}}==
In the lambda calculus, we can map over a list as in https://github.com/tromp/AIT/blob/master/lists/map.lam, which gives the following BLC program to negate every bit of input:
<pre>010001101000000101100000000001011000000101111111010110010111111101111110111010</pre>
=={{header|BQN}}==
<syntaxhighlight lang="bqn">Square ← ט
array ← 2‿3‿5‿7‿11‿13
Square¨ array</syntaxhighlight>
The use of the ¨ modifier is the general approach, but actually not necessary with arithmetic functions.
{{out}}
<pre>⟨ 4 9 25 49 121 169 ⟩</pre>
=={{header|Bracmat}}==
<
= location value
. !arg:(?location,?value)
Line 446 ⟶ 484:
& mapar$(array,4,callbackFunction2)
& mapar$(array,4,callbackFunction1)
);</
{{Out}}
<pre>array[0] = 1
Line 459 ⟶ 497:
=={{header|Brat}}==
<
[:a :b :c :d :e].each { element |
p element
}</
Alternatively:
<
=={{header|C}}==
'''callback.h'''
<
#define CALLBACK_H
Line 486 ⟶ 524:
void map(int* array, int len, void(*callback)(int,int));
#endif</
'''callback.c'''
<
#include "callback.h"
Line 515 ⟶ 553:
map(array, 4, callbackFunction);
return 0;
}</
{{Out}}
Line 525 ⟶ 563:
</pre>
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|3.0+}}
This version uses the C# 3 lambda notation.
<
// Simplest method: LINQ, functional
int[] squares1 = intArray.Select(x => x * x).ToArray();
Line 539 ⟶ 577:
// Or, if you only want to call a function on each element, just use foreach
foreach (var i in intArray)
Console.WriteLine(i * i);</
{{works with|C sharp|C#|2.0+}}
{{works with|Visual C sharp|Visual C#|2005}}
<
static class Program
Line 577 ⟶ 615:
Console.WriteLine(value * value);
}
}</
=={{header|C++}}==
Line 583 ⟶ 621:
{{works with|g++|4.1.1}}
===C-Style Array===
<
#include <algorithm> //for_each defined here
Line 598 ⟶ 636:
return 0;
}
//prints 1 4 9 16 25</
===std::vector===
{{libheader|STL}}
<
#include <algorithm> // for_each defined here
#include <vector> // stl vector class
Line 623 ⟶ 661:
return 0;
}
//prints 1 4 9 16 25</
More tricky with binary function
<
#include <algorithm> // for_each defined here
#include <vector> // stl vector class
Line 649 ⟶ 687:
return 0;
}
//prints 1x 2x 3x 4x 5x</
===Boost.Lambda===
{{libheader|Boost}}
<
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</
===C++11===
<
#include <iostream>
#include <algorithm>
Line 675 ⟶ 713:
std::cout << std::endl;
return 0;
}</
=={{header|Clean}}==
Line 681 ⟶ 719:
Define a function and an initial (unboxed) array.
<
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).
<
Apply the function to the initial array (using a comprehension) and print result.
<
Start = mapArray square values</
=={{header|Clio}}==
'''Math operations'''
<
'''Quick functions'''
<syntaxhighlight lang="text">[1 2 3 4] -> * n: n * 2 + 1 -> print</
'''Anonymous function'''
<
-> * fn n:
n * 2 + 1
-> print</
'''Named function'''
<
n * 2 + 1
[1 2 3 4] -> * double-plus-one -> print</
=={{header|Clojure}}==
<
(map inc [1 2 3 4])</
<
(map (fn [x] (* x x)) [1 2 3 4])</
<
(map #(* % %) [1 2 3 4])</
=={{header|
<syntaxhighlight lang="clu">% This procedure will call a given procedure with each element
% of the given array. Thanks to CLU's type parameterization,
% it will work for any type of element.
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])
end
end apply_to_all
% Callbacks for both string and int
show_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 them
start_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</syntaxhighlight>
{{out}}
<pre>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</pre>
=={{header|COBOL}}==
{{Works with|COBOL 2002}}
Basic implementation of a map function:
<syntaxhighlight lang="cobolfree"> >>SOURCE FORMAT IS FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. map.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 i USAGE IS INDEX.
01 table-size CONSTANT AS 30.
LINKAGE SECTION.
01 table-param.
03 table-values USAGE IS FLOAT-LONG, OCCURS table-size TIMES.
01 func-ptr USAGE IS PROGRAM-POINTER.
PROCEDURE DIVISION USING BY REFERENCE table-param, BY VALUE func-ptr.
GOBACK.
END PROGRAM map.</syntaxhighlight>
=={{header|CoffeeScript}}==
<
map = (arr, f) -> (f(e) for e in arr)
arr = [1, 2, 3, 4, 5]
f = (x) -> x * x
console.log map arr, f # prints [1, 4, 9, 16, 25]
</syntaxhighlight>
=={{header|Common Lisp}}==
Line 761 ⟶ 846:
Imperative: print 1, 2, 3, 4 and 5:
<
Functional: collect squares into new vector that is returned:
<
(map 'vector #'square #(1 2 3 4 5))</
Destructive, like the Javascript example; add 1 to every slot of vector *a*:
<
(map-into *a* #'1+ *a*)</
=={{header|Component Pascal}}==
BlackBox Component Builder
<
MODULE Callback;
IMPORT StdLog;
Line 830 ⟶ 915:
END Do;
END Callback.
</syntaxhighlight>
Execute: ^Q Callback.Do<br/>
{{Out}}
Line 859 ⟶ 944:
=={{header|Crystal}}==
Calling with a block
<
new_values = values.map do |number|
Line 865 ⟶ 950:
end
puts new_values #=> [2, 4, 6]</
Calling with a function/method
<
def double(number)
Line 879 ⟶ 964:
new_values = values.map &->double(Int32)
puts new_values #=> [2, 4, 6]</
=={{header|D}}==
<
void main() {
Line 888 ⟶ 973:
auto m = items.map!(x => x + 5)();
writeln(m);
}</
{{out}}
<pre>[6, 7, 8, 9, 10]</pre>
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
// Declare the callback function
procedure callback(const AInt:Integer);
Line 911 ⟶ 996:
callback(myArray[i]);
end.
</syntaxhighlight>
=={{header|Dyalect}}==
<
let ys = []
for x in this when pred(x) {
}
return ys
}
var arr = [1, 2, 3, 4, 5]
var squares = arr.
print(squares)</
=={{header|Déjà Vu}}==
There is a <code>map</code> builtin that does just this.
<
#implemented roughly like this:
Line 935 ⟶ 1,022:
# for i in lst:
# f i
# [</
{{out}}
<pre>[ 2 5 9 ]</pre>
Line 941 ⟶ 1,028:
=={{header|E}}==
<
def square(value) {
return value * value
}</
Example of builtin iteration:
<
println(`Item $index is $value.`)
}
array.iterate(callback)</
There is no built-in map function '''yet'''.
Line 957 ⟶ 1,044:
returning a plain list (which is usually an array in implementation).
<
def output := [].diverge()
for item in collection {
Line 964 ⟶ 1,051:
return output.snapshot()
}
println(map(square, array))</
=={{header|EchoLisp}}==
<
(vector-map sqrt #(0 4 16 49))
→ #( 0 2 4 7)
Line 979 ⟶ 1,066:
v[2] = 4
→ #( 4 9 16)
</syntaxhighlight>
=={{header|Efene}}==
<
N * N
}
Line 1,015 ⟶ 1,102:
io.format("squares3 : ~p~n", [squares3(Numbers)])
}
</syntaxhighlight>
=={{header|EGL}}==
<
program ApplyCallbackToArray
Line 1,037 ⟶ 1,124:
return( i * i );
end
end</
=={{header|Elena}}==
ELENA
<
PrintSecondPower(n){ console.writeLine(n * n) }
Line 1,047 ⟶ 1,134:
public program()
{
new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.forEach
}</
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">
Enum.map([1, 2, 3], fn(n) -> n * 2 end)
Enum.map [1, 2, 3], &(&1 * 2)
</syntaxhighlight>
{{Out}}
Line 1,064 ⟶ 1,151:
A list would be more commonly used in Erlang rather than an array.
<syntaxhighlight lang="erlang">
1> L = [1,2,3].
[1,2,3]
</syntaxhighlight>
You can use lists:foreach/2 if you just want to apply the callback to each element of the list.
<syntaxhighlight lang="text">
2> lists:foreach(fun(X) -> io:format("~w ",[X]) end, L).
1 2 3 ok
</syntaxhighlight>
Or you can use lists:map/2 if you want to create a new list with the result of the callback on each element.
<syntaxhighlight lang="erlang">
3> lists:map(fun(X) -> X + 1 end, L).
[2,3,4]
</syntaxhighlight>
Or you can use lists:foldl/3 if you want to accumulate the result of the callback on each element into one value.
<syntaxhighlight lang="erlang">
4> lists:foldl(fun(X, Sum) -> X + Sum end, 0, L).
6
</syntaxhighlight>
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM CALLBACK
Line 1,116 ⟶ 1,203:
PRINT
END PROGRAM
</syntaxhighlight>
This example shows how to pass a function to a procedure.
{{Out}}
Line 1,124 ⟶ 1,211:
=={{header|Euphoria}}==
<
-- apply a function to all elements of a sequence
sequence result
Line 1,141 ⟶ 1,228:
-- 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 <code>routine_id()</code>.
Note that this example will not work for multi-dimensional sequences.
Line 1,147 ⟶ 1,234:
=={{header|F_Sharp|F#}}==
Apply a named function to each member of the array. The result is a new array of the same size as the input.
<
let 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.
<
Use ''iter'' if the applied function does not return a value.
<
=={{header|Factor}}==
Print each element squared:
<
Collect return values:
<
=={{header|Fantom}}==
Line 1,165 ⟶ 1,252:
In Fantom, functions can be passed to a collection iterator, such as 'each'. 'map' is used similarly, and the results are collected into a list.
<
class Main
{
Line 1,175 ⟶ 1,262:
}
}
</syntaxhighlight>
{{Out}}
Line 1,189 ⟶ 1,276:
=={{header|FBSL}}==
'''User-defined mapping function:'''
<
FOREACH DIM e IN MyMap(Add42, {1, 2, 3})
Line 1,205 ⟶ 1,292:
END FUNCTION
FUNCTION Add42(n): RETURN n + 42: END FUNCTION</
{{Out}}
<pre>43 44 45
Line 1,211 ⟶ 1,298:
'''Standard MAP() function:'''
<
DIM languages[] = {{"English", {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}}, _
Line 1,227 ⟶ 1,314:
MAP(NameANumber, lang[0], 1 TO 10, lang[1])
PRINT LPAD("", 40, "-")
END SUB</
{{Out}}
<pre>The number 1 is called "one" in English
Line 1,252 ⟶ 1,339:
----------------------------------------
Press any key to continue...</pre>
=={{header|Fe}}==
<syntaxhighlight lang="clojure">
(= map (fn (f lst)
(let res (cons nil nil))
(let tail res)
(while lst
(setcdr tail (cons (f (car lst)) nil))
(= lst (cdr lst))
(= tail (cdr tail)))
(cdr res)))
(print (map (fn (x) (* x x)) '(1 2 3 4 5 6 7 8 9 10)))
</syntaxhighlight>
=={{header|Forth}}==
Line 1,257 ⟶ 1,358:
This is a word that will call a given function on each cell in an array.
<
-rot cells bounds do i @ over execute i ! cell +loop ;</
{{Out|Example usage}}
<
data 5 ' 1+ map \ adds one to each element of data</
=={{header|Fortran}}==
Line 1,268 ⟶ 1,369:
{{Works with |Fortran|ISO 95 and later}}
<
contains
elemental function cube( x )
Line 1,276 ⟶ 1,377:
cube = x * x * x
end function cube
end module arrCallback</
<
use arrCallback
implicit none
Line 1,294 ⟶ 1,395:
write(*,*) b(i,:)
end do
end program testAC</
{{Works with|ANSI FORTRAN| 77 (with MIL-STD-1753 structured DO) and later}}
<
C
C-- Declare array:
Line 1,310 ⟶ 1,411:
end do
C
end</
=={{header|FP}}==
<
& square: <1,2,3,4,5></
=={{header|FreeBASIC}}==
<
Sub PrintEx(n As Integer)
Line 1,335 ⟶ 1,436:
Print
Print "Press any key to quit the program"
Sleep</
{{out}}
Line 1,354 ⟶ 1,455:
=={{header|Frink}}==
<
f = {|x| x^2} // Anonymous function to square input
a = [1,2,3,5,7]
println[map[f, a]]
</syntaxhighlight>
=={{header|FunL}}==
<
[1, 2, 3].foreach( a -> println(2a) )</
{{out}}
Line 1,377 ⟶ 1,478:
=={{header|Futhark}}==
<syntaxhighlight lang="futhark">
map f l
</syntaxhighlight>
e.g.
<syntaxhighlight lang="futhark">
map (\x->x+1) [1,2,3] -- [2,3,4]
</syntaxhighlight>
or equivalently
<syntaxhighlight lang="futhark">
map (+1) [1,2,3] -- [2,3,4]
</syntaxhighlight>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
void local fn Callback( n as NSInteger )
NSLog( @"Square root of %ld = %f", n, sqr(n) )
end fn
void local fn DoIt
NSUInteger i, count
CFArrayRef array = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10]
count = len(array)
for i = 0 to count -1
fn Callback( fn NumberIntegerValue( array[i] ) )
next
end fn
fn DoIt
HandleEvents
</syntaxhighlight>
Another option is to enumerate the array.
<syntaxhighlight lang="futurebasic">include "NSLog.incl"
void local fn Callback( array as CFArrayRef, obj as CFTypeRef )
long value = intVal(obj)
NSLog( @"Square root of %ld = %f", value, sqr(value) )
end fn
void local fn DoIt
CFArrayRef array = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10]
ArrayEnumerateObjects( array, @fn Callback, NULL )
end fn
fn DoIt
HandleEvents</syntaxhighlight>
{{out}}
<pre>
Square root of 1 = 1.000000
Square root of 2 = 1.414214
Square root of 3 = 1.732051
Square root of 4 = 2.000000
Square root of 5 = 2.236068
Square root of 6 = 2.449490
Square root of 7 = 2.645751
Square root of 8 = 2.828427
Square root of 9 = 3.000000
Square root of 10 = 3.162278
</pre>
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Apply_a_callback_to_an_array}}
'''Solution'''
Most programming languages define a high-order map function. In Fōrmulæ, there is ''arraization'' (by analogy with ''summation''). In the following expression, the "big" curly braces resembles the "big" sigma of a summation:
[[File:Fōrmulæ - Apply a callback to an array 01.png]]
[[File:Fōrmulæ - Apply a callback to an array 02.png]]
The elements of the array are not required to be of the same type:
[[File:Fōrmulæ - Apply a callback to an array 03.png]]
[[File:Fōrmulæ - Apply a callback to an array 04.png]]
=={{header|GAP}}==
<
b := ShallowCopy(a);
Line 1,418 ⟶ 1,586:
b;
# [ 1 .. 4 ]</
=={{header|Go}}==
Line 1,425 ⟶ 1,593:
Perhaps in contrast to Ruby, it is idiomatic in Go to use the for statement:
<
import "fmt"
Line 1,433 ⟶ 1,601:
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.
<
import "fmt"
Line 1,466 ⟶ 1,634:
return i * i
}))
}</
{{out}}
<pre>
Line 1,480 ⟶ 1,648:
Print each value in a list
<
Create a new list containing the squares of another list
<
=={{header|Haskell}}==
Line 1,489 ⟶ 1,657:
===List===
{{works with|GHC}}
<
let values = [1..10]
map square values</
Using list comprehension to generate a list of the squared values
<
More directly
<
Or with one less layer of monadic wrapping
<
Using function composition to create a function that will print the squares of a list
<
printSquares values</
===Array===
{{works with|GHC|7.10.3}}
<
square :: Int -> Int
Line 1,517 ⟶ 1,685:
main :: IO ()
main = print $ fmap square values</
{{Out}}
<pre>array (1,10) [(1,1),(2,4),(3,9),(4,16),(5,25),(6,36),(7,49),(8,64),(9,81),(10,100)]</pre>
=={{header|Guish}}==
{{works with|guish|2.5.1}}
<syntaxhighlight lang="guish">
# applies add2 (adds 2) to each element
add2 = {
return add(@1, 2)
}
l = {1, 2, 3, 4, 5, 6, 7}
puts each(add2, flat(@l))
</syntaxhighlight>
=={{header|Icon}} and {{header|Unicon}}==
<
local lst
lst := [10, 20, 30, 40]
Line 1,530 ⟶ 1,709:
procedure callback(p,arg)
return p(" -> ", arg)
end</
=={{header|IDL}}==
Line 1,536 ⟶ 1,715:
Hard to come up with an example that isn't completely contrived. IDL doesn't really distinguish between a scalar and an array; thus
<
will yield a scalar if <tt>a</tt> is scalar or a vector if <tt>a</tt> is a vector or an n-dimensional array if <tt>a</tt> is an n-dimensional array
=={{header|Insitux}}==
<syntaxhighlight lang="insitux">; apply a named function
(map inc [1 2 3 4])</syntaxhighlight>
<syntaxhighlight lang="insitux">; apply a parameterised closure
(map (fn x (+ x 1)) [1 2 3 4])</syntaxhighlight>
<syntaxhighlight lang="insitux">; apply a non-parameterised closure
(map #(+ % 1) [1 2 3 4])</syntaxhighlight>
<syntaxhighlight lang="insitux">; apply an explicit partial closure
(map @(+ 1) [1 2 3 4])</syntaxhighlight>
<syntaxhighlight lang="insitux">; apply an implicit partial closure
(map (+ 1) [1 2 3 4])</syntaxhighlight>
=={{header|Io}}==
<
=={{header|J}}==
'''Solution''':
<
'''Example''':
<
array =: 1 2 3 4 5
callback"_1 array
1 4 9 16 25</
But note that this is a trivial example since <code>*: 1 2 3 4 5</code> would get the same result. Then again, this is something of a trivial exercise in J since all of J is designed around the idea of applying functions usefully to arrays.
=={{header|Jakt}}==
<syntaxhighlight lang="jakt">
fn map<T, U>(anon array: [T], function: fn(anon x: T) -> U) throws -> [U] {
mut result: [U] = []
result.ensure_capacity(array.size())
for item in array {
result.push(value: function(item))
}
return result
}
fn main() {
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let array_squared = map(array, function: fn(anon n: i64) => n * n)
println("{}", array_squared)
}
</syntaxhighlight>
{{out}}
<pre>
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
</pre>
=={{header|Java}}==
Line 1,563 ⟶ 1,782:
while the <code>IntToInt</code> is used to replace the array values.
<
interface IntConsumer {
Line 1,607 ⟶ 1,826:
});
}
}</
Using Java 8 streams:
{{works with|Java|8}}
<
public class ArrayCallback {
Line 1,628 ⟶ 1,847:
System.out.println("sum: " + sum);
}
}</
=={{header|JavaScript}}==
===ES3===
<
var ret = [];
for (var i = 0; i < a.length; i++) {
Line 1,641 ⟶ 1,860:
}
map([1, 2, 3, 4, 5], function(v) { return v * v; });</
===ES5===
<
===ES6===
<
The result is always:
Line 1,654 ⟶ 1,873:
=={{header|Joy}}==
<
=={{header|jq}}==
<
map(exp) # exponentiate each item in the input list
Line 1,671 ⟶ 1,890:
# Elementwise operation
[.[] + 1 ] # add 1 to each element of the input array
</
<
[0, 1 , 10]
[1,2,11]</
=={{header|Jsish}}==
<
;[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; });
Line 1,684 ⟶ 1,903:
[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; }) ==> [ 1, 4, 9, 16, 25 ]
=!EXPECTEND!=
*/</
{{out}}
Line 1,692 ⟶ 1,911:
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
@show [n ^ 2 for n in numbers] # list comprehension
Line 1,699 ⟶ 1,918:
@show [n * n for n in numbers] # no need for a function,
@show numbers .* numbers # element-wise operation
@show numbers .^ 2 # includes .+, .-, ./, comparison, and bitwise operations as well</
=={{header|Kotlin}}==
<
val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // build
val function = { i: Int -> i * i } // function to apply
val list = array.map { function(it) } // process each item
println(list) // print results
}</
{{out}}
<pre>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</pre>
=={{header|Klingphix}}==
<
( 1 2 3 4 ) [dup *] map
Line 1,718 ⟶ 1,937:
pstack
" " input</
{{out}}
<pre>((1, 4, 9, 16))</pre>
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{A.map {lambda {:x} {* :x :x}} {A.new 1 2 3 4 5 6 7 8 9 10}}
-> [1,4,9,16,25,36,49,64,81,100]
</syntaxhighlight>
=={{header|Lang}}==
<syntaxhighlight lang="lang">
&arr = fn.arrayGenerateFrom(fn.inc, 10)
fn.println(&arr)
fn.arrayMap(&arr, fn.combC(fn.pow, 2))
fn.println(&arr)
</syntaxhighlight>
{{out}}
<pre>
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
</pre>
=={{header|Lang5}}==
<
[1 2 3 4 5] square . "\n" .
[1 2 3 4 5] 'square apply . "\n" .</
=={{header|langur}}==
<
{{out}}
Line 1,740 ⟶ 1,972:
=={{header|Lasso}}==
<
local(
Line 1,751 ⟶ 1,983:
}
#mycube</
-> array(1, 8, 27, 64, 125)
=={{header|Lisaac}}==
<
+ b : {INTEGER;};
Line 1,768 ⟶ 2,000:
};
a.foreach b;</
=={{header|Logo}}==
<
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</
=={{header|Lua}}==
Say we have an array:
<
A map function for this would be
<
local result = {}
for k,v in ipairs(data) do
Line 1,789 ⟶ 2,021:
end
return result
end</
Together with our array and a square function this yields:
<
print(unpack( map(myFunc, myArray) ))
--> 1 4 9 16 25</
If you used pairs() instead of ipairs(), this would even work on a hash table in general.
However, remember that hash table do not have an implicit ordering on their elements, like arrays do,
Line 1,800 ⟶ 2,032:
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
a=(1,2,3,4,5)
b=lambda->{
Line 1,828 ⟶ 2,060:
Print s=>sum=115
</syntaxhighlight>
=={{header|M4}}==
<
define(`_arg1', `$1')dnl
define(`_foreach', `ifelse(`$2', `()', `',
Line 1,839 ⟶ 2,071:
dnl
define(`z',`eval(`$1*2') ')dnl
apply(`(1,2,3)',`z')</
{{Out}}
Line 1,849 ⟶ 2,081:
For lists and sets, which in Maple are immutable, a new object is returned.
Either the built-in procedure map, or the short syntax of a trailing tilde (~) on the applied operator may be used.
<syntaxhighlight lang="maple">
> map( sqrt, [ 1.1, 3.2, 5.7 ] );
[1.048808848, 1.788854382, 2.387467277]
Line 1,861 ⟶ 2,093:
> (x -> x + 1)~( { 1, 3, 5 } );
{2, 4, 6}
</syntaxhighlight>
For Arrays (Vectors, Matrices, etc.) both map and trailing tilde also work, and by default create a new object, leaving the input Array unchanged.
<syntaxhighlight lang="maple">
> a := Array( [ 1.1, 3.2, 5.7 ] );
a := [1.1, 3.2, 5.7]
Line 1,878 ⟶ 2,110:
> a;
[1.1, 3.2, 5.7]
</syntaxhighlight>
However, since these are mutable data structures in Maple, it is possible to use map to modify its input according to the applied procedure.
<syntaxhighlight lang="maple">
> map[inplace]( sqrt, a );
[1.048808848, 1.788854382, 2.387467277]
Line 1,886 ⟶ 2,118:
> a;
[1.048808848, 1.788854382, 2.387467277]
</syntaxhighlight>
The Array a has been modified.
It is also possible to pass additional arguments to the mapped procedure.
<syntaxhighlight lang="maple">
> map( `+`, [ 1, 2, 3 ], 3 );
[4, 5, 6]
</syntaxhighlight>
Passing additional arguments *before* the arguments from the mapped data structure is achieved using map2, or the more general map[n] procedure.
<syntaxhighlight lang="maple">
> map2( `-`, 5, [ 1, 2, 3 ] );
[4, 3, 2]
Line 1,901 ⟶ 2,133:
> map[2]( `/`, 5, [ 1, 2, 3 ] );
[5, 5/2, 5/3]
</syntaxhighlight>
=={{header|Mathematica}}//{{header|Wolfram Language}}==
<
Map[Function[#*#], {1, 2, 3, 4}]
Map[((#*#)&,{1,2,3,4}]
Map[Function[w,w*w],{1,2,3,4}]</
=={{header|MATLAB}}==
Line 1,913 ⟶ 2,145:
Example:
For both of these function the first argument is a function handle for the function we would like to apply to each element. The second argument is the array whose elements are modified by the function. The function can be any function, including user defined functions.
<
array =
Line 1,947 ⟶ 2,179:
Column 5
-3.380515006246586</
=={{header|Maxima}}==
<
map(sin, [1, 2, 3, 4]);
Line 1,957 ⟶ 2,189:
/* for matrices */
matrixmap(sin, matrix([1, 2], [2, 4]));</
=={{header|min}}==
{{works with|min|0.19.3}}
<
(1 2 3 4 5) 'sqrt map ; collect return values</
=={{header|Modula-3}}==
<
IMPORT IO, Fmt;
Line 1,990 ⟶ 2,222:
BEGIN
Map(sample, NUMBER(sample), callback);
END Callback.</
=={{header|Nanoquery}}==
<
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Line 2,005 ⟶ 2,237:
// display the squared list
println numbers</
{{out}}
<pre>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Line 2,012 ⟶ 2,244:
=={{header|Nemerle}}==
The <tt>Nemerle.Collections</tt> namespace defines the methods <tt>Iter()</tt> (if the function applied is <tt>void</tt>) and <tt>Map()</tt> (if the function applied returns a value).
<
def squares = seq.Map(x => x*x);</
=={{header|NetLogo}}==
<syntaxhighlight lang="netlogo">
;; NetLogo “anonymous procedures”
;; stored in a variable, just to show it can be done.
let callback [ [ x ] x * x ]
show (map callback [ 1 2 3 4 5 ])
</syntaxhighlight>
=={{header|NewLISP}}==
<
(1 4 9 16)
</syntaxhighlight>
=={{header|NGS}}==
<syntaxhighlight lang="ngs">{
[1, 2, 3, 4, 5].map(F(x) x*x)
}</
=={{header|Nial}}==
<
=1 4 9 16</
=={{header|Nim}}==
<syntaxhighlight lang="nim">
from std/sequtils import apply
let arr = @[1,2,3,4]
arr.apply proc(some: int) = echo(some, " squared = ", some*some)</syntaxhighlight>
{{Out}}
Line 2,041 ⟶ 2,283:
3 squared = 9
4 squared = 16
=={{header|Nutt}}==
<syntaxhighlight lang="Nutt">
module main
imports native.io.output.say
operator |> (arr:Array,f:Procedure):Array==>{f(x) of x |-> arr}
say({0,1,2,3,4,5}|>a==>a+2)//|{2,3,4,5,6,7}
end
</syntaxhighlight>
=={{header|Oberon-2}}==
{{Works with|oo2x}}
<
MODULE ApplyCallBack;
IMPORT
Line 2,133 ⟶ 2,388:
Init(a);r := Map3(Fun3,a);Show(r^);
END ApplyCallBack.
</syntaxhighlight>
{{Out}}
<pre>
Line 2,142 ⟶ 2,397:
=={{header|Objeck}}==
<
use Structure;
Line 2,164 ⟶ 2,419:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
This function is part of the standard library:
<syntaxhighlight lang
Usage example:
<
let values = Array.init 10 ((+) 1);;
Array.map square values;;</
Or with lists (which are more typical in OCaml):
<
List.map square values;;</
Use <tt>iter</tt> if the applied function does not return a value.
<
<
with partial application we can also write:
<
<
=={{header|Octave}}==
Line 2,194 ⟶ 2,449:
Almost all the built-in can operate on each element of a vector or matrix; e.g. sin([pi/2, pi, 2*pi]) computes the function sin on pi/2, pi and 2*pi (returning a vector). If a function does not accept vectors/matrices as arguments, the <tt>arrayfun</tt> can be used.
<
e = x^2 + exp(-1/(y+1));
endfunction
Line 2,200 ⟶ 2,455:
% f([2,3], [1,4]) gives and error, but
arrayfun(@f, [2, 3], [1,4])
% works</
(The function <tt>f</tt> can be rewritten so that it can accept vectors as argument simply changing operators to their dot ''relatives'': <code>e = x.^2 + exp(-1 ./ (y.+1))</code>)
=={{header|Odin}}==
<syntaxhighlight lang="odin">package main
import "core:slice"
import "core:fmt"
squared :: proc(x: int) -> int {
return x * x
}
main :: proc() {
arr := []int{1, 2, 3, 4, 5}
res := slice.mapper(arr, squared)
fmt.println(res) // prints: [1, 4, 9, 16, 25]
}</syntaxhighlight>
=={{header|Oforth}}==
apply allows to perform a function on all elements of a list :
<
map regroups all results into a new list :
<
=={{header|Ol}}==
Apply custom callback (lambda) to every element of list.
<
(for-each
(lambda (element)
Line 2,219 ⟶ 2,492:
'(1 2 3 4 5))
; ==> 12345
</syntaxhighlight>
=={{header|ooRexx}}==
ooRexx doesn't directly support callbacks on array items, but this is pretty easy to implement using Routine objects.
<
new = map(start, .routines~reversit)
call map new, .routines~sayit
Line 2,246 ⟶ 2,519:
use arg string
say string
return .true -- called as a function, so a result is required</
{{out}}
<pre>kciR
Line 2,255 ⟶ 2,528:
=={{header|Order}}==
Both sequences and tuples support the usual map operation seen in many functional languages. Sequences also support <code>8seq_for_each</code>, and a few variations, which returns <code>8nil</code>.
<
ORDER_PP( 8tuple_map(8fn(8X, 8times(8X, 8X)), 8tuple(1, 2, 3, 4, 5)) )
Line 2,264 ⟶ 2,537:
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</
=={{header|Oz}}==
<
fun{Square A}
A*A
Line 2,279 ⟶ 2,552:
%% apply a FUNCTION to every element
Result = {Map Lst Square}
{Show Result}</
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.2 and above}}
<
apply(callback, [1,2,3,4,5])</
This should be contrasted with <code>call</code>:
<
which is equivalent to <code>callback(1, 2, 3, 4, 5)</code> rather than <code>[callback(1), callback(2), callback(3), callback(4), callback(5)]</code>.
Line 2,294 ⟶ 2,567:
=={{header|Perl}}==
<
my @a = (1, 2, 3, 4, 5);
Line 2,323 ⟶ 2,596:
# filter an array
my @e = grep { $_ % 2 == 0 } @a; # @e is now (2, 4)</
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"0.8.2"</span><span style="color: #0000FF;">)</span>
Line 2,335 ⟶ 2,608:
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},</span><span style="color: #000000;">add1</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
<pre>
Line 2,349 ⟶ 2,622:
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Apply_a_callback_to_an_array
by Galileo, 05/2022 #/
include ..\Utilitys.pmt
def
1 +
enddef
Line 2,366 ⟶ 2,635:
enddef
( 1 2 3 ) dup
getid square map
pstack</syntaxhighlight>
{{out}}
<pre>
[[2, 3, 4], [1, 4, 9]]
=== Press any key to exit ===</pre>
=={{header|PHP}}==
<
{
return($n * $n * $n);
Line 2,389 ⟶ 2,655:
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);</
=={{header|Picat}}==
Picat doesn't support anonymous (lambda) functions so the function must be defined in the program to be used by - say - map/2.
There are - however - quite a few ways without proper lambdas, using map/2, apply/2, or list comprehensions.
<syntaxhighlight lang="picat">go =>
L = 1..10,
% Using map/2 in different ways
println(L.map(fun)),
println(map(L,fun)),
println(map(fun,L)),
% List comprehensions
println([fun(I) : I in L]),
% Using apply/2
println([apply(fun,I) : I in L]),
% And using list comprehension with the function directly.
println([I*I : I in L]),
nl.
% Some function
fun(X) = X*X.
</syntaxhighlight>
{{trans|Prolog}}
This variant is inspired by the Prolog solution (using assert/1 to define a predicate) and shows the integration with Picat's underlying B-Prolog engine.
Picat does not support assert/1 directly, so one have to do the assert/1 in the bp module space (the module/space for the B-Prolog engine). To call the defined predicate, one must prepend the predicate name with "bp.".
Note that fun2/2 is not a function so map/2 or apply/2 cannot be used here.
<syntaxhighlight lang="picat">go2 =>
L = 1..10,
% Define the predicate _in the bp space_.
bp.assert( $(fun2(X,Y) :- Y is X*X) ),
% Use bp.fun2 to call the function.
println([B : A in L, bp.fun2(A,B)]),
nl.
</syntaxhighlight>
Using this technique one can do quite much "real" Prolog stuff even though Picat doesn't support it directly. However, one should be careful with this approach since it can sometimes be confusing and it doesn't work in all cases.
=={{header|PicoLisp}}==
<
1
2
Line 2,407 ⟶ 2,717:
: (mapcar if '(T NIL T NIL) '(1 2 3 4) '(5 6 7 8)) # Conditional function
-> (1 6 3 8)</
=={{header|Pike}}==
<
{
return n*n*n;
Line 2,417 ⟶ 2,727:
array(int) a = ({ 1,2,3,4,5 });
array(int) b = cube(a[*]); // automap operator
array(int) c = map(a, cube); // conventional map function</
=={{header|PL/I}}==
<
x = sqrt(x);
x = sin(x);</
=={{header|PL/SQL}}==
PL/SQL doesn't have callbacks, though we can pass around an object and use its method to simulate one. Further, this callback method can be defined in an abstract class that the mapping function will expect.
<
create or replace
TYPE callback AS OBJECT (
Line 2,501 ⟶ 2,811:
PKG_CALLBACK.TEST_CALLBACK();
END;
/</
=={{header|Pop11}}==
<
define proc(x);
printf(x*x, '%p,');
Line 2,514 ⟶ 2,824:
;;; Apply procedure to array
appdata(ar, proc);</
If one wants to create a new array consisting of transformed values then procedure mapdata may be more convenient.
Line 2,520 ⟶ 2,830:
=={{header|PostScript}}==
The <code>forall</code> operator applies a procedure to each element of an array, a packed array or a string.
<
In this case the respective square numbers for the elements are printed.
To create a new array from the results above code can simply be wrapped in <code>[]</code>:
<
{{libheader|initlib}}
<
[1 2 3 4 5] {dup *} map
</syntaxhighlight>
=={{header|PowerShell}}==
This can be done in PowerShell with the <code>ForEach-Object</code> cmdlet which applies a scriptblock to each element of an array:
<
To recreate a ''map'' function, found in other languages the same method applies:
<
$a | ForEach-Object $s
}
map (1..5) { $_ * $_ }</
=={{header|Prolog}}==
Prolog doesn't have arrays, but we can do it with lists. This can be done in the console mode.
<
true.
?- maplist(fun, [1,2,3,4,5], L).
L = [2,4,6,8,10].
</syntaxhighlight>
=={{header|PureBasic}}==
<
Protected n.i
For n = 0 To ArraySize(param())
Line 2,563 ⟶ 2,873:
Next
Cube(AnArray()) </
=={{header|Python}}==
<
return n * n
Line 2,583 ⟶ 2,893:
import itertools
isquares2 = itertools.imap(square, numbers) # iterator, lazy</
To print squares of integers in the range from 0 to 9, type:
<
Or:
<
Result:
<
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
'Task
'Take a combined set of elements and apply a function to each element.
'UDT
Type Friend
Names As String * 8
Surnames As String * 8
Age As Integer
End Type
Dim Friends(1 To 6) As Friend
Restore
FillArray
SearchForAdult Friends(), LBound(friends), UBound(friends)
End
Data "John","Beoz",13,"Will","Strange",22
Data "Arthur","Boile",16,"Peter","Smith",21
Data "Tom","Parker",14,"Tim","Wesson",24
Sub FillArray
Shared Friends() As Friend
Dim indeX As Integer
For indeX = LBound(friends) To UBound(friends) Step 1
Read Friends(indeX).Names, Friends(indeX).Surnames, Friends(indeX).Age
Next
End Sub
Sub SearchForAdult (F() As Friend, Min As Integer, Max As Integer)
Dim Index As Integer
Print "Friends with more than 18 years old"
For Index = Min To Max Step 1
If F(Index).Age > 18 Then Print F(Index).Names; " "; F(Index).Surnames; " "; F(Index).Age
Next Index
End Sub
</syntaxhighlight>
=={{header|Quackery}}==
Line 2,595 ⟶ 2,945:
As a dialogue in the Quackery shell (REPL), applying the word <code>cubed</code> to the nest <code>[ 1 2 3 4 5 6 7 8 9 10 ]</code>, first treating the nest as a list, then as an array.
<
...
Line 2,617 ⟶ 2,967:
...
Stack: [ 1 8 27 64 125 216 343 512 729 1000 ]</
=={{header|R}}==
Many functions can take advantage of implicit vectorisation, e.g.
<
elements <- 1:5
cubes <- cube(elements)</
Explicit looping over array elements is also possible.
<
for(i in seq_along(cubes))
{
cubes[i] <- cube(elements[i])
}</
Loop syntax can often simplified using the [http://stat.ethz.ch/R-manual/R-patched/library/base/html/apply.html *apply] family of functions.
<
cubes <- sapply(elements2, cube)</
In each case above, the value of 'cubes' is
1 8 27 64 125
Line 2,638 ⟶ 2,988:
=={{header|Racket}}==
<
#lang racket
Line 2,646 ⟶ 2,996:
;; the usual functional `map'
(vector-map sqr #(1 2 3 4 5))
</syntaxhighlight>
=={{header|Raku}}==
Line 2,652 ⟶ 3,002:
{{works with|Rakudo|2015.10-11}}
<syntaxhighlight lang="raku"
my @array = 1 .. 5;
Line 2,671 ⟶ 3,021:
# we neither need a variable for the array nor for the function
say [1,2,3]>>.&({ $^x + 1});
</syntaxhighlight>
=={{header|Raven}}==
<
[1 2 3 4 5] each dup * print</
<
group [1 2 3 4 5] each
dup *
list</
=={{header|REBOL}}==
<
Title: "Array Callback"
URL: http://rosettacode.org/wiki/Apply_a_callback_to_an_Array
Line 2,708 ⟶ 3,058:
print [crlf "Applying native function with 'map':"]
assert [[2 4 6] = map :square-root [4 16 36]]</
{{Out}}
Line 2,724 ⟶ 3,074:
Retro provides a variety of array words. Using these to multiply each value in an array by 10 and display the results:
<
=={{header|REXX}}==
<
numeric digits 100 /*be able to display some huge numbers.*/
parse arg # . /*obtain an optional value from the CL.*/
Line 2,749 ⟶ 3,099:
/*──────────────────────────────────────────────────────────────────────────────────────*/
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</
{{out|output|text= when using the default input:}}
<pre>
Line 2,784 ⟶ 3,134:
=={{header|Ring}}==
<
for x in [1,2,3,4,5]
x = x*x
next
</syntaxhighlight>
=={{header|RLaB}}==
Line 2,804 ⟶ 3,154:
Consider an example:
<syntaxhighlight lang="rlab">
>> x = rand(2,4)
0.707213207 0.275298961 0.396757763 0.232312312
Line 2,811 ⟶ 3,161:
0.649717845 0.271834652 0.386430003 0.230228332
0.213952984 0.205601224 0.536006923 0.617916954
</syntaxhighlight>
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.
<syntaxhighlight lang="rlab">
x = rand(2,4);
y = zeros(2,4);
Line 2,826 ⟶ 3,176:
}
}
</syntaxhighlight>
Line 2,833 ⟶ 3,183:
function 'members' which returns a string vector with the names of the elements of the list.
<syntaxhighlight lang="rlab">
x = <<>>;
for (i in 1:9)
Line 2,845 ⟶ 3,195:
y.[i] = sin( x.[i] );
}
</syntaxhighlight>
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
≪ → array func
≪ array 0 CON
1 array SIZE FOR j
j array j GET func EVAL PUT
NEXT
≫ ≫
´MAP’ STO
[1,2,3,4,5,6,7,8,9] ≪ SQ ≫ MAP
{{out}}
<pre>
1: [ 1 4 9 16 25 36 49 64 81 ]
</pre>
=={{header|Ruby}}==
You could use a traditional "for i in arr" approach like below:
<
puts i**2
end</
Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk)
<
To create a new array of each value squared
<
=={{header|Rust}}==
<
println!("{}", n);
}
Line 2,869 ⟶ 3,235:
a = [1, 2, 3, 4, 5];
let _: Vec<_> = a.into_iter().map(echo).collect();
}</
=={{header|Salmon}}==
Line 2,875 ⟶ 3,241:
These examples apply the square function to a list of the numbers from 0 through 9 to produce a new list of their squares, then iterate over the resulting list and print the squares.
<
(comprehend(x; list) (to_apply(x)));
Line 2,881 ⟶ 3,247:
iterate(x; apply([0...9], square))
x!;</
With short identifiers:
<
fun apply(list, ageless to_apply)
Line 2,893 ⟶ 3,259:
iter(x; apply([0...9], square))
x!;</
With the numbers given as a list of individual elements:
<
(comprehend(x; list) (to_apply(x)));
Line 2,903 ⟶ 3,269:
iterate(x; apply([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], square))
x!;</
=={{header|Sather}}==
<
do_something(i:INT):INT is
return i * i;
Line 2,917 ⟶ 3,283:
loop #OUT + a.elt! + "\n"; end;
end;
end;</
=={{header|Scala}}==
<
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
<syntaxhighlight lang
Same for an array
<
a.foreach {i => println(i)}
a.foreach(println(_)) '' // same as previous line''</
Or for an externally defined function:
<
l.foreach(doSomething)</
There is also a ''for'' syntax, which is internally rewritten to call foreach. A foreach method must be defined on ''a''
<
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)
<
Or the equivalent ''for'' syntax, with the additional keyword ''yield'', map is called instead of foreach
<
=={{header|Scheme}}==
<
(define x #(1 2 3 4 5))
(map square (vector->list x))</
A single-line variation
<
For completeness, the <tt>map</tt> function (which is R5RS standard) can be coded as follows:
<
(if (null? L)
L
(cons (f (car L)) (map f (cdr L)))))</
=={{header|SenseTalk}}==
<
put each item in [1,2,3,5,9,14,24] squared
Line 2,965 ⟶ 3,331:
to handle myFunc of num
return 2*num + 1
end myFunc</
Output:
<
(3,5,7,11,19,29,49)</
=={{header|Sidef}}==
Defining a callback function:
<
The function will get called for each element:
<
Same as above, but with the function inlined:
<
For creating a new array, we can use the Array.map method:
<
=={{header|Simula}}==
<
! APPLIES A CALLBACK FUNCTION TO AN ARRAY ;
Line 3,005 ⟶ 3,371:
FOR I := 1 STEP 1 UNTIL 5 DO OUTFIX(A(I), 2, 8); OUTIMAGE;
END.</
{{out}}
<pre>
Line 3,012 ⟶ 3,378:
=={{header|Slate}}==
<
=={{header|Smalltalk}}==
<
You can tell symbols how to react to the <tt>value:</tt> message, and then write ²:
<
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.:
<
=={{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:
<
foreach(numbers, function(idx, num) {
print(num);
});</
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:
<
let doubled = map(dict, function(key, val) {
return val * 2;
});</
=={{header|SQL PL}}==
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
<
--#SET TERMINATOR @
Line 3,071 ⟶ 3,437:
END;
END @
</syntaxhighlight>
Output:
<pre>
Line 3,084 ⟶ 3,450:
=={{header|Standard ML}}==
<syntaxhighlight lang="standard ml">
map f l
</syntaxhighlight>
i.e.
<syntaxhighlight lang="standard ml">
map (fn x=>x+1) [1,2,3];; (* [2,3,4] *)
</syntaxhighlight>
=={{header|Stata}}==
There is no 'map' function in Mata, but it's easy to implement. Notice that you can only pass functions that are written in Mata, no builtin ones. For instance, the trigonometric functions (cos, sin) or the exponential are builtin. To pass a builtin function to another function, one needs to write a wrapper in Mata. See also Stata help about '''[https://www.stata.com/help.cgi?m2_pointers pointers]''' and '''[https://www.stata.com/help.cgi?m2_ftof passing functions to functions]'''. There are two versions of the function: one to return a numeric array, another to return a string array.
<
nr = rows(a)
nc = cols(a)
Line 3,117 ⟶ 3,483:
function square(x) {
return(x*x)
}</
'''Output'''
Line 3,130 ⟶ 3,496:
=={{header|SuperCollider}}==
Actually, there is a builtin <tt>squared</tt> operator:
<
Anything that is a <tt>Collection</tt> can be used with <tt>collect</tt>:
<
[[List Comprehension#SuperCollider|List comprehension]] combined with a higher-order function can also be used:
<
var map = { |fn, xs|
all {: fn.value(x), x <- xs };
};
map.value(square, [1, 2, 3]);</
=={{header|Swift}}==
<
return n * n
}
Line 3,153 ⟶ 3,519:
let squares1b = numbers.map { $0 * $0 } // map method on array with anonymous function and unnamed parameters
let isquares1 = numbers.lazy.map(square) // lazy sequence</
=={{header|Tailspin}}==
<
def numbers: [1,3,7,10];
Line 3,171 ⟶ 3,537:
[ $numbers... -> $ * $ ] -> !OUT::write
[ $numbers... -> cube ] -> !OUT::write
</syntaxhighlight>
=={{header|Tcl}}==
If I wanted to call "<tt>myfunc</tt>" on each element of <tt>dat</tt> and <tt>dat</tt> were a list:
<
myfunc $var
}</
This does not retain any of the values returned by <tt>myfunc</tt>.
if <tt>dat</tt> were an (associative) array, however:
<
myfunc $dat($name)
}</
More functional, with a simple <code>map</code> function:
<
set res {}
foreach e $list {lappend res [$f $e]}
Line 3,195 ⟶ 3,561:
% map square {1 2 3 4 5}
1 4 9 16 25</
=={{header|TI-89 BASIC}}==
<
Define foreach(fe_cname,fe_list) = Prgm
Local fe_i
Line 3,215 ⟶ 3,581:
foreach("callback", {1,2,3,4,5})
Disp map("√", {1,2,3,4,5})</
{{Out}}
Line 3,229 ⟶ 3,595:
JavaScript alike:
<
a.map(function(v) { return v * v; })
</syntaxhighlight>
Using short form of lambda notation:
<
a.map( :v: v*v );
</syntaxhighlight>
=={{header|Toka}}==
<
{
value| array fn |
Line 3,256 ⟶ 3,622:
( Add 1 to each item in the array )
a 5 [ 1 + ] map-array</
=={{header|TorqueScript}}==
Line 3,264 ⟶ 3,630:
Callbacks:
<syntaxhighlight lang="torquescript">
function map(%array,%arrayCount,%function)
{
Line 3,273 ⟶ 3,639:
}
}
</syntaxhighlight>
Now to set up an array:
<syntaxhighlight lang="torquescript">
$array[0] = "Hello.";
$array[1] = "Hi.";
$array[2] = "How are you?";
</syntaxhighlight>
Now to call the function correctly:
<syntaxhighlight lang="torquescript">
map("$array",3,"echo");
</syntaxhighlight>
Which should result in:
<syntaxhighlight lang="torquescript">
=> Hello.
Line 3,297 ⟶ 3,663:
=> How are you?
</syntaxhighlight>
=={{header|TXR}}==
Line 3,303 ⟶ 3,669:
Print 1 through 10 out of a vector, using <code>prinl</code> the callback, right from the system shell command prompt:
<
1
2
Line 3,313 ⟶ 3,679:
8
9
10</
<code>mapdo</code> is like <code>mapcar</code> but doesn't accumulate a list, suitable for imperative programming situations when the function is invoked to perform a side effect.
Line 3,321 ⟶ 3,687:
=={{header|uBasic/4tH}}==
We cannot transfer the array address, since uBasic/4tH has only got one, but we can transfer the function pointer and size.
<syntaxhighlight lang="text">S = 5 ' Size of the array
For x = 0 To S - 1 ' Initialize array
Line 3,382 ⟶ 3,748:
Push 10000+((Pop()*-(Pop()/2))/10000)
If a@ Then Push -Pop() ' Result is directly transferred
Return ' through the stack</
{{out}}
<pre>SQRT(1) = 1.0000
Line 3,400 ⟶ 3,766:
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
<
map_command=$1
shift
Line 3,406 ⟶ 3,772:
}
list=1:2:3
(IFS=:; map echo $list)</
{{works with|ksh93}}
{{works with|pdksh}}
{{works with|zsh}}
<
typeset command=$1
shift
Line 3,417 ⟶ 3,783:
}
set -A ary 1 2 3
map print "${ary[@]}"</
{{works with|zsh}}
<
a=(1 2 3)
map print $a</
=={{header|Ursala}}==
The * is a built-in map operator.
This example shows a map of the successor function over a list of natural numbers.
<
#cast %nL
demo = successor* <325,32,67,1,3,7,315></
{{Out}}
<pre>
Line 3,439 ⟶ 3,805:
=={{header|V}}==
apply squaring (dup *) to each member of collection
<
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 3,463 ⟶ 3,829:
Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)
End If
End Function</
{{out}}
<pre>0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55</pre>
Line 3,472 ⟶ 3,838:
=====Implementation=====
<syntaxhighlight lang="vb">
class callback
dim sRule
Line 3,489 ⟶ 3,855:
end function
end class
</syntaxhighlight>
=====Invocation=====
<syntaxhighlight lang="vb">
dim a1
dim cb
Line 3,506 ⟶ 3,872:
cb.applyto a1
wscript.echo join( a1, ", " )
</syntaxhighlight>
{{Out}}
Line 3,519 ⟶ 3,885:
The result of evaluating the string will be the new value.
The list/dictionary is modified in place.
<
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)')</
{{Out}}
Line 3,541 ⟶ 3,907:
and System.Linq.Enumerable.ToArray(Of TSource)(IEnumerable(Of TSource)) eagerly converts the enumerable to an array.
<
Function OneMoreThan(i As Integer) As Integer
Return i + 1
Line 3,565 ⟶ 3,931:
Array.ForEach(resultArr, AddressOf Console.WriteLine)
End Sub
End Module</
{{out}}
Line 3,575 ⟶ 3,941:
=={{header|Vorpal}}==
Given and array, A, and a function, F, mapping F over the elements of A is simple:
<syntaxhighlight 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.
<
=={{header|Wart}}==
<
{{Out}}
Line 3,591 ⟶ 3,957:
=={{header|WDTE}}==
<
let s => import 'stream';
Line 3,599 ⟶ 3,965:
-> s.map (* 2)
-> s.collect
;</
In WDTE, mapping can be accomplished using the <code>stream</code> module. Streams are essentially lazy iterators. The <code>arrays</code> module provides a function for creating a stream from an array, and then the <code>stream</code> module's functions can be used to perform a map operation. <code>collect</code> runs the iteration, collecting the elements yielded in a new array.
=={{header|Wren}}==
<
arr = arr.map { |x| x * 2 }.toList
arr = arr.map(Fn.new { |x| x / 2 }).toList
arr.each { |x| System.print(x) }</
{{out}}
Line 3,619 ⟶ 3,985:
=={{header|XBS}}==
<
set newArr:array = [];
foreach(k,v as arr){
newArr
}
send newArr;
}
set arr:array = [1,2,3,4,5];
set result:array = map(arr,func(v){
send v*2;
});
log(arr
log(result
{{out}}
<pre>
Line 3,641 ⟶ 4,007:
=={{header|Yabasic}}==
<
local i
Line 3,671 ⟶ 4,037:
print t(i), "\t";
next i
print</
=={{header|Yacas}}==
<
MapSingle(Sin, {1,2,3,4})
MapSingle({{x}, x^2}, {1,2,3,4})
</syntaxhighlight>
=={{header|Z80 Assembly}}==
<
byte &01,&02,&03,&04,&05
Array_End:
Line 3,695 ⟶ 4,061:
inc (hl)
inc hl ;next entry in array
djnz bar</
{{out}}
Line 3,703 ⟶ 4,069:
</pre>
=={{header|Zig}}==
<syntaxhighlight lang="zig">pub fn main() !void {
var array = [_]i32{1, 2, 3};
apply(@TypeOf(array[0]), array[0..], func);
}
fn apply(comptime T: type, a: []T, f: fn(T) void) void {
for (a) |item| {
f(item);
}
}
fn func(a: i32) void {
const std = @import("std");
std.debug.print("{d}\n", .{a-1});
}</syntaxhighlight>
=={{header|zkl}}==
<
{{Out}}
<pre>
Line 3,712 ⟶ 4,094:
=={{header|zonnon}}==
<
module Main;
type
Line 3,752 ⟶ 4,134:
Write(Map(x,Power))
end Main.
</syntaxhighlight>
{{Out}}
<pre>
Line 3,759 ⟶ 4,141:
=={{header|ZX Spectrum Basic}}==
<
20 LET b$="x*x"
30 LET c$="x+x^2"
Line 3,769 ⟶ 4,151:
190 STOP
200 DATA 2,5,6,10,100
</syntaxhighlight>
{{omit from|gnuplot}}
|