www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Re: Idea: partially pure functions

mort Wrote:

 I'm not an expert on D, but it looks like a pretty nice language.  While
reading about 'pure' recently, however, I found what appeared to be pretty
major usability problems with the idea as it was presented:
 - Pure functions can have local mutable state, but aren't allowed to factor
the logic for manipulating that state out into functions (since such a function
would be non-pure).
 - Pure functions can't be applied to mutable data.  So you potentially need a
mutable non-pure version of each pure function.
 An elegant solution to both of these problems would seem to be the one
proposed in this thread - get rid of the requirement that parameters be
invariant.  The first problem above is solved by pure functions with mutable
parameters, and the second by pure functions with const parameters.
 Special optimizations that require purity and parameter invariance can always
be done by creating a specialized version of each pure function that's invoked
when the arguments are known to be invariant.  Let the compiler handle the
duplication - don't make the programmer copy/paste.

I agree with you completely, and was planning on making an similar post about the subject. Take one of the string functions, for instance, countchars. It has the following signature: size_t countchars(string s, string pattern); This function etiher is or could be pure. However, the function would work just as well when operating on const (char)[] data, which is potentially mutable, or char[] data, which is explicitly mutable. Being able to have a conditionally pure function, one that was pure if its arguments were invariant and not pure if they were not, would allow this function to work for both mutable and immutable data, and gain all the optimization benefits of a pure function if its parameters were indeed invariant. There are of course occasions where functions might need to act differently based on the invariance of its parameters. string.split, for instance, would probably want to copy the data it returns if its parameters were not invariant. However, I think differences like these could easily be handled with D's compile-time reflection abilities. Lastly, I never thought about the case where a pure function would need to call another function to operate on explicitly mutable but temporary local data. It would be nice to have that handled as well! It seems like the more you dig in to pure functions, the more you realize that the compiler needs to be able to be very smart to make the concept usable for programmers. As it stands now, it seems difficult for pure functions to interact with the rest of D.
Aug 01 2008