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}}==
<
package
{
Line 22:
}
}
</
=={{header|Ada}}==
{{works with|GNAT|GPL 2005}}
<
with Ada.Text_Io;
with Ada.Integer_text_IO;
Line 64:
Map(Sample, Display'access);
end Call_Back_Example;
</
=={{header|ALGOL 68}}==
Line 97:
{{works with|ICC|9.1}}
===callback.h===
<
#ifndef CALLBACK_H
#define CALLBACK_H
Line 114:
#endif
</
===callback.c===
<
#include <stdio.h>
#include "callback.h"
Line 145:
return 0;
}
</
===Output===
Line 157:
{{works with|C sharp|C#|2.0+}}
{{works with|Visual C sharp|Visual C#|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 sharp|C#|3.0+}}
This version uses the C# 3 lambda notation.
<lang csharp>
Array.ForEach(intArray, i => Console.WriteLine(i * i));
</lang>
=={{header|C++}}==
Line 203 ⟶ 206:
{{works with|g++|4.1.1}}
===C-Style Array===
<
#include <iostream> //cout for printing
#include <algorithm> //for_each defined here
Line 220 ⟶ 223:
}
//prints 1 4 9 16 25
</
===std::vector===
{{libheader|STL}}
<
#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
Line 247 ⟶ 250:
}
//prints 1 4 9 16 25
</
More tricky with binary function
<
#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
Line 275 ⟶ 278:
}
//prints 1x 2x 3x 4x 5x
</
===Boost.Lambda===
{{libheader|Boost}}
<
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
</
=={{header|Clean}}==
Line 292 ⟶ 295:
Define a function and an initial (unboxed) array.
<lang clean>
square x = x * x
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 = mapArray square values
</lang>
=={{header|Common Lisp}}==
Line 310 ⟶ 319:
Imperative: print 1, 2, 3, 4 and 5:
<
(map nil #'print #(1 2 3 4 5))
</
Functional: collect squares into new vector that is returned:
<
(defun square (x) (* x x))
(map 'vector #'square #(1 2 3 4 5))
</
Destructive, like the Javascript example; add 1 to every slot of vector *a*:
<
(defvar *a* (vector 1 2 3))
(map-into *a* #'1+ *a*)
</
=={{header|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>
=={{header|D}}==
<
U[] map(T, U)(T[] array, U delegate(T) dg) {
auto result = new U[array.length];
Line 355 ⟶ 370:
);
}
</
Using std.algorithm:
<
writefln(map!("a + 5")([1, 2, 3, 4, 5]));
</
=={{header|E}}==
<lang e>
def array := [1,2,3,4,5]
def
return value * value
}
</lang>
Example of builtin iteration:
<lang e>
def
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>
=={{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 -- )
-rot cells bounds do i @ over execute i ! cell +loop ;
</lang>
Example usage:
<lang forth>
data 5 ' 1+ map \ adds one to each element of data
</lang>
=={{header|Fortran}}==
Line 402 ⟶ 427:
{{Works with |Fortran|ISO 95 and later}}
<
module arrCallback
contains
Line 412 ⟶ 437:
end function cube
end module arrCallback
</
<
program testAC
use arrCallback
Line 432 ⟶ 457:
end do
end program testAC
</
{{Works with|ANSI FORTRAN| 77 (with MIL-STD-1753 structured DO) and later}}
<lang fortran>
program test
C
C-- Declare array:
Line 456 ⟶ 475:
C
end
</
=={{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}}
<
let square x = x*x
let values = [1..10]
map square values
</
Using list comprehension to generate a list of the squared values
<
[square x | x <- values]
</
Using function composition to create a function that will print the squares of a list
<
let printSquares = putStr.unlines.map (show.square)
printSquares values
</
===Array===
{{works with|GHC}}
<
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
</
=={{header|Icon}}==
<lang icon>
procedure main()
local lst
lst := [10, 20, 30, 40]
every callback(!lst)
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:
<
interface IntToVoid {
void run(int x);
Line 553 ⟶ 577:
}.run(z);
}
</
Or if you want to perform "map" - return an array of the results of function applications:
<
interface IntToInt {
int run(int x);
Line 571 ⟶ 595:
}.run(myIntArray[i]);
}
</
=={{header|JavaScript}}==
Line 577 ⟶ 601:
Portable technique:
<
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; });
</
{{libheader|BeyondJS}}
With the [http://w3future.com/html/beyondJS/ BeyondJS] library:
<
var a = (1).to(10).collect(Math.pow.curry(undefined,2));
</
With Firefox 2.0:
<
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)];
</
{{libheader|Functional}}
<
Functional.map('x*x*x', [1,2,3,4,5])
</
=={{header|Logo}}==
<lang logo>
to
output :x * :x
end
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}
</lang>
A map function for this would be
<lang lua>
map = function(f, data)
local result = {}
for
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.
=={{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:
<
Array.map
</
Usage example:
<
let square x = x * x;;
let values = Array.init 10 ((+) 1);;
Array.map square values;;
</
=={{header|Oz}}==
<
functor
import
Line 693 ⟶ 727:
{Application.exit 0}
end
</
=={{header|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)
</
=={{header|PHP}}==
<
function cube($n)
{
Line 736 ⟶ 770:
$b = array_map("cube", $a);
print_r($b);
</
=={{header|PL/SQL}}==
{{works with|Oracle}}
<
set serveroutput on
declare
Line 766 ⟶ 800:
end;
/
</
=={{header|Pop11}}==
<lang pop11>
;;; Define a procedure
define proc(x);
printf(x*x, '%p,');
enddefine;
</lang>
If one wants to create a new array consisting of transformed values then procedure mapdata may be more convenient.
=={{header|Python}}==
<
def square(n):
return n * n
Line 803 ⟶ 839:
import itertools
isquares2 = itertools.imap(square, numbers) # iterator, lazy
</
To print squares of integers in the range from 0 to 9, type:
<
print " ".join(str(n * n) for n in range(10))
</
Or:
<
print " ".join(map(str, map(square, range(10))))
</
Result:
<
0 1 4 9 16 25 36 49 64 81
</
=={{header|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
list
</lang>
=={{header|Ruby}}==
You could use a traditional "for i in arr" approach like below:
<
for i in [1,2,3,4,5] do
puts i**2
end
</
Or you could the more preferred ruby way of an iterator (which is borrowed from SmallTalk)
<
[1,2,3,4,5].each{ |i| puts i**2 }
</
To create a new array of each value squared
<
[1,2,3,4,5].map{ |i| i**2 }
</
=={{header|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(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>
=={{header|Scheme}}==
<
(define (square n) (* n n))
(define x #(1 2 3 4 5))
(map square (vector->list x))
</
A single-line variation
<
(map (lambda (n) (* n n)) '(1 2 3 4 5))
</
For completeness, the <tt>map</tt> function (which is R5RS standard) can be coded as follows:
<
(define (map f L)
(if (null? L)
L
(cons (f (car L)) (map f (cdr L)))))
</
=={{header|Smalltalk}}==
<
#( 1 2 3 4 5 ) collect: [:n | n * n].
</
=={{header|Tcl}}==
If I wanted to call "<tt>myfunc</tt>" on each element of <tt>dat</tt> and <tt>dat</tt> were a list:
<
foreach var $dat { myfunc $var }
</
if <tt>dat</tt> were an array, however:
<
foreach name [array names dat] { myfunc $dat($name) }
</
=={{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>
|