How do I pass a function as an argument?
The basic idea is something like this (which doesn't work):
∇R ← double a
R ← 2 × a
∇
∇R ← a applytwice f
R ← f f a
∇
5 applytwice double
Is there something like \fun
in erlang or function-pointers in C?
Arguments are passed by value; that is, when a function is called, the parameter receives a copy of the argument's value, not its address. This rule applies to all scalar values, structures, and unions passed as arguments. Modifying a parameter does not modify the corresponding argument passed by the function call.
Unlike many programming languages which use parentheses or brackets for function calls, function application in APL is written simply by writing the function next to its arguments.
Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, a function greet is created which takes a function as an argument.
In APL, functions may not be passed as arguments to functions. However, APL has operators, which are higher order functions, that can take functions as arguments. There are primitive operators like / (reduction) used for example to sum up a vector +/v. The function + is the left operand and is passed into the operator /.
In Dyalog APL, there is a primitive operator using the (named "power") for apply a function n times so we can write:
double←{2×⍵}
(double ⍣ 2) 7
28
(double ⍣ 10) 7
7168
You can also write your own operators (in most APLs). In Dyalog APL we can write your applytwice operator as:
applytwice←{⍺⍺ ⍺⍺ ⍵}
double applytwice 7
28
Finally, you can pass functions around by putting them in a namespace and passing the namespace around instead. This is like a very light weight instance of class with a method. For example:
s←⎕NS ''
s.f←{2×⍵}
ApplyFTwice←{⍺.f ⍺.f ⍵}
s ApplyFTwice 7
28
In this case, the function has to be named f, but we could many different functions named f, each in its own namespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With