Conditional Idioms
Vector 18:2, page 104
Transcribed from the printed issue; not yet reviewed. Read it in the PDF of the issue, page 104
Most of you will have seen something similar to:
where (DOIF) is something like
Later you might have encountered
and if you had your wits about you, you would have laughed knowingly and absolutely KNOWN that, had you written the original code it would have said
Well done! here are a few more examples. I don’t claim that any of these are original insights. I’ve had the best part of the list knocking about for years, seldom refer to it and then more often to add one than remember one I’ve used before.
Just thought someone else might be mildly interested.
These are not functions, they are conditional expressions that either perform an operation or not or they perform one operation or another. Wherein:
(
c) is a simple logical scalar which decides the issue.
(a) & (w) are the two or (a) is the single primary input(s) to the expression.
(z) is a temporary variable.
(F) is a dyadic function.
If (c) is zero and there is no alternative (else) in the description then the first of (a) & (w) mentioned is returned unaltered other than by scalar extension.
ISO standard APL is used throughout.
| 1. | Multiply (a) by (w) |
a×w*c |
| 2. | Reciprocate (w) |
w*¯1*c |
| 3. | Divide (a) by (w) |
a×w*-c |
| 4. | Divide (a) by (w) else multiply |
a×w*¯1*c |
| 5. | Negate (minus) (w) |
wׯ1*c |
| 6. | Sum of (a) and (w) else difference |
a-wׯ1*c |
| 7. | Reverse (w) (rank 1) |
w[⍒c×⍳⍴w] |
| 8. | Reverse (w) (first dim) |
(⍴w)⍴⊖(c↓1,⍴w)⍴w |
| 9. | F-Reduction (w) (first dim) |
F⌿(c↓1,⍴w)⍴w |
| 10. | F-Reduction (w) (last dim) |
F/((⍴w),c↓1)⍴w |
| 11. | Transpose (w) |
(⍒c×⍳⍴⍴w)⍉w |
| 12. | Transpose (w) by (a) (non-slicing) |
(⍋c×a)⍉w |
| 13. | Ceiling (w) else floor |
z×⌊w×z←¯1*c |
| 14. | Maximise (a) with (w) else minimise |
z×(a×z)⌊w×z←¯1*c |
| 15. | And (a) with (w) else or |
c=(a=c)∧w=c |
| 16. | Sum (+⌿w) else last (1↓⍴w)⍴⊖w |
c⊥w |
| 17. | Ravel (w) |
(×⌿(c↓1,⍴⍴w)⍴⍴w)⍴w |
Having put the list in this form under that intro there didn’t seem to be as many as I’d thought so I tried to search out a few more, added five and came to the conclusion that all but one of the new ones were just variations on a theme. I think all those that remain deserve to be there in that each either has something which is very specific that couldn’t be used elsewhere or is a typical example of a more generally applicable technique.
I’d be very pleased to see if anyone else has any further examples showing any new insights or techniques.