Consider the following simple piece of code:
a ← ⍳5
el1 ← a+2
el2 ← +/el1
el1 el2
┌─────────┬──┐
│3 4 5 6 7│25│
└─────────┴──┘
I am simply adding 2 to a
and summing the array up, then returning array containing results of both operations. As I understand it, APL interpreter would in this case have to go 2 times over the array.
Is this the correct way to do this in APL or does the language have some kind of accumulators, similar to what functional programming languages provide (which would let me go only 1 time over the array)?
As such, there isn't any specific accumulation functionality in APL. I imagine most APLers view +/A and X+2 as primitive operations where the interpreter must iterate repeatedly over arrays a fact of life.
However, assuming your APL system supports user-defined operators, you can easily write a kind of accumulation operator. That is, if the goal is to make a single pass over an array. Something like
Where the code would be something like
This is a very simplistic solution which would work correctly with + and x and other functions where fn1's identity is 1. Performance would not be as good as that of the example. Note also the solution starts to resemble reduction.
Back to normal APL, if you don't need the intermediate result,
+/ a + 2
would be fine. As a practical matter, code fragments of+/ a x 2
or+/ a * 2
are very common. Also for vector a, inner product could also work,a +.x 2
anda +.* 2
are also not uncommon.Last and certainly least, a future optimising APL interpreter or compiler could employ loop fusion to do this operation internally with only one loop instead of two.