Home > Software design >  Use a recursive dop in APL
Use a recursive dop in APL

Time:11-27

In the tryapl.org Primer when you select the Del glyph (∇) it shows an example of a Double-Del (∇∇) where a dop (as I understand it, a user defined operator) can reference itself in a recursive fashion:

Double-Del Syntax:  dop self-reference

    pow←{                ⍝ power operator: apply ⍵⍵ times
        ⍵⍵=0:⍵           ⍝ ⍵⍵ is 0: finished
        ⍺⍺ ∇∇(⍵⍵-1)⍺⍺ ⍵  ⍝ otherwise: recurse
    }

Can someone provide me with some examples of this particular dop in use so I can see how to utilize it? I see that a single is not used in the body of this dop, only ⍺⍺; does that make this a monadic dop?

I have tried a number of different ways to use this operator in an expression after it's defined and can't seem to get anything but errors or instances where it appears the body/text of the dop is in an array as text, alongside what I was trying to pass to it.

CodePudding user response:

Example usage

      incr←{1 ⍵}      ⍝ define an increment function
      (incr pow 3) 5  ⍝ apply it 3 times to 5
8

Lack of single

The operator has ⍵⍵ which alone makes it a dyadic operator. The lack of a single means that, when given the two required operands, it derives a monadic function.

Troubleshooting

When an operator takes an array (as opposed to a function) operand adjacent to an argument, it is crucial to separate the operand from the argument. This can be done in any of three ways:

  1. Name the derived function and then apply it:
    add3←incr pow 3
    add3 5
  2. Parenthesise the derived function:
    (incr pow 3) 5
  3. Separate the operand from the argument using a function (often, the identity function is used):
    incr pow 3 ⊢ 5

Failing this, the intended operand and argument will strand to a single array, which then becomes the operand, leaving the derived function with no argument that it can apply to:

incr pow (3 5)

The result is therefore the derived function; the text source you see reported.

  • Related