Apply a callback to an array: Difference between revisions

From Rosetta Code
Content added Content deleted
(Undo revision 91391 by 109.125.75.243 (Talk))
Line 1,010: Line 1,010:
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|PureBasic}}==
=={{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:
<lang PureBasic>Procedure Cube(Array param.i(1))
<lang powershell>1..5 | ForEach-Object { $_ * $_ }</lang>
Protected n.i
To recreate a ''map'' function, found in other languages the same method applies:
For n = 0 To ArraySize(param())
<lang powershell>function map ([array] $a, [scriptblock] $s) {
Debug Str(param(n)) + "^3 = " + Str(param(n) * param(n) * param(n))
$a | ForEach-Object $s
Next
}</lang>
EndProcedure

Dim AnArray.i(4)

For n = 0 To ArraySize(AnArray())
AnArray(n) = Random(99)
Next

Cube(AnArray()) </lang>


=={{header|Python}}==
=={{header|Python}}==

Revision as of 20:48, 21 September 2010

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

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny

<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:
(
  [4]INT array := ( 1, 4, 9, 16 );
  map(array, call back proc)
)</lang>

Output:

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

AutoHotkey

<lang AutoHotkey>map("callback", "3,4,5")

callback(array){

 Loop, Parse, array, `,
   MsgBox % (2 * A_LoopField)

}

map(callback, array){

 %callback%(array)

}</lang>

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>

C

callback.h <lang c>#ifndef CALLBACK_H

  1. 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>#include <stdio.h>

  1. 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>#include <iostream> //cout for printing

  1. 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>#include <iostream> // cout for printing

  1. include <algorithm> // for_each defined here
  2. 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 cpp>#include <iostream> // cout for printing

  1. include <algorithm> // for_each defined here
  2. include <vector> // stl vector class
  3. 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 lisp>;; apply a named function, inc (map inc [1 2 3 4])</lang>

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

<lang lisp>;; 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>

Efene

<lang efene>square = fn (N) {

   N * N

}

  1. list comprehension

squares1 = fn (Numbers) {

   [square(N) for N in Numbers]

}

  1. functional form

squares2a = fn (Numbers) {

   lists.map(fn square:1, Numbers)

}

  1. functional form with lambda

squares2b = fn (Numbers) {

   lists.map(fn (N) { N * N }, Numbers)

}

  1. no need for a function

squares3 = fn (Numbers) {

   [N * N for N in Numbers]

}

@public run = fn () {

   Numbers = [1, 3, 5, 7]
   io.format("squares1 : ~p~n", [squares1(Numbers)])
   io.format("squares2a: ~p~n", [squares2a(Numbers)])
   io.format("squares2b: ~p~n", [squares2b(Numbers)])
   io.format("squares3 : ~p~n", [squares3(Numbers)])

} </lang>

Erlang

A list would be more commonly used in Erlang rather than an array.

<lang Erlang> 1> L = [1,2,3]. [1,2,3] </lang>

You can use lists:foreach/2 if you just want to apply the callback to each element of the list.

<lang> 2> lists:foreach(fun(X) -> io:format("~w ",[X]) end, L). 1 2 3 ok </lang>

Or you can use lists:map/2 if you want to create a new list with the result of the callback on each element.

<lang Erlang> 3> lists:map(fun(X) -> X + 1 end, L). [2,3,4] </lang>

Or you can use lists:foldl/3 if you want to accumulate the result of the callback on each element into one value.

<lang Erlang> 4> lists:foldl(fun(X, Sum) -> X + Sum end, 0, L). 6 </lang>

Factor

Print each element squared: <lang factor>{ 1 2 3 4 } [ sq . ] each</lang>

Collect return values: <lang factor>{ 1 2 3 4 } [ sq ] map</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

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

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> Use iter if the applied function does not return a value. <lang fsharp>Array.iter (fun x -> printfn "%d" x) [|1; 2; 3; 4; 5|]</lang>

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 = mapM_ (print.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 and Unicon

Icon

<lang icon>procedure main()

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

end

procedure callback(p,arg)

  return p(" -> ", arg)

end</lang>

Unicon

This Icon solution works in Unicon. A solution that uses Unicon extensions has not been provided.

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

<lang idl>b = a^3</lang>

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

<lang io>list(1,2,3,4,5) map(squared)</lang>

J

Solution: <lang j> "_1</lang>

Example: <lang j> callback =: *:

  array    =:  1 2 3 4 5
  
  callback"_1 array

1 4 9 16 25</lang>

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>

Joy

<lang joy>[1 2 3 4 5] [dup *] map.</lang>

Lisaac

<lang Lisaac>+ a : ARRAY(INTEGER); + b : {INTEGER;};

a := ARRAY(INTEGER).create 1 to 3; 1.to 3 do { i : INTEGER;

 a.put i to i;

};

b := { arg : INTEGER;

 (arg * arg).print;
 '\n'.print;

};

a.foreach b;</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 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.

M4

<lang M4>define(`foreach', `pushdef(`$1')_foreach($@)popdef(`$1')')dnl define(`_arg1', `$1')dnl define(`_foreach', `ifelse(`$2', `()', `',

  `define(`$1', _arg1$2)$3`'$0(`$1', (shift$2), `$3')')')dnl

dnl define(`apply',`foreach(`x',$1,`$2(x)')')dnl dnl define(`z',`eval(`$1*2') ')dnl apply(`(1,2,3)',`z')</lang>

Output:

2 4 6

MATLAB

There are two types of arrays in MATLAB: arrays and cell arrays. MATLAB includes two functions, one for each of these data types, that accomplish the specification for this task. For arrays, we use "arrayfun()"; for cell arrays we use "cellfun()".
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. <lang MATLAB>>> array = [1 2 3 4 5]

array =

    1     2     3     4     5

>> arrayfun(@sin,array)

ans =

 Columns 1 through 4
  0.841470984807897   0.909297426825682   0.141120008059867  -0.756802495307928
 Column 5
 -0.958924274663138

>> cellarray = {1,2,3,4,5}

cellarray =

   [1]    [2]    [3]    [4]    [5]

>> cellfun(@tan,cellarray)

ans =

 Columns 1 through 4
  1.557407724654902  -2.185039863261519  -0.142546543074278   1.157821282349578
 Column 5
 -3.380515006246586</lang>

Modula-3

<lang modula3>MODULE Callback EXPORTS Main;

IMPORT IO, Fmt;

TYPE CallBack = PROCEDURE (a: CARDINAL; b: INTEGER);

    Values = REF ARRAY OF INTEGER;

VAR sample := ARRAY [1..5] OF INTEGER {5, 4, 3, 2, 1};

   callback := Display;

PROCEDURE Display(loc: CARDINAL; val: INTEGER) =

 BEGIN
   IO.Put("array[" & Fmt.Int(loc) & "] = " & Fmt.Int(val * val) & "\n");
 END Display;

PROCEDURE Map(VAR values: ARRAY OF INTEGER; size: CARDINAL; worker: CallBack) =

 VAR lvalues := NEW(Values, size);
 BEGIN
   FOR i := FIRST(lvalues^) TO LAST(lvalues^) DO
     worker(i, values[i]);
   END;
 END Map;

BEGIN

 Map(sample, NUMBER(sample), callback);

END Callback.</lang>

Nial

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

Objeck

<lang objeck> use Structure;

bundle Default {

 class Test {
   function : Main(args : String[]) ~ Nil {
     Run();
   }
   function : native : Run() ~ Nil {
     values := IntVector->New([1, 2, 3, 4, 5]);
     squares := values->Apply(Square(Int) ~ Int);
     each(i : squares) {
       squares->Get(i)->PrintLine();
     };
   }
   
   function : Square(value : Int) ~ Int {
     return value * value;
   }
 }

} </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>

Or with lists (which are more typical in OCaml): <lang ocaml>let values = [1;2;3;4;5;6;7;8;9;10];; List.map square values;;</lang>

Use iter if the applied function does not return a value.

<lang ocaml>Array.iter (fun x -> Printf.printf "%d" x) [|1; 2; 3; 4; 5|];;</lang> <lang ocaml>List.iter (fun x -> Printf.printf "%d" x) [1; 2; 3; 4; 5];;</lang>

with partial application we can also write:

<lang ocaml>Array.iter (Printf.printf "%d") [|1; 2; 3; 4; 5|];;</lang> <lang ocaml>List.iter (Printf.printf "%d") [1; 2; 3; 4; 5];;</lang>

Octave

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 arrayfun can be used.

<lang octave>function e = f(x, y)

 e = x^2 + exp(-1/(y+1));

endfunction

% f([2,3], [1,4]) gives and error, but arrayfun(@f, [2, 3], [1,4]) % works</lang>

(The function f can be rewritten so that it can accept vectors as argument simply changing operators to their dot relatives: e = x.^2 + exp(-1 ./ (y.+1)))


Oz

<lang oz>declare

 fun{Square A}
   A*A
 end
 Lst = [1 2 3 4 5]
 
 %% apply a PROCEDURE to every element
 {ForAll Lst Show}
 %% apply a FUNCTION to every element
 Result = {Map Lst Square}
 {Show Result}</lang>

Perl

<lang perl># create array my @a = (1, 2, 3, 4, 5);

  1. create callback function

sub mycallback {

 return 2 * shift;

}

  1. use array indexing

for (my $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)

  1. filter an array

my @e = grep { $_ % 2 == 0 } @a; # @e is now (2, 4)</lang>

Perl 6

Works with: Rakudo version #21 "Seattle"

<lang perl6>my $function = { 2 * $^x + 3 }; my @array = 1 .. 5;

  1. via map function

.say for map $function, @array;

  1. via map method

.say for @array.map($function);

  1. via for loop

for @array {

   say $function($_);

}

  1. via the "hyper" metaoperator and method indirection

say @array».$function;</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>

PicoLisp

<lang PicoLisp>: (mapc println (1 2 3 4 5)) # Print numbers 1 2 3 4 5 -> 5

(mapcar '((N) (* N N)) (1 2 3 4 5)) # Calculate squares

-> (1 4 9 16 25)

(mapcar ** (1 2 3 4 5) (2 .)) # Same, using a circular list

-> (1 4 9 16 25)

(mapcar if '(T NIL T NIL) '(1 2 3 4) '(5 6 7 8)) # Conditional function

-> (1 6 3 8)</lang>

Pike

<lang pike>int cube(int n) {

   return n*n*n;

}

array(int) a = ({ 1,2,3,4,5 }); array(int) b = cube(a[*]); // automap operator array(int) c = map(a, cube); // conventional map function </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 := x.first;
     -- square array
     while i is not null loop
             x(i) := x(i)*x(i);
             dbms_output.put_line(x(i));
             i := x.next(i);
     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.

PowerShell

This can be done in PowerShell with the ForEach-Object cmdlet which applies a scriptblock to each element of an array: <lang powershell>1..5 | ForEach-Object { $_ * $_ }</lang> To recreate a map function, found in other languages the same method applies: <lang powershell>function map ([array] $a, [scriptblock] $s) {

   $a | ForEach-Object $s

}</lang>

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>

R

Many functions can take advantage of implicit vectorisation, e.g. <lang R>cube <- function(x) x*x*x elements <- 1:5 cubes <- cube(elements)</lang> Explicit looping over array elements is also possible. <lang R>cubes <- numeric(5) for(i in seq_along(cubes)) {

  cubes[i] <- cube(elements[i])

}</lang> Loop syntax can often simplified using the *array family of functions. <lang R>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

Raven

<lang raven># To print the squared elements [1 2 3 4 5] each dup * print</lang>

<lang raven># To obtain a new array group [1 2 3 4 5] each

 dup *

list</lang>

REBOL

<lang REBOL>REBOL [

   Title: "Array Callback"
   Date: 2010-01-04
   Author: oofoe
   URL: http://rosettacode.org/wiki/Apply_a_callback_to_an_Array

]

map: func [ "Apply a function across an array." f [native! function!] "Function to apply to each element of array." a [block!] "Array to process." /local x ][x: copy [] forall a [append x do [f a/1]] x]

square: func [x][x * x]

Tests

assert: func [code][print [either do code [" ok"]["FAIL"] mold code]]

print "Simple loop, modify in place:" assert [[1 100 81] = (a: [1 10 9] forall a [a/1: square a/1] a)]

print [crlf "Functional style with 'map':"] assert [[4 16 36] = map :square [2 4 6]]

print [crlf "Applying native function with 'map':"] assert [[2 4 6] = map :square-root [4 16 36]]</lang>

Output:

Simple loop, modify in place:
  ok [[1 100 81] = (a: [1 100 81] forall a [a/1: square a/1] a)]

Functional style with 'map':
  ok [[4 16 36] = map :square [2 4 6]]

Applying native function with 'map':
  ok [[2 4 6] = map :square-root [4 16 36]]

RLaB

RLaB has two type of arrays: 'standard' or 1-dimensional, that can be a row- or a column-vectory; and, 'associative' which are called lists. For standard array its entry identifier (index) is an integer in range 1:N where N is the size of the array. For associative array its entry identifier is a string consisting of printable ASCII characters.

All scalar mathematical functions are 'matrix-optimized' meaning that if the argument to a function is a matrix, then the return value of the function is a matrix of the same size as the input argument, where the function is applied to the individual entries of the matrix. Consider an example:

<lang RLaB> >> x = rand(2,4)

0.707213207   0.275298961   0.396757763   0.232312312
0.215619868   0.207078017   0.565700032   0.666090571

>> sin(x)

0.649717845   0.271834652   0.386430003   0.230228332
0.213952984   0.205601224   0.536006923   0.617916954

</lang>

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.

<lang RLaB> x = rand(2,4); y = zeros(2,4); for (i in 1:2) {

 for (j in 1:4)
 {
   y[i;j] = sin( x[i;j] );
 }

} </lang>


The functions can take lists as arguments, but then it has to be specified within the body of the function what to do with the list elements. Given a list call it 'x' there is a RLaB function 'members' which returns a string vector with the names of the elements of the list.

<lang RLaB> x = <<>>; for (i in 1:9) {

 x.[i] = rand();

}

y = <<>>; for (i in members(x)) {

 y.[i] = sin( x.[i] );

} </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>

Sather

<lang sather>class MAIN is

 do_something(i:INT):INT is
   return i * i;
 end;
 main is
   a:ARRAY{INT} := |1, 2, 3, 4, 5|;
   -- we use an anonymous closure to apply our do_something "callback"
   a.map(bind(do_something(_)));
   loop #OUT + a.elt! + "\n"; end;
 end;

end;</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>

Slate

<lang slate>#( 1 2 3 4 5 ) collect: [| :n | n * n].</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> This does not retain any of the values returned by myfunc.

if dat were an (associative) array, however: <lang tcl>foreach name [array names dat] {

   myfunc $dat($name)

}</lang>

More functional, with a simple map function: <lang Tcl>proc map {f list} {

  set res {}
  foreach e $list {lappend res [$f $e]}
  return $res

} proc square x {expr {$x*$x}}

% map square {1 2 3 4 5} 1 4 9 16 25</lang>

TI-89 BASIC

<lang ti89b>© For no return value Define foreach(fe_cname,fe_list) = Prgm

 Local fe_i
 For fe_i,1,dim(fe_list)
   #fe_cname(fe_list[fe_i])
 EndFor

EndPrgm

© For a list of results Define map(map_cnam,map_list) = seq(#map_cnam(map_list[map_i]),map_i,1,dim(map_list))

Define callback(elem) = Prgm

 Disp elem

EndPrgm

foreach("callback", {1,2,3,4,5}) Disp map("√", {1,2,3,4,5})</lang>

Output:






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>

Ursala

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

  1. cast %nL

demo = successor* <325,32,67,1,3,7,315></lang> output:

<326,33,68,2,4,8,316>

V

apply squaring (dup *) to each member of collection <lang v>[1 2 3 4] [dup *] map</lang>

VBScript

I really have my doubts as to whether this really counts as a callback. I used the same thing in the solution to Amb.

Implementation

<lang vb> class callback dim sRule

public property let rule( x ) sRule = x end property

public default function applyTo(a) dim p1 for i = lbound( a ) to ubound( a ) p1 = a( i ) a( i ) = eval( sRule ) next applyTo = a end function end class </lang>

Invocation

<lang vb> dim a1 dim cb set cb = new callback

cb.rule = "ucase(p1)" a1 = split("my dog has fleas", " " ) cb.applyTo a1 wscript.echo join( a1, " " )

cb.rule = "p1 ^ p1" a1 = array(1,2,3,4,5,6,7,8,9,10) cb.applyto a1 wscript.echo join( a1, ", " )

</lang>

Output
MY DOG HAS FLEAS
1, 4, 27, 256, 3125, 46656, 823543, 16777216, 387420489, 10000000000

Vorpal

Given and array, A, and a function, F, mapping F over the elements of A is simple: <lang vorpal>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>

Zsh

<lang zsh>map(){for i ($*[2,-1]) $1 $i} a=(1 2 3) map print $a</lang>