Apply a callback to an array: Difference between revisions

From Rosetta Code
Content added Content deleted
m (<code>, fixed use of reserved identifier in C code, some minor formatting improvements)
m (<lang>)
Line 2: Line 2:


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<code actionscript>
<lang actionscript>
package
package
{
{
Line 22: Line 22:
}
}
}
}
</code>
</lang>


=={{header|Ada}}==
=={{header|Ada}}==
{{works with|GNAT|GPL 2005}}
{{works with|GNAT|GPL 2005}}
<code ada>
<lang ada>
with Ada.Text_Io;
with Ada.Text_Io;
with Ada.Integer_text_IO;
with Ada.Integer_text_IO;
Line 64: Line 64:
Map(Sample, Display'access);
Map(Sample, Display'access);
end Call_Back_Example;
end Call_Back_Example;
</code>
</lang>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 97: Line 97:
{{works with|ICC|9.1}}
{{works with|ICC|9.1}}
===callback.h===
===callback.h===
<code c>
<lang c>
#ifndef CALLBACK_H
#ifndef CALLBACK_H
#define CALLBACK_H
#define CALLBACK_H
Line 114: Line 114:


#endif
#endif
</code>
</lang>


===callback.c===
===callback.c===
<code>
<lang c>
#include <stdio.h>
#include <stdio.h>
#include "callback.h"
#include "callback.h"
Line 145: Line 145:
return 0;
return 0;
}
}
</code>
</lang>


