How to correctly handle immutable ranges

Jonathan M Davis jmdavisProg at gmx.com
Wed Jan 2 14:14:27 PST 2013


On Monday, December 31, 2012 15:58:02 Peter Alexander wrote:
> On Monday, 31 December 2012 at 14:24:53 UTC, monarch_dodra wrote:
> > The same can't be said about ranges: a "immutable(Range!T)"
> > might not safely copyable as a "Range!(immutable(T))"
> 
> Hmm, are you sure? Can you give an example? Surely if Range is a
> struct and everything is copied then it can all change from
> mutable to immutable (using a postblit where necessary).

immutable(Range!T) and Range!(immutable(T)) are completely different types. 
They may come from the same template, but they're different instantiations of 
that template, and there's no guarantee that they have any relation to each 
other. In a pathalogical case, you could have something like

struct S(T)
{
 static if(is(T == immutable))
 {
 double d;
 int foo() { return 7; }
 }
 else
 {
 int i;
 string s = "hello";
 bool maybe;

 double bar(int i) { return i * 1.1; }
 void baz() { writeln(i); }
 }
}

So, the compiler can't assume that immutable(Range!T) and Range!(immutable(T)) 
have any real relation with one another.

Ideally, that problem could be solved by declaring an overload of opSlice 
which returned a tail-const version of the range, but that poses difficulties 
due to circular dependencies when one template instantiation refers to 
another. The circular dependency problem might be solvable with a static if 
though. I'd have to play around with it more to figure out the details. It's a 
bit of a thorny problem, and I've had issues with it in the past.

But if a tail-const opSlice can be done, then if you need a tail-const version 
of a range, you can just slice the range to get it, which is what happens with 
arrays. It's just that with them, it's done automatically. If the opSlice stuff 
got sorted out well enough though, and it was generally accepted how to define 
a tail-const opSlice, then it might be reasonable for the compiler to use that 
where appropriate, giving ranges the same tail-const abilities as arrays.

- Jonathan M Davis


More information about the Digitalmars-d mailing list