Apply a callback to an array: Difference between revisions

m
<lang>
m (<code>, fixed use of reserved identifier in C code, some minor formatting improvements)
m (<lang>)
Line 2:
 
=={{header|ActionScript}}==
<codelang actionscript>
package
{
Line 22:
}
}
</codelang>
 
=={{header|Ada}}==
{{works with|GNAT|GPL 2005}}
<codelang ada>
with Ada.Text_Io;
with Ada.Integer_text_IO;
Line 64:
Map(Sample, Display'access);
end Call_Back_Example;
</codelang>
 
=={{header|ALGOL 68}}==
Line 97:
{{works with|ICC|9.1}}
===callback.h===
<codelang c>
#ifndef CALLBACK_H
#define CALLBACK_H
Line 114:
 
#endif
</codelang>
 
===callback.c===
<codelang c>
#include <stdio.h>
#include "callback.h"
Line 145:
return 0;
}
</codelang>
 
===Output===
Line 157:
{{works with|C sharp|C#|2.0+}}
{{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+}}
This version uses the C# 3 lambda notation.
 
<lang csharp>
int[] intArray = { 1, 2, 3, 4, 5 };
Array.ForEach(int[] intArray = { 1, i2, =>3, Console.WriteLine(i4, *5 i))};
Array.ForEach(intArray, i => Console.WriteLine(i * i));
</lang>
 
=={{header|C++}}==
Line 203 ⟶ 206:
{{works with|g++|4.1.1}}
===C-Style Array===
<codelang cpp>
#include <iostream> //cout for printing
#include <algorithm> //for_each defined here
Line 220 ⟶ 223:
}
//prints 1 4 9 16 25
</codelang>
 
===std::vector===
{{libheader|STL}}
<codelang cpp>
#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
Line 247 ⟶ 250:
}
//prints 1 4 9 16 25
</codelang>
 
More tricky with binary function
<codelang>
#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
Line 275 ⟶ 278:
}
//prints 1x 2x 3x 4x 5x
</codelang>
 
===Boost.Lambda===
{{libheader|Boost}}
<codelang cpp>
using namespace std;
using namespace boost::lambda;
Line 286 ⟶ 289:
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
</codelang>
 
