Transforming a range back to the original type?

Jonathan M Davis jmdavisProg at gmx.com
Fri May 4 15:38:59 PDT 2012


On Friday, May 04, 2012 21:24:05 Jacob Carlborg wrote:
> I have no problem if there's a new collection. I'm saying of the same
> _type_, not the same _collection_. As I've said in other posts in this
> thread, I mostly just want to assign the result of a range operation
> back to the original variable.

Well, if you have a variable to assign to, then you know the type already. You 
don't need to query the range. You just need a way to create an instance of 
that container from the range. If it's an array, then use std.array.array. If 
it's a string, you can use std.conv.to (so that you get a string rather than a 
dstring). If it's standard a container, then std.container.make should do the 
trick. If it's another type, then as long as the type's constructor takes a 
range, you can just use the constructor. In general, it should just be one 
function call.

> Preferably I would like to not have to
> call any extra functions or constructors but that's not how ranges work.

A filter function which returned the same container type as it was passed would 
be doing something pretty similar to creating a range with the elements that 
match the predicate and creating a container from that. It might be more 
efficient depending on exactly how it was done and what the compiler's able to 
optimize, but it would be far less flexible. Ranges serve as building blocks, 
allowing us to chain functions in way that would be _really_ ineffecient with 
containers (using just one function might end up being more efficient, but if 
every such function in a chain is creating a new container, it would get very 
inefficient very quickly). Ranges end up being far more powerful. Yes, you then 
have to worry about putting the range in a container if you really want a 
container, but it should only take one function call, so I would think that 
the flexibility that ranges buy you would be well worth that small annoyance.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list