opSlice() magic for foreach now works?

spir denis.spir at gmail.com
Wed Mar 30 07:06:26 PDT 2011


Hello,

I was trying std.container's SList and noticed foreach iteration works for it, 
while it defines neither opApply, nore a (complete) input range interface. But 
it does implement a parameter-less opSlice, which maps to "l2 = l1[];". More 
precisely, SList (as other container types) defines a 'Range' struct type which 
is the return type of opSlice().
TDPL states this method should automagically deal as standard traversal for 
foreach (when no opApply or range interface is defined on the collection to be 
traverseditself, I guess). But the magic did not work up to very recently.

Does this mean this feature is now implemented? (Note: I tried it for a custom 
collection type, and it worked fine.) If yes, I guess it deserves an announce 
on the mailing list, as many of thus were waiting for it (hurray!). And a clear 
explanation at three places:
* in the 'foreach' section of the language reference manual
* in std.range's doc
* in std.container's doc

Note that this feature fills a long-standing gap in the unification of 
collections & ranges: there have been until now 2 contradictory requirements 
upon ranges:

1. A collection should be iterable (indeed).
2. A collection should /not/ implement a range interface (be its own range), 
instead it should provide
    one or more methods returning traversal ranges. This is supposed to be more 
flexible.

The only solutions were either to provide opApply in addition to 2., or to 
force the user explicitely calling the methods, as in:
    foreach (element; myCollection.elements()) {...}
Both are unsatisfying for different reasons. Thank to the "total slice" magic, 
opSlice() now implicitely deals as /standard/ traversal for a collection. Like 
if it were a kind of 'opTraversal'. This is exactly equivalent, I guess, to 
Python's __iter__. opSlice() is thus, if I understand correctly, supposed to 
return a 'traversable' thingy, typically an input range.

I have not yet tried to provide a collection implementing opSlice() to funcs 
expecting a range. Hope this works as expected, or it will do so soon.

[See also thread about "multiple-item traversal ranges"]
Denis
-- 
_________________
vita es estrany
spir.wikidot.com



More information about the Digitalmars-d mailing list