Apply a callback to an array: Difference between revisions

Added Maple implementation
(Added BBC BASIC)
(Added Maple implementation)
Line 1,011:
2 4 6
</pre>
 
=={{header|Maple}}==
For lists and sets, which in Maple are immutable, a new object is returned. Either the built-in procedure map, or the short syntax of a trailing tilde (~) on the applied operator may be used.
<lang Maple>
> map( sqrt, [ 1.1, 3.2, 5.7 ] );
[1.048808848, 1.788854382, 2.387467277]
 
> map( x -> x + 1, { 1, 3, 5 } );
{2, 4, 6}
 
> sqrt~( [ 1.1, 3.2, 5.7 ] );
[1.048808848, 1.788854382, 2.387467277]
 
> (x -> x + 1)~( { 1, 3, 5 } );
{2, 4, 6}
</lang>
For Arrays (Vectors, Matrices, etc.) both map and trailing tilde also work, and by default create a new object, leaving the input Array unchanged.
<lang Maple>
> a := Array( [ 1.1, 3.2, 5.7 ] );
a := [1.1, 3.2, 5.7]
 
> sqrt~( a );
[1.048808848, 1.788854382, 2.387467277]
 
> a;
[1.1, 3.2, 5.7]
 
> map( sqrt, a );
[1.048808848, 1.788854382, 2.387467277]
 
> a;
[1.1, 3.2, 5.7]
</lang>
However, since these are mutable data structures in Maple, it is possible to use map to modify its input according to the applied procedure.
<lang Maple>
> map[inplace]( sqrt, a );
[1.048808848, 1.788854382, 2.387467277]
 
> a;
[1.048808848, 1.788854382, 2.387467277]
</lang>
The Array a has been modified.
 
It is also possible to pass additional arguments to the mapped procedure.
<lang Maple>
> map( `+`, [ 1, 2, 3 ], 3 );
[4, 5, 6]
</lang>
Passing additional arguments *before* the arguments from the mapped data structure is achieved using map2, or the more general map[n] procedure.
<lang Maple>
> map2( `-`, 5, [ 1, 2, 3 ] );
[4, 3, 2]
 
> map[2]( `/`, 5, [ 1, 2, 3 ] );
[5, 5/2, 5/3]
</lang>
 
=={{header|Mathematica}}==
Anonymous user