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

Sergei Gorelkin sergei_gorelkin at mail.ru
Tue Oct 20 17:16:28 CEST 2009


Paul Ishenin пишет:
> Marc Weustink wrote:
>> I can see a use for using iterators in a for loop, however they should 
>> be declared with some keyword.
>>
>> Something like
>>
>> type
>>   TListIterator = iterator(TList, init_func, next_func, check_func)
>>     function init_func: Boolean;
>>     function next_func: <element type>
>>     function check_func: Boolean;
>>   end;
>>
>> begin
>>   for element in list using TListIterator do...
>>
>> IMO this is more pascal than using some interface or predefined 
>> function names.
> Good idea. What is iterator internally? Is this an object with the 
> special header?
> 
> Is it internall the same as:
> TListIterator = object
>  function init_func(AList: TList): Boolean;
>  function next_func: Pointer;
>  function check_func: Boolean;
> end;
> 
Don't comlicate it more than necessary:

1) An object (or record with methods, provided you implement it first 
:-) is preferable over class, since using it can help avoiding 
construction/destruction, memory allocations, and implicit try..finally.
2) Using objects/records also enables you to use operators to encode the 
iterator. This isn't possible for classes.
3) next_func and check_func above can be coalesced to a single
   function next(out obj: TItem): Boolean;
4) The syntax 'for element in list using TListIterator' is kind of 
redundant. I'd suggest:
   for element in list.GetForwardIterator do ..., or even
   for element in list.GetSubItems(arguments) do ...

Regards,
Sergei



More information about the fpc-devel mailing list