[fpc-devel] New feature discussion: for-in loop

Michael Van Canneyt michael at freepascal.org
Tue Oct 20 11:09:12 CEST 2009



On Tue, 20 Oct 2009, Paul Ishenin wrote:

> Michael Van Canneyt wrote:
>
>>> And what is so special in the class type?
>> 
>> First:
>> For a for loop, you are guaranteed that the loop logic behaves correctly.
>> A loop is equivalent to the following:
>> 
>> I:=StartValue;
>> E:=EndValue;
>> While I<=EndValue do
>>   begin
>>   // loop stuff
>>   Inc(I);
>>   end;
>> 
>> And you cannot change I manually during the loop.
>> 
>> You don't know this with an iterator since you depend on the implementation
>> of the iterator. The loop could loop forever then...
>
> Yes. For-in loop is not a for-to loop. While and Repeat loops can also loop 
> forever. You can't protect a developer if his hands grow from the wrong 
> place.
>
>> Secondly:
>> You promote a certain class/interface to a language feature. The compiler 
>> then depends on the presence of a certain class with some 'known' methods 
>> in the RTL.
>
> Yes, I see this very bad too. That's why this discussion is started. But what 
> can be suggested instead?

IMHO nothing. Maybe marc's proposal.

> Maybe new type?
>
> TSomeIterator = iterator(<iterated type>)
> ...
> end;
>
> or we can use some basic class:
>
> TIterator = class
> public
>  function MoveNext: Boolean;
>  property Current: <what type to return?>
> end;

This is the same as what Borland does: you promote a certain class to a language
feature...

> I don't like non-constructive criticism. If you don't like something please 
> be ready to suggest something instead. And in this case something what can be 
> used to implement for-in loop for classes and implements this delphi 
> compatible (so 'for S in MyStringList do' will work).


I did suggest something instead: implement iterators in the classes unit, as 
Graeme suggests.

Yes, I know this is not Delphi compatible. But I'm OK with that.
I think the importance and gain of the for in loop is far too small to spend
time on it, since there are plenty of alternatives possible today.

Of course, if you want to be 100% delphi compatible, then there is simply 
no way we can ever agree on this particular feature, no matter how
constructive I am or you are.

So then, in the end, someone will have to back down and put aside his wishes :-)

But I really don't see the advantage of being able to type

   For F in Someclass.Iterator do
     F.Something

over

   While SomeClass.HaveValue do
     SomeClasss.NextValue.Something;

It's not clearer, at most it saves you a couple of keystrokes.

Raping a clean language for this is simply not correct. It's not because
Borland - in its desire to make money - implemented every idiots' request,
that we should do the same.

Michael.



More information about the fpc-devel mailing list