Apply a callback to an array: Difference between revisions

(→‎{{header|NetLogo}}: corrected syntax. No curly braces in NetLogo)
Line 2,448:
$b = array_map("cube", $a);
print_r($b);</lang>
 
=={{header|Picat}}==
Picat doesn't support anonymous (lambda) functions so the function must be defined in the program to be used by - say - map/2.
There are - however - quite a few ways without proper lambdas, using map/2, apply/2, or list comprehensions.
<lang Picat>go =>
L = 1..10,
 
% Using map/2 in different ways
println(L.map(fun)),
println(map(L,fun)),
println(map(fun,L)),
 
% List comprehensions
println([fun(I) : I in L]),
 
% Using apply/2
println([apply(fun,I) : I in L]),
 
% And using list comprehension with the function directly.
println([I*I : I in L]),
nl.
 
% Some function
fun(X) = X*X.
</lang>
 
 
This variant is inspired by the Prolog solution (using assert/1 to define a predicate) and shows the integration with Picat's underlying B-Prolog engine.
 
Picat does not support assert/1 directly, so one have to do the assert/1 in the bp module space (the module/space for the B-Prolog engine). To call the defined predicate, one must prepend the predicate name with "bp.".
 
Note that fun2/2 is not a function so map/2 or apply/2 cannot be used here.
<lang Picat>go2 =>
L = 1..10,
 
% Define the predicate _in the bp space_.
bp.assert( $(fun2(X,Y) :- Y is X*X) ),
 
% Use bp.fun2 to call the function.
println([B : A in L, bp.fun2(A,B)]),
nl.
</lang>
 
Using this technique one can do quite much "real" Prolog stuff even though Picat doesn't support it directly. However, one should be careful with this approach since it can sometimes be confusing and it doesn't work in all cases.
 
=={{header|PicoLisp}}==
495

edits