The only missing piece in rich loops was building continuation nested loops — here the old C-like loops were obviously winning. In order to move closer to the podium I made few improvements, the first one — I cannot decide if this is an ugly hack or well designed concept.
I introduced iterator providers. Iterator provider is an object which can provide an iterator (yes, a groundbreaking approach). Usually you can think of a sequence as an iterator provider but there is another one obvious candidate — an iterator itself. It just returns copy of
this. Such addition allows loops to work with iterators directly:
let iter = some_coll.getIterator(); for elem in iter do ••• end
The second improvement is allowing to iterate over non existing data — in rigid mathematical sense an empty set is a not equal to no set, however so far I don’t see any danger with treating them here the same:
let none ?[Int] = null; for elem in none do ••• end
The third improvement is the smallest, it just supports method chaining. Advancing iterator instead of returning
true/false returns an optional iterator. On a successful iteration — the iterator itself, on a failure —
null. This part will be changed as soon as I implement reference passing as it was done in Smalltalk.
Those three changes combined let you write nested loops without any effort:
let coll = [1,2,3]; top: for x in coll do for y in top.iterator do System.Terminal.stdOut.writeLine(x,",",y); end end
It will write such pairs — (1,1), (1,2), (1,3), (2,2), (2,3), (3,3). Please note there are pairs where
y is equal to
x. When this is undesired start nested loop from the next element in collection — i.e. advance the iterator.
let coll = [1,2,3]; top: for x in coll do for y in top.iterator!next() do System.Terminal.stdOut.writeLine(x,",",y); end end
You should see — (1,2), (1,3), (2,3).
The iterator attribute of the
top control is a copy of an iterator used internally by compiler, so you can alter it any way you want, it won’t harm the outer or inner loop.
Except for optimizing the internal wiring of rich loops I am done here, the plan is 100% completed.