Purity (D2 standard libraries / object.d)

dsimcha dsimcha at yahoo.com
Sat Jan 10 14:29:44 PST 2009


== Quote from Walter Bright (newshound1 at digitalmars.com)'s article
> Andrei Alexandrescu wrote:
> > Walter Bright wrote:
> >> Michel Fortin wrote:
> >>> Hum, could the compiler be trusted to add the memoization code to
> >>> pure functions so they can stay pure?
> >>
> >> If the compiler does general memoization on pure functions, all it has
> >> to do is use the bits of the arguments passed on the stack to the
> >> function as an index into an associative array of the return values.
> >
> > Not the bits, the full objects if they have indirection. (Pure functions
> > should accept const parameters!)
> You're right, the "just the bits on the stack" is if the arguments are
> immutable. Const arguments would have to include whatever was indirectly
> referenced, which I argue is impractical for the runtime to handle
> automatically.

Even if the bits are immutable, I can't see how this could work.  What if
something is GC'd and then that memory location gets overwritten?  For example:

import std.contracts, std.stdio;

enum N = 100;

void main() {
    foo();
    bar();
}

uint pureFun(invariant uint[] data) pure {
    // Do stuff.
    return someUint;
}

void foo() {
    uint[] myArray = new uint[N];
    // Fill in myArray;
    invariant uint[] myInvariantArray = assumeUnique(myArray);
    writeln(pureFun(myInvariantArray));
}

void bar() {
    // Same as foo().
}

In this case, foo.myInvariantArray goes out of scope when foo() returns.  When
bar() allocates an array, it's entirely possible that the GC will give bar.myArray
the same memory address as foo.myArray had.  In this case, if you're only using
stack bits to handle memoization, you're screwed.



More information about the Digitalmars-d mailing list