Jump to content

Apply a callback to an array: Difference between revisions

m
Fixed lang tags.
m (Fixed lang tags.)
Line 3:
 
=={{header|ActionScript}}==
<lang actionscript>package
package
{
public class ArrayCallback
Line 22 ⟶ 21:
}
}
}</lang>
}
</lang>
 
=={{header|Ada}}==
{{works with|GNAT|GPL 2005}}
<lang ada>with Ada.Text_Io;
with Ada.Text_Io;
with Ada.Integer_text_IO;
Line 64 ⟶ 61:
begin
Map(Sample, Display'access);
end Call_Back_Example;</lang>
</lang>
 
=={{header|ALGOL 68}}==
<lang algol68> PROC call back proc = (INT location, INT value)VOID:
(
printf(($"array["g"] = "gl$, location, value))
);
 
PROC map = (REF[]INT array, PROC (INT,INT)VOID call back)VOID:
(
FOR i FROM LWB array TO UPB array DO
call back(i, array[i])
OD
);
main:
PROC map = (REF[]INT array, PROC (INT,INT)VOID call back)VOID:
(
[4]INT FORarray i:= FROM( LWB1, array4, TO9, UPB array16 DO);
map(array, call back(i, array[i]proc)
)</lang>
OD
);
main:
(
[4]INT array := ( 1, 4, 9, 16 );
map(array, call back proc)
)
Output:
<lang algol68>array[ +1] = +1
array[ +2] = +4
array[ +3] = +9
array[ +4] = +16</lang>
 
=={{header|AutoHotkey}}==
<lang AutoHotkey>map("callback", "3,4,5")
map("callback", "3,4,5")
callback(array)
{
Line 103 ⟶ 98:
{
%callback%(array)
}</lang>
}
</lang>
 
 
=={{header|AWK}}==
<lang awk>$ awk 'func psqr(x){print x,x*x}BEGIN{split("1 2 3 4 5",a);for(i in a)psqr(a[i])}'
4 16
5 25
1 1
2 4
3 9</lang>
 
=={{header|C}}==
Line 175 ⟶ 169:
 
{{works with|Visual C sharp|Visual C#|2005}}
<lang csharp>using System;
using System;
 
static class Program
Line 209 ⟶ 202:
Console.WriteLine(value * value);
}
}</lang>
}
</lang>
 
{{works with|C sharp|C#|3.0+}}
This version uses the C# 3 lambda notation.
 
<lang csharp>int[] intArray = { 1, 2, 3, 4, 5 };
int[] Array.ForEach(intArray = { 1, 2,i 3,=> 4,Console.WriteLine(i 5* }i));</lang>
Array.ForEach(intArray, i => Console.WriteLine(i * i));
</lang>
 
=={{header|C++}}==
Line 224 ⟶ 214:
{{works with|g++|4.1.1}}
===C-Style Array===
<lang cpp>#include <iostream> //cout for printing
#include <iostream> //cout for printing
#include <algorithm> //for_each defined here
 
Line 240 ⟶ 229:
return 0;
}
//prints 1 4 9 16 25</lang>
</lang>
 
===std::vector===
{{libheader|STL}}
<lang cpp>#include <iostream> // cout for printing
<lang cpp>
#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
#include <vector> // stl vector class
Line 267 ⟶ 254:
return 0;
}
//prints 1 4 9 16 25</lang>
</lang>
 
More tricky with binary function
<lang cpp>#include <iostream> // cout for printing
<lang>
#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
#include <vector> // stl vector class
Line 295 ⟶ 280:
return 0;
}
//prints 1x 2x 3x 4x 5x</lang>
</lang>
 
===Boost.Lambda===
{{libheader|Boost}}
<lang cpp>using namespace std;
using namespace std;
using namespace boost::lambda;
vector<int> ary(10);
int i = 0;
for_each(ary.begin(), ary.end(), _1 = ++var(i)); // init array
transform(ary.begin(), ary.end(), ostream_iterator<int>(cout, " "), _1 * _1); // square and output</lang>
</lang>
 