===Output===
===Output===
Line 157: Line 157:
{{works with|C sharp|C#|2.0+}}
{{works with|C sharp|C#|2.0+}}
{{works with|Visual C sharp|Visual C#|2005}}
{{works with|Visual C sharp|Visual C#|2005}}
<lang csharp>
using System;
using System;
static class Program
{
// Purpose: Apply a callback (or anonymous method) to an Array
// Output: Prints the squares of an int array to the console.
// Compiler: Visual Studio 2005
// Framework: .net 2
[STAThread]
public static void Main()
{
int[] intArray = { 1, 2, 3, 4, 5 };
// Using a callback,
Console.WriteLine("Printing squares using a callback:");
Array.ForEach<int>(intArray, PrintSquare);
// or using an anonymous method:
Console.WriteLine("Printing squares using an anonymous method:");
Array.ForEach<int>
(
intArray,
delegate(int value)
{
Console.WriteLine(value * value);
});
}
public static void PrintSquare(int value)
{
Console.WriteLine(value * value);
}
}


static class Program
{
// Purpose: Apply a callback (or anonymous method) to an Array
// Output: Prints the squares of an int array to the console.
// Compiler: Visual Studio 2005
// Framework: .net 2
[STAThread]
public static void Main()
{
int[] intArray = { 1, 2, 3, 4, 5 };

// Using a callback,
Console.WriteLine("Printing squares using a callback:");
Array.ForEach<int>(intArray, PrintSquare);

// or using an anonymous method:
Console.WriteLine("Printing squares using an anonymous method:");
Array.ForEach<int>
(
intArray,
delegate(int value)
{
Console.WriteLine(value * value);
});
}

public static void PrintSquare(int value)
{
Console.WriteLine(value * value);
}
}
</lang>


{{works with|C sharp|C#|3.0+}}
{{works with|C sharp|C#|3.0+}}
This version uses the C# 3 lambda notation.
This version uses the C# 3 lambda notation.


<lang csharp>
int[] intArray = { 1, 2, 3, 4, 5 };
Array.ForEach(intArray, i => Console.WriteLine(i * i));
int[] intArray = { 1, 2, 3, 4, 5 };
Array.ForEach(intArray, i => Console.WriteLine(i * i));
</lang>


=={{header|C++}}==
=={{header|C++}}==
Line 203: Line 206:
{{works with|g++|4.1.1}}
{{works with|g++|4.1.1}}
===C-Style Array===
===C-Style Array===
<code cpp>
<lang cpp>
#include <iostream> //cout for printing
#include <iostream> //cout for printing
#include <algorithm> //for_each defined here
#include <algorithm> //for_each defined here
Line 220: Line 223:
}
}
//prints 1 4 9 16 25
//prints 1 4 9 16 25
</code>
</lang>


===std::vector===
===std::vector===
{{libheader|STL}}
{{libheader|STL}}
<code cpp>
<lang cpp>
#include <iostream> // cout for printing
#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
#include <algorithm> // for_each defined here
Line 247: Line 250:
}
}
//prints 1 4 9 16 25
//prints 1 4 9 16 25
</code>
</lang>


More tricky with binary function
More tricky with binary function
<code>
<lang>
#include <iostream> // cout for printing
#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
#include <algorithm> // for_each defined here
Line 275: Line 278:
}
}
//prints 1x 2x 3x 4x 5x
//prints 1x 2x 3x 4x 5x
</code>
</lang>


===Boost.Lambda===
===Boost.Lambda===
{{libheader|Boost}}
{{libheader|Boost}}
<code cpp>
<lang cpp>
using namespace std;
using namespace std;
using namespace boost::lambda;
using namespace boost::lambda;
Line 286: Line 289:
for_each(ary.begin(), ary.end(), _1 = ++var(i)); // init array
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
transform(ary.begin(), ary.end(), ostream_iterator<int>(cout, " "), _1 * _1); // square and output
</code>
</lang>


=={{header|Clean}}==
=={{header|Clean}}==
Line 292: Line 295:
Define a function and an initial (unboxed) array.
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]}
values :: {#Int}
values = {x \\ x <- [1 .. 10]}
</lang>


One can easily define a map for arrays, which is overloaded and works for all kinds of arrays (lazy, strict, unboxed).
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}
mapArray f array = {f x \\ x <-: array}
</lang>


Apply the function to the initial array (using a comprehension) and print result.
Apply the function to the initial array (using a comprehension) and print result.


<lang clean>
Start :: {#Int}
Start = mapArray square values
Start :: {#Int}
Start = mapArray square values
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 310: Line 319:
Imperative: print 1, 2, 3, 4 and 5:
Imperative: print 1, 2, 3, 4 and 5:


<code lisp>
<lang lisp>
(map nil #'print #(1 2 3 4 5))
(map nil #'print #(1 2 3 4 5))
</code>
</lang>


Functional: collect squares into new vector that is returned:
Functional: collect squares into new vector that is returned:


<code lisp>
<lang lisp>
(defun square (x) (* x x))
(defun square (x) (* x x))
(map 'vector #'square #(1 2 3 4 5))
(map 'vector #'square #(1 2 3 4 5))
</code>
</lang>


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


<code lisp>
<lang lisp>
(defvar *a* (vector 1 2 3))
(defvar *a* (vector 1 2 3))
(map-into *a* #'1+ *a*)
(map-into *a* #'1+ *a*)
</code>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==


<lang clojure>
;; apply a named function, inc
;; apply a named function, inc
(map inc [1 2 3 4])
(map inc [1 2 3 4])
</lang>


<lang clojure>
;; apply a function
;; apply a function
(map (fn [x] (* x x)) [1 2 3 4])
(map (fn [x] (* x x)) [1 2 3 4])
</lang>


<lang clojure>
;; shortcut syntax for a function
;; shortcut syntax for a function
(map #(* % %) [1 2 3 4])
(map #(* % %) [1 2 3 4])
</lang>


=={{header|D}}==
=={{header|D}}==
<code d>
<lang d>
U[] map(T, U)(T[] array, U delegate(T) dg) {
U[] map(T, U)(T[] array, U delegate(T) dg) {
auto result = new U[array.length];
auto result = new U[array.length];
Line 355: Line 370:
);
);
}
}
</code>
</lang>
Using std.algorithm:
Using std.algorithm:
<code d>
<lang d>
writefln(map!("a + 5")([1, 2, 3, 4, 5]));
writefln(map!("a + 5")([1, 2, 3, 4, 5]));
</code>
</lang>


=={{header|E}}==
=={{header|E}}==


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


Example of builtin iteration:
Example of builtin iteration:


<lang e>
def callback(index, value) {
println(`Item $index is $value.`)
def callback(index, value) {
println(`Item $index is $value.`)
}
}
array.iterate(callback)
array.iterate(callback)
</lang>


There is no built-in map function '''yet'''. The following is one of the ways one could be implemented, returning a plain list (which is usually an array in implementation).
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()
def output := [].diverge()
for item in collection {
for item in collection {
output.push(func(item))
output.push(func(item))
}
}
return output.snapshot()
return output.snapshot()
}
}
println(map(square, array))
println(map(square, array))
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
Line 390: Line 411:
This is a word that will call a given function on each cell in an array.
This is a word that will call a given function on each cell in an array.


<lang forth>
: map ( addr n fn -- )
: map ( addr n fn -- )
-rot cells bounds do i @ over execute i ! cell +loop ;
-rot cells bounds do i @ over execute i ! cell +loop ;
</lang>


Example usage:
Example usage:


<lang forth>
create data 1 , 2 , 3 , 4 , 5 ,
data 5 ' 1+ map \ adds one to each element of data
create data 1 , 2 , 3 , 4 , 5 ,
data 5 ' 1+ map \ adds one to each element of data
</lang>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 402: Line 427:


{{Works with |Fortran|ISO 95 and later}}
{{Works with |Fortran|ISO 95 and later}}
<code fortran>
<lang fortran>
module arrCallback
module arrCallback
contains
contains
Line 412: Line 437:
end function cube
end function cube
end module arrCallback
end module arrCallback
</code>
</lang>


<code fortran>
<lang fortran>
program testAC
program testAC
use arrCallback
use arrCallback
Line 432: Line 457:
end do
end do
end program testAC
end program testAC
</code>
</lang>


{{Works with|ANSI FORTRAN| 77 (with MIL-STD-1753 structured DO) and later}}
{{Works with|ANSI FORTRAN| 77 (with MIL-STD-1753 structured DO) and later}}
<lang fortran>
<!-- NOTE TO EDITORS OF THIS EXAMPLE:
program test
The following contains an invisible unicode character (U+FEFF) at the
start of the first FORTRAN code line (i.e. "program test") in order to work
around a bug in code tags, which would break correct FORTRAN 77 column alignment.
As long as the code tag problem isn't fixed, please make sure that you don't
accidentally delete that invisible character! -->
<code fortran>
 program test
C
C
C-- Declare array:
C-- Declare array:
Line 456: Line 475:
C
C
end
end
</code>
</lang>


=={{header|FP}}==
=={{header|FP}}==
Line 465: Line 484:


Print each value in a list
Print each value in a list
<lang groovy>
[1,2,3,4].each { println it }
[1,2,3,4].each { println it }
</lang>


Create a new list containing the squares of another list
Create a new list containing the squares of another list
<lang groovy>
[1,2,3,4].collect { it * it }
[1,2,3,4].collect { it * it }
</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==
Line 474: Line 497:
===List===
===List===
{{works with|GHC}}
{{works with|GHC}}
<code haskell>
<lang haskell>
let square x = x*x
let square x = x*x
let values = [1..10]
let values = [1..10]
map square values
map square values
</code>
</lang>


Using list comprehension to generate a list of the squared values
Using list comprehension to generate a list of the squared values
<code haskell>
<lang haskell>
[square x | x <- values]
[square x | x <- values]
</code>
</lang>


Using function composition to create a function that will print the squares of a list
Using function composition to create a function that will print the squares of a list
<code haskell>
<lang haskell>
let printSquares = putStr.unlines.map (show.square)
let printSquares = putStr.unlines.map (show.square)
printSquares values
printSquares values
</code>
</lang>


===Array===
===Array===
{{works with|GHC}}
{{works with|GHC}}
<code haskell>
<lang haskell>
import Data.Array.IArray
import Data.Array.IArray
let square x = x*x
let square x = x*x
let values = array (1,10) [(i,i)|i <- [1..10]] :: Array Int Int
let values = array (1,10) [(i,i)|i <- [1..10]] :: Array Int Int
amap square values
amap square values
</code>
</lang>


=={{header|Icon}}==
=={{header|Icon}}==
<lang icon>
procedure main()
procedure main()
local lst
lst := [10, 20, 30, 40]
local lst
lst := [10, 20, 30, 40]
every callback(!lst)
every callback(!lst)
end
end
procedure callback(arg)
write("->", arg)
end


procedure callback(arg)
write("->", arg)
end
</lang>


=={{header|IDL}}==
=={{header|IDL}}==
Line 541: Line 565:
So if you want to perform an action (which doesn't return anything) on an array of int's:
So if you want to perform an action (which doesn't return anything) on an array of int's:


<code java>
<lang java>
interface IntToVoid {
interface IntToVoid {
void run(int x);
void run(int x);
Line 553: Line 577:
}.run(z);
}.run(z);
}
}
</code>
</lang>


Or if you want to perform "map" - return an array of the results of function applications:
Or if you want to perform "map" - return an array of the results of function applications:


<code java>
<lang java>
interface IntToInt {
interface IntToInt {
int run(int x);
int run(int x);
Line 571: Line 595:
}.run(myIntArray[i]);
}.run(myIntArray[i]);
}
}
</code>
</lang>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 577: Line 601:
Portable technique:
Portable technique:


<code javascript>
<lang javascript>
function map(a, func) {
function map(a, func) {
for (var i in a)
for (var i in a)
Line 585: Line 609:
var a = [1, 2, 3, 4, 5];
var a = [1, 2, 3, 4, 5];
map(a, function(v) { return v * v; });
map(a, function(v) { return v * v; });
</code>
</lang>


{{libheader|BeyondJS}}
{{libheader|BeyondJS}}
With the [http://w3future.com/html/beyondJS/ BeyondJS] library:
With the [http://w3future.com/html/beyondJS/ BeyondJS] library:


<code javascript>
<lang javascript>
var a = (1).to(10).collect(Math.pow.curry(undefined,2));
var a = (1).to(10).collect(Math.pow.curry(undefined,2));
</code>
</lang>


With Firefox 2.0:
With Firefox 2.0:


<code javascript>
<lang javascript>
function cube(num) {
function cube(num) {
return Math.pow(num, 3);
return Math.pow(num, 3);
Line 603: Line 627:
var numbers = [1, 2, 3, 4, 5];
var numbers = [1, 2, 3, 4, 5];


//get results of calling cube on every element
// get results of calling cube on every element
var cubes1 = numbers.map(cube);
var cubes1 = numbers.map(cube);


//display each result in a separate dialog
// display each result in a separate dialog
cubes1.forEach(alert);
cubes1.forEach(alert);


//array comprehension
// array comprehension
var cubes2 = [cube(n) for each (n in numbers)];
var cubes2 = [cube(n) for each (n in numbers)];
var cubes3 = [n * n * n for each (n in numbers)];
var cubes3 = [n * n * n for each (n in numbers)];
</code>
</lang>


{{libheader|Functional}}
{{libheader|Functional}}
<code javascript>
<lang javascript>
Functional.map('x*x*x', [1,2,3,4,5])
Functional.map('x*x*x', [1,2,3,4,5])
</code>
</lang>
=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>
to square :x
output :x * :x
to square :x
output :x * :x
end
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]
show map "square [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
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>


=={{header|Lua}}==
=={{header|Lua}}==


Say we have an array:
Say we have an array:
<lang lua>
myArray = {1, 2, 3, 4, 5}
myArray = {1, 2, 3, 4, 5}
</lang>
A map function for this would be
A map function for this would be
<lang lua>
map = function(f, data)
map = function(f, data)
local result = {}
local result = {}
for k,v in ipairs(data) do
result[k] = f(v)
for k,v in ipairs(data) do
result[k] = f(v)
end
end
return result
return result
end
end
</lang>
Together with our array and and a square function this yields:
Together with our array and 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) ))
print(unpack( map(myFunc, myArray) ))
--> 1 4 9 16 25
--> 1 4 9 16 25
</lang>
If you used pairs() instead of ipairs(), this would even work on a hash table in general.
If you used pairs() instead of ipairs(), this would even work on a hash table in general.


=={{header|Nial}}==
=={{header|Nial}}==


<lang nial>
each (* [first, first] ) 1 2 3 4
each (* [first, first] ) 1 2 3 4
=1 4 9 16
=1 4 9 16
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
This function is part of the standard library:
This function is part of the standard library:


<code ocaml>
<lang ocaml>
Array.map
Array.map
</code>
</lang>


Usage example:
Usage example:
<code ocaml>
<lang ocaml>
let square x = x * x;;
let square x = x * x;;
let values = Array.init 10 ((+) 1);;
let values = Array.init 10 ((+) 1);;
Array.map square values;;
Array.map square values;;
</code>
</lang>


=={{header|Oz}}==
=={{header|Oz}}==
<pre>
<lang oz>
functor
functor
import
import
Line 693: Line 727:
{Application.exit 0}
{Application.exit 0}
end
end
</pre>
</lang>
=={{header|Perl}}==
=={{header|Perl}}==
<code perl>
<lang perl>
# create array
# create array
my @a = (1, 2, 3, 4, 5);
my @a = (1, 2, 3, 4, 5);
Line 724: Line 758:
my $func = \&mycallback;
my $func = \&mycallback;
my @d = map $func->($_), @a; # @d is now (2, 4, 6, 8, 10)
my @d = map $func->($_), @a; # @d is now (2, 4, 6, 8, 10)
</code>
</lang>


=={{header|PHP}}==
=={{header|PHP}}==
<code php>
<lang php>
function cube($n)
function cube($n)
{
{
Line 736: Line 770:
$b = array_map("cube", $a);
$b = array_map("cube", $a);
print_r($b);
print_r($b);
</code>
</lang>


=={{header|PL/SQL}}==
=={{header|PL/SQL}}==
{{works with|Oracle}}
{{works with|Oracle}}
<code plsql>
<lang plsql>
set serveroutput on
set serveroutput on
declare
declare
Line 766: Line 800:
end;
end;
/
/
</code>
</lang>


=={{header|Pop11}}==
=={{header|Pop11}}==


<lang pop11>
;;; Define a procedure
;;; Define a procedure
define proc(x);
define proc(x);
printf(x*x, '%p,');
printf(x*x, '%p,');
enddefine;
enddefine;


;;; Create array
;;; Create array
lvars ar = { 1 2 3 4 5};
lvars ar = { 1 2 3 4 5};


;;; Apply procedure to array
;;; Apply procedure to array
appdata(ar, proc);
appdata(ar, proc);
</lang>


If one wants to create a new array consisting of transformed values then procedure mapdata may be more convenient.
If one wants to create a new array consisting of transformed values then procedure mapdata may be more convenient.


=={{header|Python}}==
=={{header|Python}}==
<code python>
<lang python>
def square(n):
def square(n):
return n * n
return n * n
Line 803: Line 839:
import itertools
import itertools
isquares2 = itertools.imap(square, numbers) # iterator, lazy
isquares2 = itertools.imap(square, numbers) # iterator, lazy
</code>
</lang>
To print squares of integers in the range from 0 to 9, type:
To print squares of integers in the range from 0 to 9, type:
<code python>
<lang python>
print " ".join(str(n * n) for n in range(10))
print " ".join(str(n * n) for n in range(10))
</code>
</lang>
Or:
Or:
<code python>
<lang python>
print " ".join(map(str, map(square, range(10))))
print " ".join(map(str, map(square, range(10))))
</code>
</lang>
Result:
Result:
<code python>
<lang python>
0 1 4 9 16 25 36 49 64 81
0 1 4 9 16 25 36 49 64 81
</code>
</lang>


=={{header|Raven}}==
=={{header|Raven}}==


<lang raven>
# To print the squared elements
# To print the squared elements
[1 2 3 4 5] each dup * print
[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 *
group [1 2 3 4 5] each
list
dup *
list
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
You could use a traditional "for i in arr" approach like below:
You could use a traditional "for i in arr" approach like below:
<code ruby>
<lang ruby>
for i in [1,2,3,4,5] do
for i in [1,2,3,4,5] do
puts i**2
puts i**2
end
end
</code>
</lang>


Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk)
Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk)
<code ruby>
<lang ruby>
[1,2,3,4,5].each{ |i| puts i**2 }
[1,2,3,4,5].each{ |i| puts i**2 }
</code>
</lang>


To create a new array of each value squared
To create a new array of each value squared
<code ruby>
<lang ruby>
[1,2,3,4,5].map{ |i| i**2 }
[1,2,3,4,5].map{ |i| i**2 }
</code>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>
val l = List(1,2,3,4)
val l = List(1,2,3,4)
l.foreach {i => println(i)}
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
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(_))
l.foreach(println(_))
</lang>
Same for an array
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''
a.foreach {i => println(i)}
a.foreach(println(_)) '' // same as previous line''
</lang>


Or for an externally defined function:
Or for an externally defined function:
<lang scala>
def doSomething(in: int) = {println("Doing something with "+in)}
def doSomething(in: int) = {println("Doing something with "+in)}
l.foreach(doSomething)
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''
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)
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)
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)
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
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
val squares = for (val i <- l) yield i * i
</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
<code scheme>
<lang scheme>
(define (square n) (* n n))
(define (square n) (* n n))
(define x #(1 2 3 4 5))
(define x #(1 2 3 4 5))
(map square (vector->list x))
(map square (vector->list x))
</code>
</lang>


A single-line variation
A single-line variation
<code scheme>
<lang scheme>
(map (lambda (n) (* n n)) '(1 2 3 4 5))
(map (lambda (n) (* n n)) '(1 2 3 4 5))
</code>
</lang>


For completeness, the <tt>map</tt> function (which is R5RS standard) can be coded as follows:
For completeness, the <tt>map</tt> function (which is R5RS standard) can be coded as follows:
<code scheme>
<lang scheme>
(define (map f L)
(define (map f L)
(if (null? L)
(if (null? L)
L
L
(cons (f (car L)) (map f (cdr L)))))
(cons (f (car L)) (map f (cdr L)))))
</code>
</lang>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<code smalltalk>
<lang smalltalk>
#( 1 2 3 4 5 ) collect: [:n | n * n].
#( 1 2 3 4 5 ) collect: [:n | n * n].
</code>
</lang>
=={{header|Tcl}}==
=={{header|Tcl}}==


If I wanted to call "<tt>myfunc</tt>" on each element of <tt>dat</tt> and <tt>dat</tt> were a list:
If I wanted to call "<tt>myfunc</tt>" on each element of <tt>dat</tt> and <tt>dat</tt> were a list:


<code tcl>
<lang tcl>
foreach var $dat { myfunc $var }
foreach var $dat { myfunc $var }
</code>
</lang>


if <tt>dat</tt> were an array, however:
if <tt>dat</tt> were an array, however:


<code tcl>
<lang tcl>
foreach name [array names dat] { myfunc $dat($name) }
foreach name [array names dat] { myfunc $dat($name) }
</code>
</lang>


=={{header|Toka}}==
=={{header|Toka}}==


<lang toka>
( array count function -- )
( array count function -- )
{
{
Line 926: Line 981:
( Add 1 to each item in the array )
( Add 1 to each item in the array )
a 5 [ 1 + ] map-array
a 5 [ 1 + ] map-array
</lang>


=={{header|V}}==
=={{header|V}}==
apply squaring (dup *) to each member of collection
apply squaring (dup *) to each member of collection
<lang v>
[1 2 3 4] [dup *] map
[1 2 3 4] [dup *] map
</lang>

Revision as of 16:50, 30 January 2009

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

In this task, the goal is to take a combined set of elements and apply a function to each element.

ActionScript

<lang actionscript> package {

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

} </lang>

Ada

Works with: GNAT version GPL 2005

<lang ada> with Ada.Text_Io;

with Ada.Integer_text_IO;

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

</lang>

ALGOL 68

 PROC call back proc = (INT location, INT value)VOID:
 (
   printf(($"array["g"] = "gl$, location, value))
 );

 PROC map = (REF[]INT array, PROC (INT,INT)VOID call back)VOID:
 (
   FOR i FROM LWB array TO UPB array DO
      call back(i, array[i])
   OD
 );
 
 main:
 (
   [4]INT array := ( 1, 4, 9, 16 );
   map(array, call back proc)
 )

Output:

array[         +1] =          +1
array[         +2] =          +4
array[         +3] =          +9
array[         +4] =         +16


C

Works with: gcc version 4.1.1
Works with: TCC version 0.9.23
Works with: ICC version 9.1

callback.h

<lang c>

  1. ifndef CALLBACK_H
  2. define CALLBACK_H

/*

* By declaring the function in a separate file, we allow
* it to be used by other source files.
*
* It also stops ICC from complaining.
*
* If you don't want to use it outside of callback.c, this
* file can be removed, provided the static keyword is prepended
* to the definition.
*/

void map(int* array, int len, void(*callback)(int,int));

  1. endif

</lang>

callback.c

<lang c>

  1. include <stdio.h>
  2. include "callback.h"

/*

* We don't need this function outside of this file, so
* we declare it static.
*/

static void callbackFunction(int location, int value) {

 printf("array[%d] = %d\n", location, value);

}

void map(int* array, int len, void(*callback)(int,int)) {

 int i;
 for(i = 0; i < len; i++)
 {
    callback(i, array[i]);
 }

}

int main() {

 int array[] = { 1, 2, 3, 4 };
 map(array, 4, callbackFunction);
 return 0;

} </lang>

Output

 array[0] = 1
 array[1] = 2
 array[2] = 3
 array[3] = 4

C#

Works with: C# version 2.0+
Works with: Visual C# version 2005

<lang csharp> using System;

static class Program {

 // Purpose: Apply a callback (or anonymous method) to an Array
 // Output: Prints the squares of an int array to the console.
 // Compiler: Visual Studio 2005
 // Framework: .net 2
  
 [STAThread]
 public static void Main() 
 {
   int[] intArray = { 1, 2, 3, 4, 5 };
   // Using a callback,
   Console.WriteLine("Printing squares using a callback:");
   Array.ForEach<int>(intArray, PrintSquare);
   // or using an anonymous method:
   Console.WriteLine("Printing squares using an anonymous method:");
   Array.ForEach<int>
   (
     intArray,
     delegate(int value) 
     {
       Console.WriteLine(value * value);    
     });
 }
 public static void PrintSquare(int value) 
 { 
   Console.WriteLine(value * value);
 }

} </lang>

Works with: C# version 3.0+

This version uses the C# 3 lambda notation.

<lang csharp> int[] intArray = { 1, 2, 3, 4, 5 }; Array.ForEach(intArray, i => Console.WriteLine(i * i)); </lang>

C++

Works with: g++ version 4.1.1

C-Style Array

<lang cpp>

  1. include <iostream> //cout for printing
  2. include <algorithm> //for_each defined here

//create the function (print the square) void print_square(int i) {

 std::cout << i*i << " ";

}

int main() {

 //create the array
 int ary[]={1,2,3,4,5};
 //stl for_each
 std::for_each(ary,ary+5,print_square);
 return 0;

} //prints 1 4 9 16 25 </lang>

std::vector

Library: STL

<lang cpp>

  1. include <iostream> // cout for printing
  2. include <algorithm> // for_each defined here
  3. include <vector> // stl vector class

// create the function (print the square) void print_square(int i) {

 std::cout << i*i << " ";

}

int main() {

 // create the array
 std::vector<int> ary;
 ary.push_back(1);
 ary.push_back(2);
 ary.push_back(3);
 ary.push_back(4);
 ary.push_back(5);
 // stl for_each
 std::for_each(ary.begin(),ary.end(),print_square);
 return 0;

} //prints 1 4 9 16 25 </lang>

More tricky with binary function <lang>

  1. include <iostream> // cout for printing
  2. include <algorithm> // for_each defined here
  3. include <vector> // stl vector class
  4. include <functional> // bind and ptr_fun

// create a binary function (print any two arguments together) template<class type1,class type2> void print_juxtaposed(type1 x, type2 y) {

 std::cout << x << y;

}

int main() {

 // create the array
 std::vector<int> ary;
 ary.push_back(1);
 ary.push_back(2);
 ary.push_back(3);
 ary.push_back(4);
 ary.push_back(5);
 // stl for_each, using binder and adaptable unary function
 std::for_each(ary.begin(),ary.end(),std::bind2nd(std::ptr_fun(print_juxtaposed<int,std::string>),"x "));
 return 0;

} //prints 1x 2x 3x 4x 5x </lang>

Boost.Lambda

Library: Boost

<lang cpp> using namespace std; using namespace boost::lambda; vector<int> ary(10); int i = 0; for_each(ary.begin(), ary.end(), _1 = ++var(i)); // init array transform(ary.begin(), ary.end(), ostream_iterator<int>(cout, " "), _1 * _1); // square and output </lang>

Clean

Define a function and an initial (unboxed) array.

<lang clean> square x = x * x

values :: {#Int} values = {x \\ x <- [1 .. 10]} </lang>

One can easily define a map for arrays, which is overloaded and works for all kinds of arrays (lazy, strict, unboxed).

<lang clean> mapArray f array = {f x \\ x <-: array} </lang>

Apply the function to the initial array (using a comprehension) and print result.

<lang clean> Start :: {#Int} Start = mapArray square values </lang>

Common Lisp

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

<lang lisp> (map nil #'print #(1 2 3 4 5)) </lang>

Functional: collect squares into new vector that is returned:

<lang lisp> (defun square (x) (* x x)) (map 'vector #'square #(1 2 3 4 5)) </lang>

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

<lang lisp> (defvar *a* (vector 1 2 3)) (map-into *a* #'1+ *a*) </lang>

Clojure

<lang clojure>

apply a named function, inc

(map inc [1 2 3 4]) </lang>

<lang clojure>

apply a function

(map (fn [x] (* x x)) [1 2 3 4]) </lang>

<lang clojure>

shortcut syntax for a function

(map #(* % %) [1 2 3 4]) </lang>

D

<lang d> U[] map(T, U)(T[] array, U delegate(T) dg) {

   auto result = new U[array.length];

   foreach (index, element; array)
       result[index] = dg(element);

   return result;

}

void main() {

   writefln(
       [1, 2, 3, 4, 5].map( (int i) { return i+5; } )   
   );

} </lang> Using std.algorithm: <lang d> writefln(map!("a + 5")([1, 2, 3, 4, 5])); </lang>

E

<lang e> def array := [1,2,3,4,5] def square(value) {

   return value * value

} </lang>

Example of builtin iteration:

<lang e> def callback(index, value) {

   println(`Item $index is $value.`)

} array.iterate(callback) </lang>

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

<lang e> def map(func, collection) {

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

} println(map(square, array)) </lang>

Forth

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

<lang forth>

map ( addr n fn -- )
  -rot cells bounds do  i @ over execute i !  cell +loop ;

</lang>

Example usage:

<lang forth> create data 1 , 2 , 3 , 4 , 5 , data 5 ' 1+ map \ adds one to each element of data </lang>

Fortran

Elemental functions.

Works with: Fortran version ISO 95 and later

<lang fortran> module arrCallback contains

   elemental function cube( x )
       implicit none
       real :: cube
       real, intent(in) :: x
       cube = x * x * x
   end function cube

end module arrCallback </lang>

<lang fortran> program testAC

   use arrCallback
   implicit none
   integer :: i, j
   real, dimension(3,4) :: b, &
       a = reshape( (/ ((10 * i + j, i = 1, 3), j = 1, 4) /), (/ 3,4 /) )
    
   do i = 1, 3
       write(*,*) a(i,:)
   end do
    
   b = cube( a )  ! Applies CUBE to every member of a,
                  ! and stores each result in the equivalent element of b
   do i = 1, 3
       write(*,*) b(i,:)
   end do

end program testAC </lang>

Works with: ANSI FORTRAN version 77 (with MIL-STD-1753 structured DO) and later

<lang fortran>

     program test

C C-- Declare array:

     integer a(5)

C C-- Fill it with Data

     data a /45,22,67,87,98/

C C-- Do something with all elements (in this case: print their squares)

     do i=1,5
       print *,a(i)*a(i)
     end do

C

     end

</lang>

FP

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

Groovy

Print each value in a list <lang groovy>

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

</lang>

Create a new list containing the squares of another list <lang groovy>

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

</lang>

Haskell

List

Works with: GHC

<lang haskell> let square x = x*x let values = [1..10] map square values </lang>

Using list comprehension to generate a list of the squared values <lang haskell> [square x | x <- values] </lang>

Using function composition to create a function that will print the squares of a list <lang haskell> let printSquares = putStr.unlines.map (show.square) printSquares values </lang>

Array

Works with: GHC

<lang haskell> import Data.Array.IArray let square x = x*x let values = array (1,10) [(i,i)|i <- [1..10]] :: Array Int Int amap square values </lang>

Icon

<lang icon> procedure main()

  local lst
  lst := [10, 20, 30, 40]
  every callback(!lst)

end

procedure callback(arg)

  write("->", arg)

end </lang>

IDL

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

 b = a^3

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

Io

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

J

Solution:

   "_1

Example:

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

Java

As of the current version of Java, you have to define an interface for each type of function you want to use. The next version of Java will introduce function types.

So if you want to perform an action (which doesn't return anything) on an array of int's:

<lang java> interface IntToVoid {

   void run(int x);

}

for (int z : myIntArray) {

   new IntToVoid() {
       public void run(int x) {
           System.out.println(x);
       }
   }.run(z);

} </lang>

Or if you want to perform "map" - return an array of the results of function applications:

<lang java> interface IntToInt {

   int run(int x);

}

int[] result = new int[myIntArray.length]; for (int i = 0; i < myIntArray.length; i++) {

   result[i] =
       new IntToInt() {
           public int run(int x) {
               return x * x;
           }
       }.run(myIntArray[i]);

} </lang>

JavaScript

Portable technique:

<lang javascript> function map(a, func) {

 for (var i in a)
   a[i] = func(a[i]);

}

var a = [1, 2, 3, 4, 5]; map(a, function(v) { return v * v; }); </lang>

Library: BeyondJS

With the BeyondJS library:

<lang javascript> var a = (1).to(10).collect(Math.pow.curry(undefined,2)); </lang>

With Firefox 2.0:

<lang javascript> function cube(num) {

 return Math.pow(num, 3);

}

var numbers = [1, 2, 3, 4, 5];

// get results of calling cube on every element var cubes1 = numbers.map(cube);

// display each result in a separate dialog cubes1.forEach(alert);

// array comprehension var cubes2 = [cube(n) for each (n in numbers)]; var cubes3 = [n * n * n for each (n in numbers)]; </lang>

Library: Functional

<lang javascript> Functional.map('x*x*x', [1,2,3,4,5]) </lang>

<lang logo> to square :x

 output :x * :x

end show map "square [1 2 3 4 5]  ; [1 4 9 16 25] show map [? * ?] [1 2 3 4 5]  ; [1 4 9 16 25] foreach [1 2 3 4 5] [print square ?]  ; 1 4 9 16 25, one per line </lang>

Lua

Say we have an array: <lang lua> myArray = {1, 2, 3, 4, 5} </lang> A map function for this would be <lang lua> map = function(f, data)

  local result = {}
  for k,v in ipairs(data) do
     result[k] = f(v)
  end
  return result

end </lang> Together with our array and and a square function this yields: <lang lua> myFunc = function(x) return x*x end

print(unpack( map(myFunc, myArray) )) --> 1 4 9 16 25 </lang> If you used pairs() instead of ipairs(), this would even work on a hash table in general.

Nial

<lang nial>

each (* [first, first] ) 1 2 3 4
=1 4 9 16

</lang>

OCaml

This function is part of the standard library:

<lang ocaml> Array.map </lang>

Usage example: <lang ocaml> let square x = x * x;; let values = Array.init 10 ((+) 1);; Array.map square values;; </lang>

Oz

<lang oz> functor import

 Application System

define

 Print = System.showInfo
 fun{Square A}
   A*A
 end
 fun{FuncEach Func A}
   {Map A Func}
 end
 proc{ProcEach Proc A}
   {ForAll A Proc}
 end
 Arr = [1 2 3 4 5]
 {ProcEach Print {FuncEach Square Arr}}
 {ForAll {Map Arr Square} Print}           %% same
 {Application.exit 0}

end </lang>

Perl

<lang perl>

  1. create array

my @a = (1, 2, 3, 4, 5);

  1. create callback function

sub mycallback {

 return 2 * shift;

}

  1. use array indexing

my $i; for ($i = 0; $i < scalar @a; $i++) {

 print "mycallback($a[$i]) = ", mycallback($a[$i]), "\n";

}

  1. using foreach

foreach my $x (@a) {

 print "mycallback($x) = ", mycallback($x), "\n";

}

  1. using map (useful for transforming an array)

my @b = map mycallback($_), @a; # @b is now (2, 4, 6, 8, 10)

  1. and the same using an anonymous function

my @c = map { $_ * 2 } @a; # @c is now (2, 4, 6, 8, 10)

  1. use a callback stored in a variable

my $func = \&mycallback; my @d = map $func->($_), @a; # @d is now (2, 4, 6, 8, 10) </lang>

PHP

<lang php> function cube($n) {

  return($n * $n * $n);

}

$a = array(1, 2, 3, 4, 5); $b = array_map("cube", $a); print_r($b); </lang>

PL/SQL

Works with: Oracle

<lang plsql> set serveroutput on declare

     type myarray is table of number index by binary_integer;
     x myarray;
     i pls_integer;

begin

     -- populate array
     for i in 1..5 loop
             x(i) := i;
     end loop;
     i :=0;
     -- square array
     loop
             i := i + 1;
             begin
                     x(i) := x(i)*x(i);
                     dbms_output.put_line(x(i));
             exception 
                     when no_data_found then exit;
             end;
     end loop;

end; / </lang>

Pop11

<lang pop11>

Define a procedure

define proc(x);

   printf(x*x, '%p,');

enddefine;

Create array

lvars ar = { 1 2 3 4 5};

Apply procedure to array

appdata(ar, proc); </lang>

If one wants to create a new array consisting of transformed values then procedure mapdata may be more convenient.

Python

<lang python> def square(n):

   return n * n
 

numbers = [1, 3, 5, 7]

squares1 = [square(n) for n in numbers] # list comprehension

squares2a = map(square, numbers) # functional form

squares2b = map(lambda x: x*x, numbers) # functional form with `lambda`

squares3 = [n * n for n in numbers] # no need for a function,

                                           # anonymous or otherwise

isquares1 = (n * n for n in numbers) # iterator, lazy

import itertools isquares2 = itertools.imap(square, numbers) # iterator, lazy </lang> To print squares of integers in the range from 0 to 9, type: <lang python> print " ".join(str(n * n) for n in range(10)) </lang> Or: <lang python> print " ".join(map(str, map(square, range(10)))) </lang> Result: <lang python> 0 1 4 9 16 25 36 49 64 81 </lang>

Raven

<lang raven>

  1. To print the squared elements

[1 2 3 4 5] each dup * print </lang>

<lang raven>

  1. To obtain a new array

group [1 2 3 4 5] each

 dup *

list </lang>

Ruby

You could use a traditional "for i in arr" approach like below: <lang ruby> for i in [1,2,3,4,5] do

  puts i**2

end </lang>

Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk) <lang ruby> [1,2,3,4,5].each{ |i| puts i**2 } </lang>

To create a new array of each value squared <lang ruby> [1,2,3,4,5].map{ |i| i**2 } </lang>

Scala

<lang scala> val l = List(1,2,3,4) l.foreach {i => println(i)} </lang>

When the argument appears only once -as here, i appears only one in println(i) - it may be shortened to <lang scala> l.foreach(println(_)) </lang> Same for an array <lang scala> val a = Array(1,2,3,4) a.foreach {i => println(i)} a.foreach(println(_)) // same as previous line </lang>

Or for an externally defined function: <lang scala> def doSomething(in: int) = {println("Doing something with "+in)} l.foreach(doSomething) </lang>

There is also a for syntax, which is internally rewritten to call foreach. A foreach method must be defined on a <lang scala> for(val i <- a) println(i) </lang>

It is also possible to apply a function on each item of an list to get a new list (same on array and most collections) <lang scala> val squares = l.map{i => i * i} //squares is List(1,4,9,16) </lang>

Or the equivalent for syntax, with the additional keyword yield, map is called instead of foreach <lang scala> val squares = for (val i <- l) yield i * i </lang>

Scheme

<lang scheme> (define (square n) (* n n)) (define x #(1 2 3 4 5)) (map square (vector->list x)) </lang>

A single-line variation <lang scheme> (map (lambda (n) (* n n)) '(1 2 3 4 5)) </lang>

For completeness, the map function (which is R5RS standard) can be coded as follows: <lang scheme> (define (map f L)

 (if (null? L)
     L
     (cons (f (car L)) (map f (cdr L)))))

</lang>

Smalltalk

<lang smalltalk>

 #( 1 2 3 4 5 ) collect: [:n | n * n].

</lang>

Tcl

If I wanted to call "myfunc" on each element of dat and dat were a list:

<lang tcl> foreach var $dat { myfunc $var } </lang>

if dat were an array, however:

<lang tcl> foreach name [array names dat] { myfunc $dat($name) } </lang>

Toka

<lang toka>

 ( array count function -- )
 {
   value| array fn |
   [ i array ] is I
   [ to fn swap to array 0 swap [ I array.get :stack fn invoke I array.put ] countedLoop ]
 } is map-array
 
 ( Build an array )
 5 cells is-array a
 10 0 a array.put
 11 1 a array.put
 12 2 a array.put
 13 3 a array.put
 14 4 a array.put
 
 ( Add 1 to each item in the array )
 a 5  [ 1 + ] map-array

</lang>

V

apply squaring (dup *) to each member of collection <lang v>

[1 2 3 4] [dup *] map

</lang>