=={{header|Clean}}==
Line 292 ⟶ 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]#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}
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{#Int}
Start = mapArray square values
</lang>
 
=={{header|Common Lisp}}==
Line 310 ⟶ 319:
Imperative: print 1, 2, 3, 4 and 5:
 
<codelang lisp>
(map nil #'print #(1 2 3 4 5))
</codelang>
 
Functional: collect squares into new vector that is returned:
 
<codelang lisp>
(defun square (x) (* x x))
(map 'vector #'square #(1 2 3 4 5))
</codelang>
 
Destructive, like the Javascript example; add 1 to every slot of vector *a*:
 
<codelang lisp>
(defvar *a* (vector 1 2 3))
(map-into *a* #'1+ *a*)
</codelang>
 
=={{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}}==
<codelang d>
U[] map(T, U)(T[] array, U delegate(T) dg) {
auto result = new U[array.length];
Line 355 ⟶ 370:
);
}
</codelang>
Using std.algorithm:
<codelang d>
writefln(map!("a + 5")([1, 2, 3, 4, 5]));
</codelang>
 
=={{header|E}}==
 
<lang e>
def array := [1,2,3,4,5]
def array := [1,2,3,4,5]
def square(value) {
def return square(value) *{ value
return value * value
}
}
</lang>
 
Example of builtin iteration:
 
<lang e>
def callback(index, value) {
def printlncallback(`Item $index, is $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).
 
<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}}==
Line 390 ⟶ 411:
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:
 
<lang forth>
create data 1 , 2 , 3 , 4 , 5 ,
create data 5 ' 1+ map, 2 \, adds3 one, to4 each, element5 of data,
data 5 ' 1+ map \ adds one to each element of data
</lang>
 
=={{header|Fortran}}==
Line 402 ⟶ 427:
 
{{Works with |Fortran|ISO 95 and later}}
<codelang fortran>
module arrCallback
contains
Line 412 ⟶ 437:
end function cube
end module arrCallback
</codelang>
 
<codelang fortran>
program testAC
use arrCallback
Line 432 ⟶ 457:
end do
end program testAC
</codelang>
 
{{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-- Declare array:
Line 456 ⟶ 475:
C
end
</codelang>
 
=={{header|FP}}==
Line 465 ⟶ 484:
 
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>
 
=={{header|Haskell}}==
Line 474 ⟶ 497:
===List===
{{works with|GHC}}
<codelang haskell>
let square x = x*x
let values = [1..10]
map square values
</codelang>
 
Using list comprehension to generate a list of the squared values
<codelang haskell>
[square x | x <- values]
</codelang>
 
Using function composition to create a function that will print the squares of a list
<codelang haskell>
let printSquares = putStr.unlines.map (show.square)
printSquares values
</codelang>
 
===Array===
{{works with|GHC}}
<codelang 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
</codelang>
 
=={{header|Icon}}==
<lang icon>
procedure main()
procedure main()
local lst
local lst := [10, 20, 30, 40]
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}}==
Line 541 ⟶ 565:
So if you want to perform an action (which doesn't return anything) on an array of int's:
 
<codelang java>
interface IntToVoid {
void run(int x);
Line 553 ⟶ 577:
}.run(z);
}
</codelang>
 
Or if you want to perform "map" - return an array of the results of function applications:
 
<codelang java>
interface IntToInt {
int run(int x);
Line 571 ⟶ 595:
}.run(myIntArray[i]);
}
</codelang>
 
=={{header|JavaScript}}==
Line 577 ⟶ 601:
Portable technique:
 
<codelang javascript>
function map(a, func) {
for (var i in a)
Line 585 ⟶ 609:
var a = [1, 2, 3, 4, 5];
map(a, function(v) { return v * v; });
</codelang>
 
{{libheader|BeyondJS}}
With the [http://w3future.com/html/beyondJS/ BeyondJS] library:
 
<codelang javascript>
var a = (1).to(10).collect(Math.pow.curry(undefined,2));
</codelang>
 
With Firefox 2.0:
 
<codelang javascript>
function cube(num) {
return Math.pow(num, 3);
Line 603 ⟶ 627:
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)];
</codelang>
 
{{libheader|Functional}}
<codelang javascript>
Functional.map('x*x*x', [1,2,3,4,5])
</codelang>
=={{header|Logo}}==
<lang logo>
to square :x
to output :x *square :x
output :x * :x
end
end
show map "square [1 2 3 4 5] ; [1 4 9 16 25]
show map [? * ?]"square [1 2 3 4 5] ; [1 4 9 16 25]
foreachshow map [? * ?] [1 2 3 4 5] [print square ?] ; [1 4 9 16 25, one per line]
foreach [1 2 3 4 5] [print square ?] ; 1 4 9 16 25, one per line
</lang>
 
=={{header|Lua}}==
 
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
<lang lua>
map = function(f, data)
map = function(f, data)
local result = {}
local result = {}
for k,v in ipairs(data) do
for result[k],v =in fipairs(vdata) 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:
<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.
 
=={{header|Nial}}==
 
<lang nial>
each (* [first, first] ) 1 2 3 4
=1 4 9 16
</lang>
 
=={{header|OCaml}}==
This function is part of the standard library:
 
<codelang ocaml>
Array.map
</codelang>
 
Usage example:
<codelang ocaml>
let square x = x * x;;
let values = Array.init 10 ((+) 1);;
Array.map square values;;
</codelang>
 
=={{header|Oz}}==
<prelang oz>
functor
import
Line 693 ⟶ 727:
{Application.exit 0}
end
</prelang>
=={{header|Perl}}==
<codelang perl>
# create array
my @a = (1, 2, 3, 4, 5);
Line 724 ⟶ 758:
my $func = \&mycallback;
my @d = map $func->($_), @a; # @d is now (2, 4, 6, 8, 10)
</codelang>
 
=={{header|PHP}}==
<codelang php>
function cube($n)
{
Line 736 ⟶ 770:
$b = array_map("cube", $a);
print_r($b);
</codelang>
 
=={{header|PL/SQL}}==
{{works with|Oracle}}
<codelang plsql>
set serveroutput on
declare
Line 766 ⟶ 800:
end;
/
</codelang>
 
=={{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
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.
 
=={{header|Python}}==
<codelang python>
def square(n):
return n * n
Line 803 ⟶ 839:
import itertools
isquares2 = itertools.imap(square, numbers) # iterator, lazy
</codelang>
To print squares of integers in the range from 0 to 9, type:
<codelang python>
print " ".join(str(n * n) for n in range(10))
</codelang>
Or:
<codelang python>
print " ".join(map(str, map(square, range(10))))
</codelang>
Result:
<codelang python>
0 1 4 9 16 25 36 49 64 81
</codelang>
 
=={{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
group [1 2 3 dup4 *5] each
listdup *
list
</lang>
 
=={{header|Ruby}}==
You could use a traditional "for i in arr" approach like below:
<codelang ruby>
for i in [1,2,3,4,5] do
puts i**2
end
</codelang>
 
Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk)
<codelang ruby>
[1,2,3,4,5].each{ |i| puts i**2 }
</codelang>
 
To create a new array of each value squared
<codelang ruby>
[1,2,3,4,5].map{ |i| i**2 }
</codelang>
 
=={{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
<lang scala>
l.foreach(println(_))
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( {i => println(_i)) '' // same as previous line''}
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)}
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''
<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)
<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
<lang scala>
val squares = for (val i <- l) yield i * i
val squares = for (val i <- l) yield i * i
</lang>
 
=={{header|Scheme}}==
<codelang scheme>
(define (square n) (* n n))
(define x #(1 2 3 4 5))
(map square (vector->list x))
</codelang>
 
A single-line variation
<codelang scheme>
(map (lambda (n) (* n n)) '(1 2 3 4 5))
</codelang>
 
For completeness, the <tt>map</tt> function (which is R5RS standard) can be coded as follows:
<codelang scheme>
(define (map f L)
(if (null? L)
L
(cons (f (car L)) (map f (cdr L)))))
</codelang>
 
=={{header|Smalltalk}}==
<codelang smalltalk>
#( 1 2 3 4 5 ) collect: [:n | n * n].
</codelang>
=={{header|Tcl}}==
 
If I wanted to call "<tt>myfunc</tt>" on each element of <tt>dat</tt> and <tt>dat</tt> were a list:
 
<codelang tcl>
foreach var $dat { myfunc $var }
</codelang>
 
if <tt>dat</tt> were an array, however:
 
<codelang tcl>
foreach name [array names dat] { myfunc $dat($name) }
</codelang>
 
=={{header|Toka}}==
 
<lang toka>
( array count function -- )
{
Line 926 ⟶ 981:
( Add 1 to each item in the array )
a 5 [ 1 + ] map-array
</lang>
 
=={{header|V}}==
apply squaring (dup *) to each member of collection
<lang v>
[1 2 3 4] [dup *] map
</lang>
973

edits