Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a pervasive function in APL

Tags:

apl

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.

like image 762
Chao Xu Avatar asked Jun 10 '12 07:06

Chao Xu


People also ask

What is a primitive function in APL?

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

What are the functions and operators in APL?

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.

What is APL?

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.

What is the precedence of a function in APL?

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.


Video Answer


2 Answers

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.

like image 82
ngn Avatar answered Oct 07 '22 02:10

ngn


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!

like image 40
Adám Avatar answered Oct 07 '22 02:10

Adám