So, today I implemented indexed assignment in Kap. I have for the longest time avoided doing so, because the semantics of the language is immutable, but the syntax itself looks like it mutates an array. After all, that's what pretty much every other language does when faced with this kind of code.
To illustrate, what do you think the following code will return?
foo ← 10 20 30
bar ← foo
foo[1] ← 50
bar[1] + foo[1] ⍝ In Kap, the last expression is the return value
If you guessed 70, you'd be right.
If you guessed this is because the assignment on the second line makes a copy, you'd be wrong. foo and bar indeed shares a reference to the same object.
What actually happens is the when you assign to a bracket expression, a new array is created with the updated content, and the value of foo is replaced.
In other words, it's equivalent to the following expression (which is what you had to write before):
foo ← {50}⍢(1⊇) foo
I.e. take element at index 1, replace it with 50 and put it back in the original array, finally assigning that result back to foo.
It turns out that in practice, you don't have to replace elements at specific locations very often, so explicit syntax for it wasn't really necessary.
But, as I was typing the new tutorial for the language, I realised that trying to explain structural under (i.e. ⍢) to a beginner is not something I want to do, so I just decided to implement the standard APL notation for this operation.
Now, to answer the obvious question why I was hesitating to do it earlier: The reason is that this is actually a very costly operation. The entire array is copied every time you replace a single element. It also prevents lazy evaluation, which is pretty bad, since that's what allows Kap to be fast.
Finally, a beginner user may use this in a loop to initialise an array, which would be a terribly slow.
I do have some ideas how to make the last case faster though. The idea is to allow an array to be mutable until any of its content is read. We'll see if it becomes necessary to implement this.
#kap #apl #programming