[fpc-pascal] "is"

Thomas Schatzl tom_at_work at gmx.at
Tue Apr 5 19:17:06 CEST 2005


Hello,

   I think I have to make some things more clear why I am in favor of 
that "foreach":

Thomas Schatzl schrieb:
>>> Features being developed now are:
>>> MI interfaces 90% (MI=multiple inheritance)
>>> Inclasses 15% (embedded classes)
>>> foreach 0% (well, we know you hate it)
>>
>> It's a useless statement if used for arrays, enumerations etc. It 
>> blows up the language for no gain. 

You are right, for arrays, enumerations etc. there is little to no gain. 
But I see the application of foreach on these types as added bonus, not 
the main thing.

As far as I understand the proposal the main point for this construct is 
the use in iterable container classes (implementing a certain 
interface). And there it can show it's advantages (or what I think that 
are advantages):

Instead of a very longish (syntax made up just now):

var
   x : IIterable;
   someCollection : TSomeCollection;
   elem : TSomeElement;

[...]
x := (someCollection as IIterable).initIterator();
while (x.hasNextElement()) do begin
	elem := (x.nextElement() as TSomeElement).next();

	<< do something with elem >>
end;
x.doneIterator();
[...]

you could write:

x : TSomeElement;
someCollection : TSomeCollection;

[...]
foreach elem in someCollection do begin
	<< do something with elem >>
end;
[...]

which is imo far easier to read. (Please don't mind the word "foreach", 
I think it's only because it's already used in other languages for that 
purposes).

The former is also less error prone in regard to using the iterator for 
the appropriate element (think of nested foreach's). It is typesafe too.
It makes it easier to quickly change the actual type of (OO-)container 
if needed.

And if basic Pascal types (arrays, sets, etc.) were allowed to be used 
in the same construct, then the programmer won't have to worry about 
syntax differences in using these basic types and OO-collections too.

E.g.

elem : Integer;
someArray : array[X...Y] of Integer;

[...]
foreach elem in someArray do begin
	<< do something with elem, e.g. inc(elem); >>
end;
[...]

or

elem : TSomeEnumeration;
someSet : set of TSomeEnumeration;

[...]
foreach elem in someSet do begin
	<< do something with elem >>
end;
[...]

In case of sets this may not only be an abbreviation for the for-loop, 
but also element testing:

for elem := low(someSet) to high(someSet) do begin
	if (elem in someSet) then begin
		<< dosomething >>
	end;
end;

Probably this also gives some additional opportunities for code 
optimizations.

But in the end you're right, it's only an abbreviation for already 
existing functionality; I'd consider it useful though.

Regards,
   Thomas




More information about the fpc-pascal mailing list