Skip to content

An Ambivalent Operator

Vector 5:4, page 96

programming techniques language design

Transcribed from the printed issue; not yet reviewed. Read it in the PDF of the issue, page 96

Here is an APL2 operator of use in ambivalent functions. One use of ambivalent functions is to elide the left argument, and thereby force it to take a default value. The methods normally used to achieve this are, for example:

[..]  →(2=⎕NC 'LEFT')/dyadic
[..]   LEFT←default
[..] dyadic:

or perhaps …

[..] ⍎(0=⎕NC 'LEFT')/'LEFT←default'

Neither of these solutions is ideal - the first embodies too much apparent complexity to acheive such a simple effect - code in which errors can be made. The second uses execute, which is bad for all the normal reasons!

The defined operator listed below allows the effect of the second example to be acheived without using execute:

     ∇R←DEFAULT(FUNC ∆MONADIC CLASS) RIGHT
[1] ⍝ OP: default func right if class is not 2
[2]  R←0                                ⍝ ASSUME DYADIC CALL
[3]  →(2=CLASS)/0                       ⍝ EXIT IF CALL WAS DYADIC
[4] R←1(DEFAULT FUNC RIGHT)             ⍝ EXEC WITH DFLT ARGUMENT
     ∇

The operator is used as follows:

     ∇AVE←SIZE AVERAGE NUMS;RUN
[1] ⍝ FN: MOVING OR NORMAL AVERAGE DEPENDING ON ⎕NC 'SIZE'
[2]  →(↑(RUN AVE)←(⍴NUMS)(AVERAGE ∆MONADIC ⎕NC 'SIZE')NUMS)/0
[3]  AVE←(SIZE+/NUMS)÷SIZE
     ∇

I trust the above is of interest, and look forward to any feedback.

Yours sincerely

D.B. Piper