[fpc-pascal] for .. in loop implementation

Vincent Snijders vsnijders at vodafonevast.nl
Wed Jan 7 11:10:32 CET 2009


leledumbo schreef:
> OK, I've read  http://wiki.freepascal.org/Modernised_Pascal this  (and the
> FAQ as well). I disagree with any statement saying that for .. in loop is
> only a type-saver. It's a good language extension and should be included
> (since Delphi already have this, it will also be a good idea). Consider the
> following example:
> 
> type
>   TDays: (Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday);
>   TDaySet: set of TDays;
> 
> var
>   d: TDaySet;
> begin
>   for d in [Monday,Wednesday,Friday] do ;
>   // versus
>   for d:=Low(TDaySet) to High(TDaySet) do
>     if d in [Monday,Wednesday,Friday] then ;
> end;
> 
> The latter one has iteration overheads, while the former can be optimized to
> loop as many as needed. I'm not saying I'm the best Pascal programmer, but
> in case there's a (better) solution to this (rather than extending the
> language) please tell me.
> 

You could write it like this:

type
   TDays: (Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday);
   TDaySet: set of TDays;

var
   d: TDays; // note the type
   i: 0..2;
const
   SomeDays: array[0..2] of TDays = (Monday,Wednesday,Friday);
begin
   for i:=Low(SomeDays) to High(SomeDays) do
   begin
     d := SubSet[i];
   end;
end;

And it loops as many times as necessary.

Vincent



More information about the fpc-pascal mailing list