How can one define a pervasive function in APL?
What I do is
function←{
(⊃⍣(⍬≡⍴⍵)){the function that apply to scalar}¨⍵
}
I think there should be a better way to do this that I'm not seeing it.
Built-in APL functions (or 'primitive' functions) are denoted by symbols (such as +-÷×). Primitive functions can be either monadic(which means they take a single right argument), or dyadic(in which case they take an argument on the left and an argument on the right). The same symbol may have both monadic and dyadic forms. Execution order
APL programmers often assign informal names when discussing functions and operators (for example, product for ×/) but the core functions and operators provided by the language are denoted by non-textual symbols. Most symbols denote functions or operators. A monadic function takes as its argument the result of evaluating everything to its right.
APL is a very rich language, and due to the general nature of its primitive functions and operators there are always plenty of different ways to express different solutions to a given problem.
In an APL expression, each function takes as its right argument the result of the entire expression to its right. No functions have higher precedence than any others. If the function is dyadic (takes both a left and a right argument), it takes as its left argument the array immediately to its left, delimited by the next function.
Most primitive functions in APL are already pervasive. So, unless you do fancy stuff, your custom functions will already be pervasive. For instance
f←{÷1+*-⍵} ⍝ sigmoid, f(x)=1/(1+exp(-x))
will work on arrays as well as scalars.
If you do do fancy stuff and you have a non-pervasive function f
, you can turn it into a
pervasive one by
g←{0=⍴⍴⍵:f⍵ ⋄ ∇¨⍵} ⍝ the pervasive version of f
which can be read as: if the argument is a scalar, apply f
on it, otherwise recursively go into each item of the argument.
The dfns
workspace contains the perv
operator which causes its operand function to be applied pervasively, with either one or two arguments:
perv←{⍺←⊢ ⍝ Scalar pervasion
1=≡⍺ ⍵ ⍵:⍺ ⍺⍺ ⍵ ⍝ (⍺ and) ⍵ depth 0: operand fn application
⍺ ∇¨⍵ ⍝ (⍺ or) ⍵ deeper: recursive traversal.
}
Try it online!
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