Using pure to create immutable

Steven Schveighoffer schveiguy at yahoo.com
Thu Sep 22 13:25:28 PDT 2011


On Thu, 22 Sep 2011 16:15:20 -0400, Jonathan M Davis <jmdavisProg at gmx.com>  
wrote:

> On Thursday, September 22, 2011 16:09:29 Steven Schveighoffer wrote:
>>
>> Technically, something like this could be cast to immutable:
>>
>> T[] foo(const(T)[] arg) pure
>>
>> Since it can be proven that the result is new data.
>>
>> So it doesn't *need* to be strong-pure.
>
> Yes, you can always cast to immutable

I meant implicitly cast, sorry.  I should be able to do this:

T[] foo(const(T)[] arg) pure {...}

immutable x = foo(y);

> but unless the compiler can _prove_
> that the return value can be safely cast to immutable, it won't do it
> implicitly, and the function needs to be strongly pure to do that.

It doesn't.  In fact, the result of a strongly-pure function *cannot* be  
cast away from immutable implicitly:

immutable(int)[] strongpure(immutable(int)[] arg) pure { return arg[0..5];}

immutable(int)[] y = [1,2,3,4,5,6,7,8,9];
int[] x = strongpure(y); // error!

This function is not strong pure:

int[] weakpure(immutable(int)[] arg) pure {...}

because it cannot be optimized away.  Subsequent calls to weakpure do  
*not* return the same value, each one returns a new piece of data.

Yet because we know it returns a new piece of data, the result should be  
implicitly castable to immutable:

immutable(int)[] y = [1,2,3,4,5,6,7,8,9];
immutable(int)[] x = weakpure(y); // should be fine

-Steve


More information about the Digitalmars-d-learn mailing list