pure or not pure?

Georg Wrede georg at nospam.org
Wed Apr 9 14:19:10 PDT 2008


Steven Schveighoffer wrote:
> I realize that I don't fully understand all the rules of what D pure 
> functions will be.
> 
> I think all agree on these rules:
> 
> - pure functions can only call pure functions
> - allow access to invariant data
> - allow mutable access to simple stack variables (variables that are all on 
> the stack, no references)
> 
> In Andrei's accu-functional document, instead of the last rule, there is:
> 
> - allow local automatic mutable state

Still not pretending to know too much, I'd say that if the A/W goal is 
"pure functions as far as MP optimizations is needed" only, then:

A function might need to have local state. Take a function that counts 
something in a list. It'd need a local counter -- unless we want to 
force the programmer to write it as a recursive function. (Which I 
wholeheartedly hope not. I'd be happy with D being multiparadigm.)

Such a variable would be the "local automatic mutable state". Local, of 
course. Automatic, as destructed at end of scope. Mutable and state, of 
course. :-)

> I'm not sure what this means :)  But here are some questions about what is 
> pure and what is not pure:
> 
> 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;

return c; // I presume.

> }
> 
> pure char[] g(int x)
> {
>    char[] c = f(x, 5);
> }

f is pure. g is pure itself, and only uses f. And a new c is created 
each time you access the function, so it's free of other references to 
it (that could change it).

For example, function

     pure char[] concatenate(char[] a, char[] b)
     {
         // return new string consisting of a ~ b
     }

The return value is of course a reference to a new string. In a purely 
functional language returning a reference to a heap object might not be 
ok (I'm no pro on that.), but as D otherwise pretends strings to behave 
somewhat value like, I assume this simply has to be ok.

Of course, a and b would have to be immutable.

It's really a shame that A/W don't elaborate on these things. Now we are 
only getting increasingly unsure about stuff, and at the same time the 
combined brain-cell-hours we invest here might simply be a wild goose 
chase. And after all, most of this is just what they eventually 
*decide*. We could use some help and guidelines, or even opinions on 
these things.

And we could even be of help to them, since right now there seem to be a 
lot of very smart, motivated and able people here. Maybe actually more 
than ever before.



More information about the Digitalmars-d mailing list