foreach with a default range
w0rp via Digitalmars-d
digitalmars-d at puremagic.com
Thu Jun 11 01:18:50 PDT 2015
A thought just came to me. When I'm implementing foreach for a
container, I'm left with the choice of using a range for a
container or opApply. I've found often that I prefer the ranges,
as it's easy for me to write a range that satisfies @nogc @safe
pure nothrow, etc. This is because the ranges don't call
delegates which are less restrictive, which opApply does.
I've been thinking about how you would implement opApply so that
it could allow you to run @system code while the iteration itself
is @safe, but then I had another idea. Could we allow foreach to
look for a method (UFCS include) for producing a default range
for an object, from a function named 'range'?
In short this...
foreach(elem; container) {}
Could be transformed into this.
foreach(elem; container.range()) {}
This is not too different from how iteration works in Python,
Java, etc. The objects are asked for an iterator, and the
iterator is used to iterate through the object. This would allow
you to implement ranges with more qualifiers set on them, without
having to type .range() everywhere.
What do others think?
More information about the Digitalmars-d
mailing list