[fpc-pascal] For..in enumerator for generic records?
Sven Barth
pascaldragon at googlemail.com
Thu Dec 1 22:58:46 CET 2016
On 30.11.2016 12:36, Ryan Joseph wrote:
>
>
>> On Nov 30, 2016, at 6:24 PM, Graeme Geldenhuys <mailinglists at geldenhuys.co.uk> wrote:
>>
>> What would you iterate/enumerate in that? I can understand iterating an
>> "array of TMyRec", but not TMyRec itself.
>
> I have a dynamic array inside a record. I’m using a record instead of a class because I want it to be stored on the stack. It’s trivial to just enumerate the array inside the record but I wanted to try the more elegant solution of making an enumerator for the record.
I've attached an example that shows how this *can* be done (it's not the
only way to do this however).
Regards,
Sven
-------------- next part --------------
program trecenum;
{$mode objfpc}
type
TLongIntArray = array of LongInt;
TRec = record
arr: TLongIntArray;
end;
TRecEnumerator = object
private
fArr: TLongIntArray;
fIndex: Integer;
function GetCurrent: LongInt;
public
constructor Create(aArr: TLongIntArray);
function MoveNext: Boolean;
property Current: LongInt read GetCurrent;
end;
constructor TRecEnumerator.Create(aArr: TLongIntArray);
begin
fArr := aArr;
fIndex := -1;
end;
function TRecEnumerator.GetCurrent: LongInt;
begin
Result := fArr[fIndex];
end;
function TRecEnumerator.MoveNext: Boolean;
begin
Inc(fIndex);
Result := fIndex < Length(fArr);
end;
operator enumerator(r: TRec): TRecEnumerator;
begin
Result.Create(r.arr);
end;
var
r: TRec;
i: LongInt;
begin
r.arr := TLongIntArray.Create(42, 53, 96, 29);
for i in r do
Writeln(i);
end.
More information about the fpc-pascal
mailing list