GC.malloc is pure - wat
Steven Schveighoffer via Digitalmars-d
digitalmars-d at puremagic.com
Fri Apr 24 08:21:43 PDT 2015
On 4/24/15 11:05 AM, anonymous wrote:
> GC.malloc is marked pure. But it isn't, is it?
>
> This should hold for a pure function:
> assert(f(x) == f(x));
All functional make this concession -- allocating is pure as long as you
don't look at the address. You a language that doesn't allow allocating
memory is quite useless.
> This fails with GC.malloc, of course.
>
> Or consider this:
> auto v = f(x);
> auto w = f(x);
> When f is pure, a compiler should be free to reuse the value of v for w.
> That's no good with GC.malloc, obviously.
This is OK as long as f is *strong* pure. D pure is not the same as the
traditional definition.
And GC.malloc is not strong pure, as it returns mutable data.
However, this should be strong pure:
immutable(int)* foo(int x) pure
{
return new int(x);
}
Any call to foo could be cached and avoided. This is allowed by the
compiler (but I'm not sure if the optimization is implemented).
But *inside* foo, you are allowed to call "weak" pure functions. Those
calls cannot be cached.
Note that calls to foo *could* be cached, but are not *required* to be
cached, as you hinted in your question.
-Steve
More information about the Digitalmars-d
mailing list