=={{header|Clean}}==
Line 313 ⟶ 295:
Define a function and an initial (unboxed) array.
 
<lang clean>square x = x * x
square x = x * x
 
values :: {#Int}
values = {x \\ x <- [1 .. 10]}</lang>
</lang>
 
One can easily define a map for arrays, which is overloaded and works for all kinds of arrays (lazy, strict, unboxed).
 
<lang clean>mapArray f array = {f x \\ x <-: array}</lang>
mapArray f array = {f x \\ x <-: array}
</lang>
 
Apply the function to the initial array (using a comprehension) and print result.
 
<lang clean>Start :: {#Int}
Start = mapArray square values</lang>
Start :: {#Int}
Start = mapArray square values
</lang>
 
=={{header|Common Lisp}}==
Line 337 ⟶ 313:
Imperative: print 1, 2, 3, 4 and 5:
 
<lang lisp>(map nil #'print #(1 2 3 4 5))</lang>
(map nil #'print #(1 2 3 4 5))
</lang>
 
Functional: collect squares into new vector that is returned:
 
<lang lisp>(defun square (x) (* x x))
(defunmap 'vector #'square #(x)1 (*2 3 x4 x5))</lang>
(map 'vector #'square #(1 2 3 4 5))
</lang>
 
Destructive, like the Javascript example; add 1 to every slot of vector *a*:
 
<lang lisp>(defvar *a* (vector 1 2 3))
(defvarmap-into *a* (vector #'1+ 2 3)*a*)</lang>
(map-into *a* #'1+ *a*)
</lang>
 
=={{header|Clojure}}==
 
<lang lisp>;; apply a named function, inc
<lang clojure>
(map inc [1 2 3 4])</lang>
;; apply a named function, inc
(map inc [1 2 3 4])
</lang>
 
<lang clojurelisp>;; apply a function
(map (fn [x] (* x x)) [1 2 3 4])</lang>
;; apply a function
(map (fn [x] (* x x)) [1 2 3 4])
</lang>
 
<lang lisp>;; shortcut syntax for a function
<lang clojure>
(map #(* % %) [1 2 3 4])</lang>
;; shortcut syntax for a function
(map #(* % %) [1 2 3 4])
</lang>
 
=={{header|D}}==
<lang d>U[] map(T, U)(T[] array, U delegate(T) dg) {
<lang d>
U[] map(T, U)(T[] array, U delegate(T) dg) {
auto result = new U[array.length];
Line 387 ⟶ 350:
[1, 2, 3, 4, 5].map( (int i) { return i+5; } )
);
}</lang>
}
</lang>
Using std.algorithm:
<lang d>writefln(map!("a + 5")([1, 2, 3, 4, 5]));</lang>
<lang d>
writefln(map!("a + 5")([1, 2, 3, 4, 5]));
</lang>
 
=={{header|E}}==
 
<lang e>def array := [1,2,3,4,5]
def array := [1,2,3,4,5]
def square(value) {
return value * value
}</lang>
}
</lang>
 
Example of builtin iteration:
 
<lang e>def callback(index, value) {
def callback(index, value) {
println(`Item $index is $value.`)
}
array.iterate(callback)</lang>
</lang>
 
There is no built-in map function '''yet'''. The following is one of the ways one could be implemented, returning a plain list (which is usually an array in implementation).
 
<lang e>def map(func, collection) {
def map(func, collection) {
def output := [].diverge()
for item in collection {
Line 422 ⟶ 377:
return output.snapshot()
}
println(map(square, array))</lang>
</lang>
 
=={{header|Forth}}==
Line 429 ⟶ 383:
This is a word that will call a given function on each cell in an array.
 
<lang forth>: map ( addr n fn -- )
-rot cells bounds do i @ over execute i ! cell +loop ;</lang>
: map ( addr n fn -- )
-rot cells bounds do i @ over execute i ! cell +loop ;
</lang>
 
Example usage:
 
<lang forth>create data 1 , 2 , 3 , 4 , 5 ,
create data 5 ' 1+ ,map 2 ,\ 3adds ,one 4to ,each 5element ,of data</lang>
data 5 ' 1+ map \ adds one to each element of data
</lang>
 
=={{header|Fortran}}==
Line 445 ⟶ 395:
 
{{Works with |Fortran|ISO 95 and later}}
<lang fortran>module arrCallback
module arrCallback
contains
elemental function cube( x )
Line 454 ⟶ 403:
cube = x * x * x
end function cube
end module arrCallback</lang>
</lang>
 
<lang fortran>program testAC
program testAC
use arrCallback
implicit none
Line 474 ⟶ 421:
write(*,*) b(i,:)
end do
end program testAC</lang>
</lang>
 
{{Works with|ANSI FORTRAN| 77 (with MIL-STD-1753 structured DO) and later}}
<lang fortran> program test
program test
C
C-- Declare array:
Line 492 ⟶ 437:
end do
C
end</lang>
</lang>
 
=={{header|FP}}==
<lang fp>{square * . [id, id]}
& square: <1,2,3,4,5></lang>
 
=={{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.
<lang fsharp>let evenp x = x % 2 = 0
let result = Array.map evenp [| 1; 2; 3; 4; 5; 6 |]</lang>
The same can be done using anonymous functions, this time squaring the members of the input array.
<lang fsharp>let result = Array.map (fun x -> x * x) [|1; 2; 3; 4; 5|]</lang>
 
=={{header|Groovy}}==
 
Print each value in a list
<lang groovy>[1,2,3,4].each { println it }</lang>
[1,2,3,4].each { println it }
</lang>
 
Create a new list containing the squares of another list
<lang groovy>[1,2,3,4].collect { it * it }</lang>
[1,2,3,4].collect { it * it }
</lang>
 
=={{header|Haskell}}==
Line 522 ⟶ 462:
===List===
{{works with|GHC}}
<lang haskell>let square x = x*x
let square x = x*x
let values = [1..10]
map square values</lang>
</lang>
 
Using list comprehension to generate a list of the squared values
<lang haskell>[square x | x <- values]</lang>
[square x | x <- values]
</lang>
 
Using function composition to create a function that will print the squares of a list
<lang haskell>let printSquares = mapM_ (print.square)
let printSquares = mapM_ (print.square)values</lang>
printSquares values
</lang>
 
===Array===
{{works with|GHC}}
<lang haskell>import Data.Array.IArray
import Data.Array.IArray
let square x = x*x
let values = array (1,10) [(i,i)|i <- [1..10]] :: Array Int Int
amap square values</lang>
</lang>
 
=={{header|Icon}}==
<lang icon>procedure main()
procedure main()
local lst
lst := [10, 20, 30, 40]
Line 558 ⟶ 489:
procedure callback(arg)
write("->", arg)
end</lang>
</lang>
 
=={{header|IDL}}==
Line 565 ⟶ 495:
Hard to come up with an example that isn't completely contrived. IDL doesn't really distinguish between a scalar and an array; thus
 
<lang idl>b = a^3</lang>
 
will yield a scalar if <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}}==
<lang io>list(1,2,3,4,5) map(squared)</lang>
 
=={{header|J}}==
Line 590 ⟶ 520:
So if you want to perform an action (which doesn't return anything) on an array of int's:
 
<lang java>interface IntToVoid {
interface IntToVoid {
void run(int x);
}
Line 601 ⟶ 530:
}
}.run(z);
}</lang>
}
</lang>
 
Or if you want to perform "map" - return an array of the results of function applications:
 
<lang java>interface IntToInt {
interface IntToInt {
int run(int x);
}
Line 619 ⟶ 546:
}
}.run(myIntArray[i]);
}</lang>
}
</lang>
 
=={{header|JavaScript}}==
Line 626 ⟶ 552:
Portable technique:
 
<lang javascript>function map(a, func) {
function map(a, func) {
for (var i in a)
a[i] = func(a[i]);
Line 633 ⟶ 558:
 
var a = [1, 2, 3, 4, 5];
map(a, function(v) { return v * v; });</lang>
</lang>
 
{{libheader|BeyondJS}}
With the [http://w3future.com/html/beyondJS/ BeyondJS] library:
 
<lang javascript>var a = (1).to(10).collect(Math.pow.curry(undefined,2));</lang>
var a = (1).to(10).collect(Math.pow.curry(undefined,2));
</lang>
 
With Firefox 2.0:
 
<lang javascript>function cube(num) {
function cube(num) {
return Math.pow(num, 3);
}
Line 660 ⟶ 581:
// array comprehension
var cubes2 = [cube(n) for each (n in numbers)];
var cubes3 = [n * n * n for each (n in numbers)];</lang>
</lang>
 
{{libheader|Functional}}
<lang javascript>Functional.map('x*x*x', [1,2,3,4,5])</lang>
Functional.map('x*x*x', [1,2,3,4,5])
</lang>
 
=={{header|Joy}}==
<lang joy>[1 2 3 4 5] [dup *] map.</lang>
[1 2 3 4 5] [dup *] map.
</lang>
 
=={{header|Lisaac}}==
<lang Lisaac>+ a : ARRAY[INTEGER];
+ a : ARRAY[INTEGER];
+ b : BLOCK;
 
Line 688 ⟶ 603:
};
 
a.foreach b;</lang>
</lang>
 
=={{header|Logo}}==
<lang logo>to square :x
to square :x
output :x * :x
end
show map "square [1 2 3 4 5] ; [1 4 9 16 25]
show map [? * ?] [1 2 3 4 5] ; [1 4 9 16 25]
foreach [1 2 3 4 5] [print square ?] ; 1 4 9 16 25, one per line</lang>
</lang>
 
=={{header|Lua}}==
 
Say we have an array:
<lang lua>myArray = {1, 2, 3, 4, 5}</lang>
myArray = {1, 2, 3, 4, 5}
</lang>
A map function for this would be
<lang lua>map = function(f, data)
map = function(f, data)
local result = {}
for k,v in ipairs(data) do
Line 715 ⟶ 624:
end
return result
end</lang>
</lang>
Together with our array and a square function this yields:
<lang lua>myFunc = function(x) return x*x end
myFunc = function(x) return x*x end
 
print(unpack( map(myFunc, myArray) ))
--> 1 4 9 16 25</lang>
</lang>
If you used pairs() instead of ipairs(), this would even work on a hash table in general.
 
=={{header|M4}}==
<lang M4>define(`foreach', `pushdef(`$1')_foreach($@)popdef(`$1')')dnl
<lang M4>
define(`foreach', `pushdef(`$1')_foreach($@)popdef(`$1')')dnl
define(`_arg1', `$1')dnl
define(`_foreach', `ifelse(`$2', `()', `',
Line 736 ⟶ 641:
dnl
define(`z',`eval(`$1*2') ')dnl
apply(`(1,2,3)',`z')</lang>
</lang>
 
Output:
Line 774 ⟶ 678:
=={{header|Nial}}==
 
<lang nial>each (* [first, first] ) 1 2 3 4
=1 4 9 16</lang>
each (* [first, first] ) 1 2 3 4
=1 4 9 16
</lang>
 
=={{header|OCaml}}==
This function is part of the standard library:
 
<lang ocaml>Array.map</lang>
Array.map
</lang>
 
Usage example:
<lang ocaml>let square x = x * x;;
let square x = x * x;;
let values = Array.init 10 ((+) 1);;
Array.map square values;;</lang>
</lang>
 
=={{header|Octave}}==
Line 809 ⟶ 707:
 
=={{header|Oz}}==
<lang oz>functor
functor
import
Application System
Line 836 ⟶ 733:
 
{Application.exit 0}
end</lang>
</lang>
=={{header|Perl}}==
<lang perl># create array
Line 886 ⟶ 782:
 
=={{header|PHP}}==
<lang php>function cube($n)
function cube($n)
{
return($n * $n * $n);
Line 894 ⟶ 789:
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);</lang>
</lang>
 
=={{header|PL/SQL}}==
{{works with|Oracle}}
<lang plsql>set serveroutput on
set serveroutput on
declare
type myarray is table of number index by binary_integer;
Line 924 ⟶ 817:
 
end;
/</lang>
/
</lang>
 
=={{header|Pop11}}==
 
<lang pop11>;;; Define a procedure
;;; Define a procedure
define proc(x);
printf(x*x, '%p,');
Line 939 ⟶ 830:
 
;;; Apply procedure to array
appdata(ar, proc);</lang>
</lang>
 
If one wants to create a new array consisting of transformed values then procedure mapdata may be more convenient.
Line 953 ⟶ 843:
 
=={{header|Python}}==
<lang python>def square(n):
def square(n):
return n * n
Line 971 ⟶ 860:
 
import itertools
isquares2 = itertools.imap(square, numbers) # iterator, lazy </lang>
</lang>
To print squares of integers in the range from 0 to 9, type:
<lang python>print " ".join(str(n * n) for n in range(10))</lang>
<lang python>
print " ".join(str(n * n) for n in range(10))
</lang>
Or:
<lang python>print " ".join(map(str, map(square, range(10))))</lang>
<lang python>
print " ".join(map(str, map(square, range(10))))
</lang>
Result:
<lang python>0 1 4 9 16 25 36 49 64 81</lang>
0 1 4 9 16 25 36 49 64 81
</lang>
 
=={{header|R}}==
Many functions can take advantage of implicit vectorisation, e.g.
<lang R>cube <- function(x) x*x*x
cube <- function(x) x*x*x
elements <- 1:5
cubes <- cube(elements) </lang>
</lang>
Explicit looping over array elements is also possible.
<lang R>cubes <- numeric(5)
cubes <- numeric(5)
for(i in seq_along(cubes))
{
cubes[i] <- cube(elements[i])
}</lang>
}
</lang>
Loop syntax can often simplified using the [http://stat.ethz.ch/R-manual/R-patched/library/base/html/apply.html *array] family of functions.
<lang R>elements2 <- list(1,2,3,4,5)
cubes <- sapply(elements2, cube)</lang>
elements2 <- list(1,2,3,4,5)
cubes <- sapply(elements2, cube)
</lang>
In each case above, the value of 'cubes' is
1 8 27 64 125
 
=={{header|Raven}}==
<lang raven># To print the squared elements
[1 2 3 4 5] each dup * print</lang>
# To print the squared elements
[1 2 3 4 5] each dup * print
</lang>
 
<lang raven># To obtain a new array
# To obtain a new array
group [1 2 3 4 5] each
dup *
list</lang>
</lang>
 
=={{header|Ruby}}==
You could use a traditional "for i in arr" approach like below:
<lang ruby>for i in [1,2,3,4,5] do
for i in [1,2,3,4,5] do
puts i**2
end</lang>
</lang>
 
Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk)
<lang ruby>[1,2,3,4,5].each{ |i| puts i**2 }</lang>
[1,2,3,4,5].each{ |i| puts i**2 }
</lang>
 
To create a new array of each value squared
<lang ruby>[1,2,3,4,5].map{ |i| i**2 }</lang>
[1,2,3,4,5].map{ |i| i**2 }
</lang>
 
=={{header|Scala}}==
<lang scala>val l = List(1,2,3,4)
l.foreach {i => println(i)}</lang>
val l = List(1,2,3,4)
l.foreach {i => println(i)}
</lang>
 
When the argument appears only once -as here, i appears only one in println(i) - it may be shortened to
<lang scala>l.foreach(println(_))</lang>
l.foreach(println(_))
</lang>
Same for an array
<lang scala>val a = Array(1,2,3,4)
val a = Array(1,2,3,4)
a.foreach {i => println(i)}
a.foreach(println(_)) '' // same as previous line''</lang>
</lang>
 
Or for an externally defined function:
<lang scala>def doSomething(in: int) = {println("Doing something with "+in)}
<lang scala>
l.foreach(doSomething)</lang>
def doSomething(in: int) = {println("Doing something with "+in)}
l.foreach(doSomething)
</lang>
 
There is also a ''for'' syntax, which is internally rewritten to call foreach. A foreach method must be defined on ''a''
<lang scala>for(val i <- a) println(i)</lang>
for(val i <- a) println(i)
</lang>
 
It is also possible to apply a function on each item of an list to get a new list (same on array and most collections)
<lang scala>val squares = l.map{i => i * i} ''//squares is'' List(1,4,9,16)</lang>
<lang scala>
val squares = l.map{i => i * i} ''//squares is'' List(1,4,9,16)
</lang>
 
Or the equivalent ''for'' syntax, with the additional keyword ''yield'', map is called instead of foreach
<lang scala>val squares = for (val i <- l) yield i * i</lang>
<lang scala>
val squares = for (val i <- l) yield i * i
</lang>
 
=={{header|Scheme}}==
<lang scheme>(define (square n) (* n n))
(define (square n) (* n n))
(define x #(1 2 3 4 5))
(map square (vector->list x))</lang>
</lang>
 
A single-line variation
<lang scheme>(map (lambda (n) (* n n)) '(1 2 3 4 5))</lang>
(map (lambda (n) (* n n)) '(1 2 3 4 5))
</lang>
 
For completeness, the <tt>map</tt> function (which is R5RS standard) can be coded as follows:
<lang scheme>(define (map f L)
(define (map f L)
(if (null? L)
L
(cons (f (car L)) (map f (cdr L)))))</lang>
</lang>
 
=={{header|Slate}}==
<lang slate>#( 1 2 3 4 5 ) collect: [| :n | n * n].</lang>
#( 1 2 3 4 5 ) collect: [| :n | n * n].
</lang>
 
=={{header|Smalltalk}}==
<lang smalltalk>#( 1 2 3 4 5 ) collect: [:n | n * n].</lang>
#( 1 2 3 4 5 ) collect: [:n | n * n].
</lang>
=={{header|Tcl}}==
 
Line 1,130 ⟶ 972:
=={{header|TI-89 BASIC}}==
 
<prelang style="font-family:'TI Uni'"ti89b>© For no return value
Define foreach(fe_cname,fe_list) = Prgm
Local fe_i
Line 1,146 ⟶ 988:
 
foreach("callback", {1,2,3,4,5})
Disp map("√", {1,2,3,4,5})</prelang>
 
Output:
Line 1,159 ⟶ 1,001:
=={{header|Toka}}==
 
<lang toka>( array count function -- )
{
( array count function -- )
value| array fn |
{
[ value|i array fn] is |I
[ to fn swap to array 0 swap [ I array.get :stack fn invoke I array.put ] countedLoop ]
[ i array ] is I
} is map-array
[ to fn swap to array 0 swap [ I array.get :stack fn invoke I array.put ] countedLoop ]
 
} is map-array
( Build an array )
5 cells ( Build an is-array )a
10 0 5a cells is-array a.put
11 10 01 a array.put
12 11 12 a array.put
13 12 23 a array.put
14 13 34 a array.put
 
14 4 a array.put
( Add 1 to each item in the array )
a 5 ( Add[ 1 to+ each item in the] map-array )</lang>
a 5 [ 1 + ] map-array
</lang>
 
 
Line 1,183 ⟶ 1,023:
The * is a built-in map operator.
This example shows a map of the successor function over a list of natural numbers.
<lang Ursala>#import nat
#import nat
 
#cast %nL
 
demo = successor* <325,32,67,1,3,7,315></lang>
</lang>
output:
<pre>
Line 1,197 ⟶ 1,035:
=={{header|V}}==
apply squaring (dup *) to each member of collection
<lang v>[1 2 3 4] [dup *] map</lang>
[1 2 3 4] [dup *] map
</lang>
 
=={{header|Vorpal}}==
Given and array, A, and a function, F, mapping F over the elements of A is simple:
<lang vorpal>A.map(F)</lang>
A.map(F)
</lang>
If F takes 2 arguments, x and , then simply pass them to map. They will be passed to F when as it is applied to each element of A.
<lang vorpal>A.map(F, x, y)</lang>
A.map(F, x, y)
</lang>
 
{{omit from|gnuplot}}
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.