[fpc-devel] for-in-index loop

Alexander Klenin klenin at gmail.com
Fri Jan 25 18:17:54 CET 2013


On Sat, Jan 26, 2013 at 3:30 AM, Florian Klämpfl <florian at freepascal.org> wrote:
>> "for-in-index" extension was actually planned by me as a prerequisite
>> for fcl-stl work.
>
> Using indicies is against all principles of iterators.
I am not sure what princilpes you are talking about,
but accessing the key of the current element is required quite often
and provided by iterator implementations in many programming languages
(except for Java, as discussed above).
I have already provided examples.

> The idea of iterators is actually to replace and get rid of indicies
> because they e.g. fail as soon as the iterated container is changed
> during iteration. Depending on the iterated container, iterators might
> be still valid even if the container changes.
This is true, but was no relevance to the syntax extension discussed here.
Note that there is no limitation on the type of index,
and of course it is not required that the indices are monotonously
increasing integers.

>> var
>>   a: array [1..5] of Integer = (1, 2, 9, 4, 5);
>>
>> In my proposal, he should write:
>> var
>>   v, i: Integer;
>> begin
>>   for v in a index i do
>>     Writeln(i, ' ', v);
>> end.
>
> In this case I just write
>
> for i:=low(a) to high(a) do
>   writeln(i,' ',a[i]);
Consider these arguments:
1) Even for simple arrays, depending on array element type,
  and optimizer implementation, for-in can be more efficient since it
can avoid multiplication for element access.
2) If "a" is a function of another complex expression returning an
array, then "for-in" may be much more efficient and compact
3) If "a" is an associative array (so i is a String), then the
"traditional" form of loop is not even possible.
4) If there is no uniform method for iterating over containers, then
each container will define its own method,
  with the end result that the language will be *more* complex for the
user, who will have to remember all these methods.

--
Alexander S. Klenin



More information about the fpc-devel mailing list