How to correctly handle immutable ranges

Peter Alexander peter.alexander.au at gmail.com
Mon Dec 31 09:11:00 PST 2012


On Monday, 31 December 2012 at 16:29:27 UTC, monarch_dodra wrote:
> But back to the original problem, I just think one shouldn't be 
> able to call a const object a range. A "Range" is mutable by 
> nature. Any attempt to pass one to an algorithm should fail 
> (IMO).

This will break a lot of existing code.

This currently works:

immutable int[] a = [1, 2, 3];
auto b = array(a);

std.array.array is one of the few functions that uses 
std.traits.isIterable, so it works for immutable slices.


> We just have a really special case regarding const slices. Even 
> then, the only reason you can "iterate them" is because the 
> compiler is implicitly copying a mutable slice behind the 
> scenes. The const slice itself, technically, really isn't 
> iterable (AFAIK)...

It could also iterate the indices:

immutable int[] a = [1, 2, 3];
foreach (i; 0..a.length)
     foo(a[i]);

Nothing illegal about that.

The specific issue I'm looking at is the joining of an immutable 
array of arrays. It should be allowed, because they can be 
iterated. In fact, if you just remove the template constraints 
from std.array.join then it works.


More information about the Digitalmars-d mailing list