I just got it! (invariant/const)

Steven Schveighoffer schveiguy at yahoo.com
Wed Apr 9 11:33:41 PDT 2008


"Janice Caron" wrote
> On 09/04/2008, Steven Schveighoffer wrote:
>>  It's the
>>  same reason you will be able to pass strings to a pure function.  A 
>> string
>>  is mutable, but the data it points to is not.
>
> No, that's because of Andrei's
>
>    RULE 3:
>    T implicitly converts to and from invariant(T) iff T refers to no
> mutable memory

Hm.. I glossed over that rule :)  But by the same rule, my example class C 
should be implicitly castable to invariant, but in the case where C has 
invariant and mutable parts, then this is not the case...  I was thinking a 
different rule (for pure functions) would be more appropriate:

Disallow access to non-invariant data

Should be changed to:

Only allow access to invariant and local data.

>
> (from accu-functional.pdf)
> Therefore, string implicitly casts to invariant(string).
>
> Perhaps then, we may say that the parameters of a pure function should
> be invariant, or implicitly castable to invariant?

Hopefully not the former, as working with invariant data when one doesn't 
have to makes things really cumbersome.  If it's implicitly castable to 
invariant, then it's implicitly castable from invariant, I'd rather have the 
mutable version :)

>
> Of course, it's /possible/ to write a pure function that takes mutable
> pointers, e.g.
>
>    int f(char[] s) pure?
>    {
>        return 42;
>    }
>
> but do we care? Wouldn't it just be easier to make that illegal and
> insist that the programmer rewrite the function more sensibly?

I'm thinking more of the case where an argument is a mutable stack pointer 
(meaning it is a pointer, but only exists in the pure function's stack) to a 
chunk of data that has both mutable and invariant pieces.  i.e.:

class C
{
    int *m;
    invariant(int *) i;
}

pure int getI(C c)
{
    return *i;
}

There may be a reason to use i, but not m in a pure function.  Why should 
pure restrict this?  It's technically correct and statically verifiable.

-Steve 





More information about the Digitalmars-d mailing list