5

What is the syntax for a vector (array) of functions in APL?

I have tried the following but these are interpreted as a 3-train and a 2-train, respectively:

{1},{2}
{1} {2}

PS. I am looking to do this with more complex (and possibly named) functions by the way, the {1} above is just so the example is short.

Adám
  • 6,573
  • 20
  • 37
P Varga
  • 19,174
  • 12
  • 70
  • 108

2 Answers2

7

Arrays of functions can be obtained using ⎕OR (Object Representation) and the fact that such objects implicitly become reconstituted into functions when used as operands. (You can also do it explicitly using ⎕FX.) It is easiest to define some helper operators first:

      _Arrayify←{f←⍺⍺ ⋄ ⎕OR'f'}
      _Apply←{2=⎕NC'⍺':⍺ ⍺⍺ ⍵ ⋄ ⍺⍺ ⍵}

Now, let's define some sample functions:

      A←{2×⍵}
      B←{⍵÷2}
      C←{-⍵}

We create a 3-element vector of functions, and check that it is indeed a "normal" array:

      fnArray←(A _Arrayify⍬)(B _Arrayify⍬)(C _Arrayify⍬)
      ⍴fnArray
3

Let's extract the second function and apply it:

      (2⊃fnArray)_Apply 10
5

We can also create an application function, so we can use operators on it:

      Apply←{⍺ _Apply ⍵}
      fnArray Apply¨10
20 5 ¯10
Adám
  • 6,573
  • 20
  • 37
5

Dyalog APL does not officially support function arrays, you can awkwardly emulate them by creating an array of namespaces with identically named functions.

      (a←⎕NS⍬).f←2∘×
      (b←⎕NS⍬).f←÷∘2
      (c←⎕NS⍬).f←-
      f←(a b c).f
      f 4
8 2 ¯4

Maria Wells suggested an operator to produce an array of functions

  • 1
    Problem is that you can't index into the array of functions to select which one to apply, so it is really no different than `f←(⊂2∘×),(⊂÷∘2),(⊂-)` – Adám Nov 29 '21 at 08:16
  • But if you leave the functions in the namespaces, you have an array ( albeit of namespaces and not actual functions) and you can index into it and manipulate like any other array. This is what happens as a matter of course when calling a method on an array of objects, a very powerful feature of Dyalog. – Paul Mansour Nov 29 '21 at 13:41
  • 2
    Encapsulating a function in a namespace and taking the object representation are both kluges to implement function arrays and its not clear to me the latter is more elegant or powerful than the former. – Paul Mansour Nov 29 '21 at 13:52
  • Is one more portable than the other (`⎕or` and `⎕nc` vs `⎕ns`)? I have read somewhere that namespaces were ISO standard APL but can't find a mention of them in the actual standard. – P Varga Dec 06 '21 at 20:25