Transforming a range back to the original type?
Jonathan M Davis
jmdavisProg at gmx.com
Fri May 4 00:01:32 PDT 2012
On Friday, May 04, 2012 08:32:09 Jacob Carlborg wrote:
> 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.
Something like that could probably only be done if every range in the
potentially large chain of wrapped ranges provided a means of getting at what
type the previous one in the chain was, and very few ranges - if any - do
that.
However, I'm not quite sure what toCollection would buy you. Why does it
really matter what type of container the range comes from originally given
that you have to create a new container to put the elements of the range into
such a container? And if you're putting the elements of a range in a new
container, you can pick whatever container type you'd like, and since it has
no real connection to the original container, I don't see why it would matter
whether it was the same type of container. All you really need is the
equivalent of std.array.array for whatever container you want to construct,
and the container's constructor should provide that.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list