Memory allocation purity

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Thu May 15 10:36:47 PDT 2014


On Thu, 15 May 2014 12:01:35 -0400, Manu via Digitalmars-d  
<digitalmars-d at puremagic.com> wrote:

> On 15 May 2014 23:47, Steven Schveighoffer via Digitalmars-d

>> Because if it were strong-pure, the compiler could optimize two  
>> sequential
>> calls as returning the same exact thing. Imagine if a constructor to a
>> mutable object always returned the same object because the constructor's
>> parameters were immutable. It would be useless.
>
> I don't follow. Forget that it's a pointer... it's just a number.

But that doesn't make sense. What you are returning is not the pointer  
value, but the pointed-at object. When you return an allocated object, you  
aren't returning the pointer, just a way to get to the object.

> A
> strong pure function simply doesn't modify it's inputs (which we can
> guarantee with const/immutable args), and returns the same output.
> It shouldn't matter if the output is mutable or not, it just has to be
> the same. Whether it's the number 10, or a pointer.

define "the same"?

char[] foo(int x) pure {return to!(char[])(x);}

would you argue that foo(5) always returns "5"? Or would you argue that it  
returns {length:1, ptr:0xee532000}?

A memoization would mean it's always returning the same exact object, not  
the same value.

> I guess it logically follows that the output must be const or
> immutable, because it can only possibly be returning a pointer to, or
> to a member of, one of it's args... and 'turtles all the way down'.

You are thinking of uniqueness of the result. That does not require strong  
purity.

> But that leads me back to where I started... how can it possibly be
> that an allocator of any sort can be pure? If you can allocate a new
> pointer, you can return it as a const or immutable pointer if you
> like, and then the function looks awfully like a strong pure function
> even though it returns a new pointer every time. That's not pure at
> all.

Strong pure is not required for implicit casting, uniqueness is. You can  
establish uniqueness based on comparing the return types to the parameters.

But a "strong pure" (and like Don says, this is really a bad description)  
as I understand it means pure in the functional purity sense -- all  
immutable parameters, all immutable returns, no global access. These can  
be optimized similarly to all functional languages (memoization of  
results, reordering or factoring of calls, dispatching calls to multiple  
threads, etc.).

-Steve


More information about the Digitalmars-d mailing list