Apply a callback to an array: Difference between revisions
m
syntax highlighting fixup automation
Drkameleon (talk | contribs) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
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</
Line 87:
{{trans|11l}}
The following assumes all code/data is stored/executed in RAM and is therefore mutable.
<
MOVE.W #(MyArray_End-MyArray)-1,D7 ;Len(MyArray)-1
MOVEQ #0,D0 ;sanitize D0-D2 to ensure nothing from any previous work will affect our math.
Line 104:
MyArray:
DC.B 1,2,3,4,5,6,7,8,9,10
MyArray_End:</
=={{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 120:
ACL2 does not have first-class functions; this is close, however:
<
(if (endp xs)
nil
Line 128:
(defun fn-to-apply (x)
(* x x))
</syntaxhighlight>
=={{header|ActionScript}}==
<
{
public class ArrayCallback
Line 149:
}
}
}</
=={{header|Ada}}==
{{works with|GNAT|GPL 2005}}
<
with Ada.Integer_text_IO;
Line 189:
begin
Map(Sample, Display'access);
end Call_Back_Example;</
=={{header|Aime}}==
<
map(list l, void (*fp)(object))
{
Line 210:
return 0;
}</
=={{header|ALGOL 68}}==
Line 217:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<
(
printf(($"array["g"] = "gl$, location, value))
Line 233:
[4]INT array := ( 1, 4, 9, 16 );
map(array, call back proc)
)</
{{Out}}
Line 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 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 270:
81 243 729
2187 6561 19683
</syntaxhighlight>
=={{header|AppleScript}}==
<
-- Returns a string like "arc has 3 letters"
arg & " has " & (count arg) & " letters"
Line 283:
-- to callback, then speaks the return value.
say (callback for aref)
end repeat</
If the callback would <code>set arg's contents to "something"</code>, then <code>alist</code> would be mutated.
Line 290:
For a more general implementation of '''map(function, list)''', '''foldl(function, startValue, list)''', and '''filter(predicate, list)''', we could write:
<
set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Line 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 381:
=={{header|AutoHotkey}}==
<
callback(array){
Line 390:
map(callback, array){
%callback%(array)
}</
=={{header|AWK}}==
<
4 16
5 25
1 1
2 4
3 9</
=={{header|Babel}}==
Line 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 415:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
a() = 1, 2, 3, 4, 5
PROCmap(a(), FNsqrt())
Line 431:
NEXT
ENDPROC
</syntaxhighlight>
{{Out}}
<pre>
Line 442:
=={{header|Bracmat}}==
<
= location value
. !arg:(?location,?value)
Line 470:
& mapar$(array,4,callbackFunction2)
& mapar$(array,4,callbackFunction1)
);</
{{Out}}
<pre>array[0] = 1
Line 483:
=={{header|Brat}}==
<
[:a :b :c :d :e].each { element |
p element
}</
Alternatively:
<
=={{header|C}}==
'''callback.h'''
<
#define CALLBACK_H
Line 510:
void map(int* array, int len, void(*callback)(int,int));
#endif</
'''callback.c'''
<
#include "callback.h"
Line 539:
map(array, 4, callbackFunction);
return 0;
}</
{{Out}}
Line 553:
This version uses the C# 3 lambda notation.
<
// Simplest method: LINQ, functional
int[] squares1 = intArray.Select(x => x * x).ToArray();
Line 563:
// Or, if you only want to call a function on each element, just use foreach
foreach (var i in intArray)
Console.WriteLine(i * i);</
{{works with|C sharp|C#|2.0+}}
{{works with|Visual C sharp|Visual C#|2005}}
<
static class Program
Line 601:
Console.WriteLine(value * value);
}
}</
=={{header|C++}}==
Line 607:
{{works with|g++|4.1.1}}
===C-Style Array===
<
#include <algorithm> //for_each defined here
Line 622:
return 0;
}
//prints 1 4 9 16 25</
===std::vector===
{{libheader|STL}}
<
#include <algorithm> // for_each defined here
#include <vector> // stl vector class
Line 647:
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 673:
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 699:
std::cout << std::endl;
return 0;
}</
=={{header|Clean}}==
Line 705:
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'''
<lang>[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|CLU}}==
<
% of the given array. Thanks to CLU's type parameterization,
% it will work for any type of element.
Line 780:
stream$putl(po, "\nStrings: ")
apply_to_all[string](strings, show_string)
end start_up</
{{out}}
<pre>Ints:
Line 799:
Basic implementation of a map function:
<
PROGRAM-ID. Map.
Line 821:
GOBACK
.</
=={{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 835:
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 904:
END Do;
END Callback.
</syntaxhighlight>
Execute: ^Q Callback.Do<br/>
{{Out}}
Line 933:
=={{header|Crystal}}==
Calling with a block
<
new_values = values.map do |number|
Line 939:
end
puts new_values #=> [2, 4, 6]</
Calling with a function/method
<
def double(number)
Line 953:
new_values = values.map &->double(Int32)
puts new_values #=> [2, 4, 6]</
=={{header|D}}==
<
void main() {
Line 962:
auto m = items.map!(x => x + 5)();
writeln(m);
}</
{{out}}
<pre>[6, 7, 8, 9, 10]</pre>
=={{header|Delphi}}==
<
// Declare the callback function
procedure callback(const AInt:Integer);
Line 985:
callback(myArray[i]);
end.
</syntaxhighlight>
=={{header|Dyalect}}==
<
let ys = []
for x in this when pred(x) {
Line 1,000:
var squares = arr.Select(x => x * x)
print(squares)</
=={{header|Déjà Vu}}==
There is a <code>map</code> builtin that does just this.
<
#implemented roughly like this:
Line 1,011:
# for i in lst:
# f i
# [</
{{out}}
<pre>[ 2 5 9 ]</pre>
Line 1,017:
=={{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 1,033:
returning a plain list (which is usually an array in implementation).
<
def output := [].diverge()
for item in collection {
Line 1,040:
return output.snapshot()
}
println(map(square, array))</
=={{header|EchoLisp}}==
<
(vector-map sqrt #(0 4 16 49))
→ #( 0 2 4 7)
Line 1,055:
v[2] = 4
→ #( 4 9 16)
</syntaxhighlight>
=={{header|Efene}}==
<
N * N
}
Line 1,091:
io.format("squares3 : ~p~n", [squares3(Numbers)])
}
</syntaxhighlight>
=={{header|EGL}}==
<
program ApplyCallbackToArray
Line 1,113:
return( i * i );
end
end</
=={{header|Elena}}==
ELENA 5.0 :
<
PrintSecondPower(n){ console.writeLine(n * n) }
Line 1,124:
{
new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.forEach:PrintSecondPower
}</
=={{header|Elixir}}==
<
Enum.map([1, 2, 3], fn(n) -> n * 2 end)
Enum.map [1, 2, 3], &(&1 * 2)
</syntaxhighlight>
{{Out}}
Line 1,140:
A list would be more commonly used in Erlang rather than an array.
<
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.
Line 1,150:
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.
<
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.
<
4> lists:foldl(fun(X, Sum) -> X + Sum end, 0, L).
6
</syntaxhighlight>
=={{header|ERRE}}==
Line 1,192:
PRINT
END PROGRAM
</syntaxhighlight>
This example shows how to pass a function to a procedure.
{{Out}}
Line 1,200:
=={{header|Euphoria}}==
<
-- apply a function to all elements of a sequence
sequence result
Line 1,217:
-- add1() is visible here, so we can ask for its routine id
? apply_to_all({1, 2, 3}, routine_id("add1"))
-- displays {2,3,4}</
This is also "Example 2" in the Euphoria documentation for <code>routine_id()</code>.
Note that this example will not work for multi-dimensional sequences.
Line 1,223:
=={{header|F_Sharp|F#}}==
Apply a named function to each member of the array. The result is a new array of the same size as the input.
<
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,241:
In Fantom, functions can be passed to a collection iterator, such as 'each'. 'map' is used similarly, and the results are collected into a list.
<
class Main
{
Line 1,251:
}
}
</syntaxhighlight>
{{Out}}
Line 1,265:
=={{header|FBSL}}==
'''User-defined mapping function:'''
<
FOREACH DIM e IN MyMap(Add42, {1, 2, 3})
Line 1,281:
END FUNCTION
FUNCTION Add42(n): RETURN n + 42: END FUNCTION</
{{Out}}
<pre>43 44 45
Line 1,287:
'''Standard MAP() function:'''
<
DIM languages[] = {{"English", {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}}, _
Line 1,303:
MAP(NameANumber, lang[0], 1 TO 10, lang[1])
PRINT LPAD("", 40, "-")
END SUB</
{{Out}}
<pre>The number 1 is called "one" in English
Line 1,333:
This is a word that will call a given function on each cell in an array.
<
-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,344:
{{Works with |Fortran|ISO 95 and later}}
<
contains
elemental function cube( x )
Line 1,352:
cube = x * x * x
end function cube
end module arrCallback</
<
use arrCallback
implicit none
Line 1,370:
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,386:
end do
C
end</
=={{header|FP}}==
<
& square: <1,2,3,4,5></
=={{header|FreeBASIC}}==
<
Sub PrintEx(n As Integer)
Line 1,411:
Print
Print "Press any key to quit the program"
Sleep</
{{out}}
Line 1,430:
=={{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,453:
=={{header|Futhark}}==
<
map f l
</syntaxhighlight>
e.g.
<
map (\x->x+1) [1,2,3] -- [2,3,4]
</syntaxhighlight>
or equivalently
<
map (+1) [1,2,3] -- [2,3,4]
</syntaxhighlight>
=={{header|Fōrmulæ}}==
Line 1,474:
=={{header|GAP}}==
<
b := ShallowCopy(a);
Line 1,494:
b;
# [ 1 .. 4 ]</
=={{header|Go}}==
Line 1,501:
Perhaps in contrast to Ruby, it is idiomatic in Go to use the for statement:
<
import "fmt"
Line 1,509:
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,542:
return i * i
}))
}</
{{out}}
<pre>
Line 1,556:
Print each value in a list
<
Create a new list containing the squares of another list
<
=={{header|Haskell}}==
Line 1,565:
===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,593:
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|Icon}} and {{header|Unicon}}==
<
local lst
lst := [10, 20, 30, 40]
Line 1,606:
procedure callback(p,arg)
return p(" -> ", arg)
end</
=={{header|IDL}}==
Line 1,612:
Hard to come up with an example that isn't completely contrived. IDL doesn't really distinguish between a scalar and an array; thus
<
will yield a scalar if <tt>a</tt> is scalar or a vector if <tt>a</tt> is a vector or an n-dimensional array if <tt>a</tt> is an n-dimensional array
=={{header|Io}}==
<
=={{header|J}}==
'''Solution''':
<syntaxhighlight lang
'''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.
Line 1,639:
while the <code>IntToInt</code> is used to replace the array values.
<
interface IntConsumer {
Line 1,683:
});
}
}</
Using Java 8 streams:
{{works with|Java|8}}
<
public class ArrayCallback {
Line 1,704:
System.out.println("sum: " + sum);
}
}</
=={{header|JavaScript}}==
===ES3===
<
var ret = [];
for (var i = 0; i < a.length; i++) {
Line 1,717:
}
map([1, 2, 3, 4, 5], function(v) { return v * v; });</
===ES5===
<
===ES6===
<
The result is always:
Line 1,730:
=={{header|Joy}}==
<
=={{header|jq}}==
<
map(exp) # exponentiate each item in the input list
Line 1,747:
# 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,760:
[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; }) ==> [ 1, 4, 9, 16, 25 ]
=!EXPECTEND!=
*/</
{{out}}
Line 1,768:
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
@show [n ^ 2 for n in numbers] # list comprehension
Line 1,775:
@show [n * n for n in numbers] # no need for a function,
@show numbers .* numbers # element-wise operation
@show numbers .^ 2 # includes .+, .-, ./, comparison, and bitwise operations as well</
=={{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,794:
pstack
" " input</
{{out}}
<pre>((1, 4, 9, 16))</pre>
=={{header|Lambdatalk}}==
<
{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|Lang5}}==
<
[1 2 3 4 5] square . "\n" .
[1 2 3 4 5] 'square apply . "\n" .</
=={{header|langur}}==
<
{{out}}
Line 1,816:
=={{header|Lasso}}==
<
local(
Line 1,827:
}
#mycube</
-> array(1, 8, 27, 64, 125)
=={{header|Lisaac}}==
<
+ b : {INTEGER;};
Line 1,844:
};
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,865:
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,876:
=={{header|M2000 Interpreter}}==
<
a=(1,2,3,4,5)
b=lambda->{
Line 1,904:
Print s=>sum=115
</syntaxhighlight>
=={{header|M4}}==
<
define(`_arg1', `$1')dnl
define(`_foreach', `ifelse(`$2', `()', `',
Line 1,915:
dnl
define(`z',`eval(`$1*2') ')dnl
apply(`(1,2,3)',`z')</
{{Out}}
Line 1,925:
For lists and sets, which in Maple are immutable, a new object is returned.
Either the built-in procedure map, or the short syntax of a trailing tilde (~) on the applied operator may be used.
<
> map( sqrt, [ 1.1, 3.2, 5.7 ] );
[1.048808848, 1.788854382, 2.387467277]
Line 1,937:
> (x -> x + 1)~( { 1, 3, 5 } );
{2, 4, 6}
</syntaxhighlight>
For Arrays (Vectors, Matrices, etc.) both map and trailing tilde also work, and by default create a new object, leaving the input Array unchanged.
<
> a := Array( [ 1.1, 3.2, 5.7 ] );
a := [1.1, 3.2, 5.7]
Line 1,954:
> a;
[1.1, 3.2, 5.7]
</syntaxhighlight>
However, since these are mutable data structures in Maple, it is possible to use map to modify its input according to the applied procedure.
<
> map[inplace]( sqrt, a );
[1.048808848, 1.788854382, 2.387467277]
Line 1,962:
> 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.
<
> 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.
<
> map2( `-`, 5, [ 1, 2, 3 ] );
[4, 3, 2]
Line 1,977:
> 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,989:
Example:
For both of these function the first argument is a function handle for the function we would like to apply to each element. The second argument is the array whose elements are modified by the function. The function can be any function, including user defined functions.
<
array =
Line 2,023:
Column 5
-3.380515006246586</
=={{header|Maxima}}==
<
map(sin, [1, 2, 3, 4]);
Line 2,033:
/* 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 2,066:
BEGIN
Map(sample, NUMBER(sample), callback);
END Callback.</
=={{header|Nanoquery}}==
<
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Line 2,081:
// display the squared list
println numbers</
{{out}}
<pre>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Line 2,088:
=={{header|Nemerle}}==
The <tt>Nemerle.Collections</tt> namespace defines the methods <tt>Iter()</tt> (if the function applied is <tt>void</tt>) and <tt>Map()</tt> (if the function applied returns a value).
<
def squares = seq.Map(x => x*x);</
=={{header|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}}==
<
[1, 2, 3, 4, 5].map(F(x) x*x)
}</
=={{header|Nial}}==
<
=1 4 9 16</
=={{header|Nim}}==
<
arr.apply proc(some: var int) = echo(some, " squared = ", some*some)</
{{Out}}
Line 2,128:
=={{header|Oberon-2}}==
{{Works with|oo2x}}
<
MODULE ApplyCallBack;
IMPORT
Line 2,217:
Init(a);r := Map3(Fun3,a);Show(r^);
END ApplyCallBack.
</syntaxhighlight>
{{Out}}
<pre>
Line 2,226:
=={{header|Objeck}}==
<
use Structure;
Line 2,248:
}
}
</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,278:
Almost all the built-in can operate on each element of a vector or matrix; e.g. sin([pi/2, pi, 2*pi]) computes the function sin on pi/2, pi and 2*pi (returning a vector). If a function does not accept vectors/matrices as arguments, the <tt>arrayfun</tt> can be used.
<
e = x^2 + exp(-1/(y+1));
endfunction
Line 2,284:
% f([2,3], [1,4]) gives and error, but
arrayfun(@f, [2, 3], [1,4])
% works</
(The function <tt>f</tt> can be rewritten so that it can accept vectors as argument simply changing operators to their dot ''relatives'': <code>e = x.^2 + exp(-1 ./ (y.+1))</code>)
Line 2,290:
=={{header|Oforth}}==
apply allows to perform a function on all elements of a list :
<
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,303:
'(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,330:
use arg string
say string
return .true -- called as a function, so a result is required</
{{out}}
<pre>kciR
Line 2,339:
=={{header|Order}}==
Both sequences and tuples support the usual map operation seen in many functional languages. Sequences also support <code>8seq_for_each</code>, and a few variations, which returns <code>8nil</code>.
<
ORDER_PP( 8tuple_map(8fn(8X, 8times(8X, 8X)), 8tuple(1, 2, 3, 4, 5)) )
Line 2,348:
ORDER_PP( 8seq_for_each(8fn(8X, 8print(8X 8comma)), 8seq(1, 2, 3, 4, 5)) )
// prints 1,2,3,4,5, and returns 8nil</
=={{header|Oz}}==
<
fun{Square A}
A*A
Line 2,363:
%% 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,378:
=={{header|Perl}}==
<
my @a = (1, 2, 3, 4, 5);
Line 2,407:
# 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,419:
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},</span><span style="color: #000000;">add1</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
<pre>
Line 2,433:
=={{header|Phixmonti}}==
<
by Galileo, 05/2022 #/
Line 2,451:
getid square map
pstack</
{{out}}
<pre>
Line 2,459:
=={{header|PHP}}==
<
{
return($n * $n * $n);
Line 2,466:
$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.
<
L = 1..10,
Line 2,491:
% Some function
fun(X) = X*X.
</syntaxhighlight>
{{trans|Prolog}}
Line 2,499:
Note that fun2/2 is not a function so map/2 or apply/2 cannot be used here.
<
L = 1..10,
Line 2,508:
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,528:
: (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,538:
array(int) a = ({ 1,2,3,4,5 });
array(int) b = cube(a[*]); // automap operator
array(int) c = map(a, cube); // conventional map function</
=={{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,622:
PKG_CALLBACK.TEST_CALLBACK();
END;
/</
=={{header|Pop11}}==
<
define proc(x);
printf(x*x, '%p,');
Line 2,635:
;;; 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,641:
=={{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,684:
Next
Cube(AnArray()) </
=={{header|Python}}==
<
return n * n
Line 2,704:
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}}==
<
'Task
'Take a combined set of elements and apply a function to each element.
Line 2,750:
End Sub
</syntaxhighlight>
=={{header|Quackery}}==
Line 2,756:
As a dialogue in the Quackery shell (REPL), applying the word <code>cubed</code> to the nest <code>[ 1 2 3 4 5 6 7 8 9 10 ]</code>, first treating the nest as a list, then as an array.
<
...
Line 2,778:
...
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,799:
=={{header|Racket}}==
<
#lang racket
Line 2,807:
;; the usual functional `map'
(vector-map sqr #(1 2 3 4 5))
</syntaxhighlight>
=={{header|Raku}}==
Line 2,813:
{{works with|Rakudo|2015.10-11}}
<
my @array = 1 .. 5;
Line 2,832:
# we neither need a variable for the array nor for the function
say [1,2,3]>>.&({ $^x + 1});
</syntaxhighlight>
=={{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,869:
print [crlf "Applying native function with 'map':"]
assert [[2 4 6] = map :square-root [4 16 36]]</
{{Out}}
Line 2,885:
Retro provides a variety of array words. Using these to multiply each value in an array by 10 and display the results:
<
=={{header|REXX}}==
<
numeric digits 100 /*be able to display some huge numbers.*/
parse arg # . /*obtain an optional value from the CL.*/
Line 2,910:
/*──────────────────────────────────────────────────────────────────────────────────────*/
fact: procedure; arg x; != 1; do f=2 to x; != !*f; end; /*f*/; return !
listA: do k=0 while a.k\==''; say arg(1) 'a.'k"=" a.k; end /*k*/; return</
{{out|output|text= when using the default input:}}
<pre>
Line 2,945:
=={{header|Ring}}==
<
for x in [1,2,3,4,5]
x = x*x
next
</syntaxhighlight>
=={{header|RLaB}}==
Line 2,965:
Consider an example:
<
>> x = rand(2,4)
0.707213207 0.275298961 0.396757763 0.232312312
Line 2,972:
0.649717845 0.271834652 0.386430003 0.230228332
0.213952984 0.205601224 0.536006923 0.617916954
</syntaxhighlight>
This can be done on entry-by-entry basis, but one has to keep in mind that the
'for' or 'while' loops are slow in interpreted languages, and RLaB is no exception.
<
x = rand(2,4);
y = zeros(2,4);
Line 2,987:
}
}
</syntaxhighlight>
Line 2,994:
function 'members' which returns a string vector with the names of the elements of the list.
<
x = <<>>;
for (i in 1:9)
Line 3,006:
y.[i] = sin( x.[i] );
}
</syntaxhighlight>
=={{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 3,030:
a = [1, 2, 3, 4, 5];
let _: Vec<_> = a.into_iter().map(echo).collect();
}</
=={{header|Salmon}}==
Line 3,036:
These examples apply the square function to a list of the numbers from 0 through 9 to produce a new list of their squares, then iterate over the resulting list and print the squares.
<
(comprehend(x; list) (to_apply(x)));
Line 3,042:
iterate(x; apply([0...9], square))
x!;</
With short identifiers:
<
fun apply(list, ageless to_apply)
Line 3,054:
iter(x; apply([0...9], square))
x!;</
With the numbers given as a list of individual elements:
<
(comprehend(x; list) (to_apply(x)));
Line 3,064:
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 3,078:
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 3,126:
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,166:
FOR I := 1 STEP 1 UNTIL 5 DO OUTFIX(A(I), 2, 8); OUTIMAGE;
END.</
{{out}}
<pre>
Line 3,173:
=={{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,232:
END;
END @
</syntaxhighlight>
Output:
<pre>
Line 3,245:
=={{header|Standard ML}}==
<
map f l
</syntaxhighlight>
i.e.
<
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,278:
function square(x) {
return(x*x)
}</
'''Output'''
Line 3,291:
=={{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,314:
let squares1b = numbers.map { $0 * $0 } // map method on array with anonymous function and unnamed parameters
let isquares1 = numbers.lazy.map(square) // lazy sequence</
=={{header|Tailspin}}==
<
def numbers: [1,3,7,10];
Line 3,332:
[ $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,356:
% 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,376:
foreach("callback", {1,2,3,4,5})
Disp map("√", {1,2,3,4,5})</
{{Out}}
Line 3,390:
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,417:
( Add 1 to each item in the array )
a 5 [ 1 + ] map-array</
=={{header|TorqueScript}}==
Line 3,425:
Callbacks:
<
function map(%array,%arrayCount,%function)
{
Line 3,434:
}
}
</syntaxhighlight>
Now to set up an array:
<
$array[0] = "Hello.";
$array[1] = "Hi.";
$array[2] = "How are you?";
</syntaxhighlight>
Now to call the function correctly:
<
map("$array",3,"echo");
</syntaxhighlight>
Which should result in:
<
=> Hello.
Line 3,458:
=> How are you?
</syntaxhighlight>
=={{header|TXR}}==
Line 3,464:
Print 1 through 10 out of a vector, using <code>prinl</code> the callback, right from the system shell command prompt:
<
1
2
Line 3,474:
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,543:
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,561:
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
<
map_command=$1
shift
Line 3,567:
}
list=1:2:3
(IFS=:; map echo $list)</
{{works with|ksh93}}
{{works with|pdksh}}
{{works with|zsh}}
<
typeset command=$1
shift
Line 3,578:
}
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,600:
=={{header|V}}==
apply squaring (dup *) to each member of collection
<
=={{header|VBA}}==
<syntaxhighlight lang=vb>
Option Explicit
Line 3,624:
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,633:
=====Implementation=====
<syntaxhighlight lang=vb>
class callback
dim sRule
Line 3,650:
end function
end class
</syntaxhighlight>
=====Invocation=====
<syntaxhighlight lang=vb>
dim a1
dim cb
Line 3,667:
cb.applyto a1
wscript.echo join( a1, ", " )
</syntaxhighlight>
{{Out}}
Line 3,680:
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,702:
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,726:
Array.ForEach(resultArr, AddressOf Console.WriteLine)
End Sub
End Module</
{{out}}
Line 3,736:
=={{header|Vorpal}}==
Given and array, A, and a function, F, mapping F over the elements of A is simple:
<syntaxhighlight lang
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,752:
=={{header|WDTE}}==
<
let s => import 'stream';
Line 3,760:
-> 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,780:
=={{header|XBS}}==
<
set newArr:array = [];
foreach(k,v as arr){
Line 3,794:
log(arr.join(", "));
log(result.join(", "));</
{{out}}
<pre>
Line 3,802:
=={{header|Yabasic}}==
<
local i
Line 3,832:
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,856:
inc (hl)
inc hl ;next entry in array
djnz bar</
{{out}}
Line 3,865:
=={{header|Zig}}==
<
var array = [_]i32{1, 2, 3};
apply(@TypeOf(array[0]), array[0..], func);
Line 3,879:
const std = @import("std");
std.debug.print("{d}\n", .{a-1});
}</
=={{header|zkl}}==
<
{{Out}}
<pre>
Line 3,889:
=={{header|zonnon}}==
<
module Main;
type
Line 3,929:
Write(Map(x,Power))
end Main.
</syntaxhighlight>
{{Out}}
<pre>
Line 3,936:
=={{header|ZX Spectrum Basic}}==
<
20 LET b$="x*x"
30 LET c$="x+x^2"
Line 3,946:
190 STOP
200 DATA 2,5,6,10,100
</syntaxhighlight>
{{omit from|gnuplot}}
|