Transforming a range back to the original type?

Jacob Carlborg doob at me.com
Thu May 3 23:32:09 PDT 2012


On 2012-05-04 01:11, Stewart Gordon wrote:

> To sum it up, it can't be done in the general case. The range API
> doesn't know or care about the underlying data structure. That's half
> the point of it. The underlying data structure might not even exist. An
> example is a range used as a file stream, a random number generator or
> to lazily generate a mathematical sequence.

Yeah, I know, I know. It's all good in theory but I never found a use 
for it in practice and in most cases it's just annoying.

> Moreover, what would you want such a function to return if the range is:
> - a file stream with a cache
> - an array wrapper to loop infinitely through it?
> - a concatenation of ranges that may be of different types?

I was mostly thinking when the range originated from a collection. Where 
it's actually possible to transfer the range back to the original 
collection type.

> Moreover, even if there were some "range with an underlying container"
> classification, it would be an extra burden on the writer of the range
> wrapper to implement this.

No, I was thinking that the developer of the collection would provide 
that. I mean, it's already possible to transform a range to an array, 
I'm sure it's possible to transform it to a list of some kind as well. 
Then we could have this for example:

collA.range.toArray();
collB.range.toList();

What I was asking for was if there is, or could be, a generic interface 
for this. Something like:

collA.range.toCollection();
collA.range.toCollection();

If "collA" is an array "toCollection" would transform the range to an 
array, just as std.array.array does. If "collB" is a list the range 
would be transformed back in to a list.

> If you want to generate a range that views a container in a certain way,
> and then construct a container of the original type (or indeed any type)
> from that range, then create the container and then use a foreach loop
> on the range (or a .save of it, if you want to keep the range
> afterwards) to put the data into the container.
>
> Stewart.


-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list