foreach() behavior on ranges

Alexandru Ermicioi alexandru.ermicioi at gmail.com
Tue Aug 24 18:52:19 UTC 2021


On Tuesday, 24 August 2021 at 08:36:18 UTC, frame wrote:
> How do you handle that issue? Are your ranges designed to have 
> this bug or do you implement opApply() always?

This is expected behavior imho. I think what you need is a 
forward range, not input range. By the contract of input range, 
it is a consumable object, hence once used in a foreach it can't 
be used anymore. It is similar to an iterator or a stream object 
in java.

Forward range exposes also capability to create save points, 
which is actually used by foreach to do, what it is done in java 
by iterable interface for example.

Then there is bidirectional and random access ranges that offer 
even more capabilities.

Per knowledge I have opApply is from pre range era, and is kinda 
left as an option to provide easy foreach integration. In this 
case you can think of objects having opApply as forward ranges, 
though just for foreach constructs only.

Regards,
Alexandru.


More information about the Digitalmars-d-learn mailing list