pure or not pure?

guslay guslay at gmail.com
Wed Apr 9 15:53:08 PDT 2008


Georg Wrede Wrote:

> guslay wrote:
> > Steven Schveighoffer Wrote:
> > 
> >>1. Can pure functions use mutable heap data?  If so, what are the 
> >>restrictions for this?
> >>
> >>i.e.:
> >>pure char[] f(int x, int y)
> >>{
> >>   char[] c = new char[y];
> >>   c[] = (char)x;
> >>}
> > 
> > Isn't the dynamic allocator a global state?
> 
> IMHO, especially in D, we'll have to make an exception of /new/.
> 
> If we didn't, then a function can't return anything that can't be stored 
> on the stack.
> 
> So, if we pretend that a string is returned via the stack, and that any 
> local strings a pure function needs temporarily, are in its own stack, 
> then we're okay.
> 
> I don't really see any alternative here. Also, I don't see the 
> language/compiler enforcing this as all that hard.


Not that I know what I'm talking about, but my understanding is:

- You should be able to allocate with "scope" a local mutable object (automatic local mutable state).

- You should not return a mutable reference type on the heap.

A a1 = f();
A a2 = f();

Let's suppose f() is pure. Mr. compiler does:

A __a = f();
A a1 = __a;
A a2 =  __a;

But if A is a reference type, you don't know the concrete type of object a1,a2. How can you do the pure stuff, like skipping the second evaluation of f(), if you can't make distinct copy. There is no copy/cloning constructor. You don't want to share the same mutable reference between a1 and a2, otherwise you would have written

A a1 = f();
A a2 = a1;

- However, allocating and returning invariant memory should be fine. If A is invariant (like a string), you should be happy for a1 and a2 to share the same reference.





More information about the Digitalmars-d mailing list