Apply a callback to an array: Difference between revisions
m
<code>, fixed use of reserved identifier in C code, some minor formatting improvements
No edit summary |
m (<code>, fixed use of reserved identifier in C code, some minor formatting improvements) |
||
Line 2:
=={{header|ActionScript}}==
<code actionscript>
package
{
Line 22:
}
}
</code>
=={{header|Ada}}==
{{works with|GNAT|GPL 2005}}
<code ada>
with Ada.Text_Io;
with Ada.Integer_text_IO;
Line 62 ⟶ 63:
begin
Map(Sample, Display'access);
end Call_Back_Example;
</code>
=={{header|ALGOL 68}}==
Line 95 ⟶ 97:
{{works with|ICC|9.1}}
===callback.h===
<code c>
#ifndef CALLBACK_H
#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));
#endif
</code>
===callback.c===
<code>
#include <stdio.h>
#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)
{
}
void map(int* array, int len, void(*callback)(int,int))
{
int i;
for(i = 0; i < len; i++)
{
}
}
int main()
{
int array[] = { 1, 2, 3, 4 };
map(array, 4, callbackFunction);
return 0;
}
</code>
===Output===
Line 194 ⟶ 203:
{{works with|g++|4.1.1}}
===C-Style Array===
<code cpp>
#include <iostream> //cout for printing
#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
return 0;
}
//prints 1 4 9 16 25
</code>
===std::vector===
{{libheader|STL}}
<code cpp>
#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
#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);
// stl for_each
std::for_each(ary.begin(),ary.end(),print_square);
return 0;
}
//prints 1 4 9 16 25
</code>
More tricky with binary function
<code>
#include <iostream> // cout for printing
#include <algorithm> // for_each defined here
#include <vector> // stl vector class
#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);
// 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
</code>
===Boost.Lambda===
{{libheader|Boost}}
<code cpp>
</code>
=={{header|Clean}}==
Line 291 ⟶ 310:
Imperative: print 1, 2, 3, 4 and 5:
<code lisp>
(map nil #'print #(1 2 3 4 5))
</code>
Functional: collect squares into new vector that is returned:
<code lisp>
(map 'vector #'square #(1 2 3 4 5))
</code>
Destructive, like the Javascript example; add 1 to every slot of vector *a*:
<code lisp>
(map-into *a* #'1+ *a*)
</code>
=={{header|Clojure}}==
Line 315 ⟶ 340:
=={{header|D}}==
<code d>
U[] map(T, U)(T[] array, U delegate(T) dg) {
auto result = new U[array.length];
Line 328 ⟶ 354:
[1, 2, 3, 4, 5].map( (int i) { return i+5; } )
);
}
</code>
Using std.algorithm:
<code d>
writefln(map!("a + 5")([1, 2, 3, 4, 5]));
</code>
=={{header|E}}==
Line 373 ⟶ 402:
{{Works with |Fortran|ISO 95 and later}}
<code fortran>
module arrCallback
contains
elemental function cube( x )
implicit
real,
end function cube
end module arrCallback
</code>
<code fortran>
program testAC
use
implicit none
real, dimension(3,4) :: b, &
a = reshape( (/ ((10 * i + j, i = 1, 3), j = 1, 4) /), (/ 3,4 /) )
do i =
end
b = cube( a
! and stores each result in the equivalent element of b
do i =
end do
end program testAC
</code>
{{Works with|ANSI FORTRAN| 77 (with MIL-STD-1753 structured DO) and later}}
<!-- NOTE TO EDITORS OF THIS EXAMPLE:
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:
integer
C
C-- Fill it with Data
data
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
</code>
=={{header|FP}}==
Line 433 ⟶ 474:
===List===
{{works with|GHC}}
<code haskell>
let square x = x*x
let values = [1..10]
map square values
</code>
Using list comprehension to generate a list of the squared values
<code haskell>
[square x | x <- values]
</code>
Using function composition to create a function that will print the squares of a list
<code haskell>
printSquares values
</code>
===Array===
{{works with|GHC}}
<code 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
</code>
=={{header|Icon}}==
Line 492 ⟶ 541:
So if you want to perform an action (which doesn't return anything) on an array of int's:
<code java>
interface IntToVoid {
void run(int x);
}
Line 502 ⟶ 552:
}
}.run(z);
}
</code>
Or if you want to perform "map" - return an array of the results of function applications:
<code java>
interface IntToInt {
int run(int x);
}
Line 518 ⟶ 570:
}
}.run(myIntArray[i]);
}
</code>
=={{header|JavaScript}}==
Line 524 ⟶ 577:
Portable technique:
<code javascript>
function map(a, func) {
for (var
a[i] = func(a[i]);
}
var a = [1, 2, 3, 4, 5];
map(a, function(v) { return v * v; });
</code>
{{libheader|BeyondJS}}
With the [http://w3future.com/html/beyondJS/ BeyondJS] library:
<code javascript>
var a = (1).to(10).collect(Math.pow.curry(undefined,2));
</code>
With Firefox 2.0:
<code 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)];
</code>
{{libheader|Functional}}
<code javascript>
Functional.map('x*x*x', [1,2,3,4,5])
</code>
=={{header|Logo}}==
to square :x
Line 593 ⟶ 653:
This function is part of the standard library:
<code ocaml>
Array.map
</code>
Usage example:
<code ocaml>
</code>
=={{header|Oz}}==
Line 629 ⟶ 692:
{Application.exit 0}
end
</pre>
=={{header|Perl}}==
<code perl>
# create array
my @a = (1, 2, 3, 4, 5);
sub mycallback {
return 2 * shift;
}
# use array indexing
my $i;
for ($i = 0; $i < scalar @a; $i++) {
print "mycallback($a[$i]) = ", mycallback($a[$i]), "\n";
}
# using foreach
foreach my $x (@a) {
print "mycallback($x) = ", mycallback($x), "\n";
}
# using map (useful for transforming an array)
my @b = map mycallback($_), @a; # @b is now (2, 4, 6, 8, 10)
# and the same using an anonymous function
# use a callback stored in a variable
my $func = \&mycallback;
my @d = map $func->($_), @a; # @d is now (2, 4, 6, 8, 10)
</code>
=={{header|PHP}}==
<code php>
function cube($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
</code>
=={{header|PL/SQL}}==
{{works with|Oracle}}
<code plsql>
set serveroutput on
declare
type myarray is table of number index by binary_integer;
x
i pls_integer;
begin
-- populate
for i in 1..5
end
i :=0;
-- square
i :=
x(i) :=
exception
end loop;
end;
/
</code>
=={{header|Pop11}}==
Line 716 ⟶ 784:
=={{header|Python}}==
<code python>
def square(n):
return n * n
Line 735 ⟶ 803:
import itertools
isquares2 = itertools.imap(square, numbers) # iterator, lazy
</
To print squares of integers in the range from 0 to 9, type:
<code python>
print " ".join(str(n * n) for n in range(10))
</code>
Or:
<code python>
print " ".join(map(str, map(square, range(10))))
</code>
Result:
0 1 4 9 16 25 36 49 64 81
</code>
=={{header|Raven}}==
Line 754 ⟶ 828:
=={{header|Ruby}}==
<code ruby>
for i in [1,2,3,4,5] do
puts i**2
end
</code>
<code ruby>
[1,2,3,4,5].each{ |i| puts i**2 }
</code>
<code ruby>
[1,2,3,4,5].map{ |i| i**2 }
</code>
=={{header|Scala}}==
Line 790 ⟶ 870:
=={{header|Scheme}}==
<code scheme>
(define x #(1 2 3 4 5))
(map square (vector->list x))
</code>
A single-line variation
<code scheme>
(map (lambda (n) (* n n)) '(1 2 3 4 5))
</code>
For completeness, the <tt>map</tt> function (which is R5RS standard) can be coded as follows:
<code scheme>
(if
L
(cons (f (car L)) (map f (cdr L)))))
</code>
=={{header|Smalltalk}}==
<code smalltalk>
#( 1 2 3 4 5 ) collect: [:n | n * n].
</code>
=={{header|Tcl}}==
If I wanted to call "<tt>myfunc</tt>" on each element of <tt>dat</tt> and <tt>dat</tt> were a list:
<code tcl>
foreach var $dat { myfunc $var }
</code>
if <tt>dat</tt> were an array, however:
<code tcl>
foreach name [array names dat] { myfunc $dat($name) }
</code>
=={{header|Toka}}==
|