Define Common Function in APL

How can one define ubiquitous function in the APL?

What i do is

function{ (⊃⍣(⍬≡⍴⍵)){the function that apply to scalar}¨⍵ } 

I think there must be a better way to do this so that I don't see it.

+6
source share
2 answers

Most primitive functions in APL are already widespread. So, if you don’t come up with, your custom functions will already be distributed. For instance,

 f←{÷1+*-⍵} ⍝ sigmoid, f(x)=1/(1+exp(-x)) 

will work with both arrays and scalars.

If you are making a fantasy and you have a non-pervasive function f , you can turn it into an all-pervasive

 g←{0=⍴⍴⍵:f⍵ ⋄ ∇¨⍵} ⍝ the pervasive version of f 

which can be read as: if the argument is a scalar, apply f to it, otherwise go recursively to each element of the argument.

+3
source

dfns workspace contains the perv , which causes its operand function to be applied universally, with one or two arguments:

 perv←{⍺←⊢ ⍝ Scalar pervasion 1=≡⍺ ⍵ ⍵:⍺ ⍺⍺ ⍵ ⍝ (⍺ and) ⍵ depth 0: operand fn application ⍺ ∇¨⍵ ⍝ (⍺ or) ⍵ deeper: recursive traversal. } 

Try it online!

0
source

Source: https://habr.com/ru/post/917709/


All Articles