2012-06-10 39 views
6

如何定義APL中的普適函數?定義APL中的普適函數

我做的是

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

我覺得應該有更好的方式來做到這一點,我沒有看到它。

回答

3

APL中的大多數原始函數已經普及。所以,除非你喜歡做東西,否則你的定製功能已經很普遍。例如

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

將在數組和標量上工作。

如果你做花哨的東西,你有一個非普遍的功能f,您可以通過

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

這可以理解爲把它變成一個 普遍的一種:如果參數是一個標量,對其應用f,否則遞歸地進入參數的每個項目。

0

dfns workspace包含導致其操作數功能perv operator被普遍地應用,有一個或兩個參數:

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

Try it online!