Pure functions

Deewiant deewiant.doesnotlike.spam at gmail.com
Thu Jun 14 10:32:39 PDT 2007


OF wrote:
> Georg Wrede Wrote:
> 
>> Conclusion
>> 
>> For the purposes of language development, we now have two attributes for 
>> each function: does it change its arguments, and does it change anything 
>> else. I'd actually like to have these incorporated into the function 
>> signature. A function can only be Pure if all the functions it calls are 
>> Pure (i.e. do not change anything) and it is Pure itself.
>> 
>> It might be useful to have "does chanege its arguments" as a flag which can
>> quickly be checked during compilation, even if it is deducable from the
>> argument declarations. This may speed things up. But the *more* important
>> flag would be whether the function may change "external" things. This is
>> hard to see without a flag in the signature.
>> 
>> 
>> I see that pure functions will gain more importance in the near future of
>> D, and therefore we should prepare for it now with this flag.
> 
> I've actually been thinking about exactly this (pure functions in D) and
> can't let this pass without giving it support.
> 
> Pure functions are great for both bug fighting reasons and optimizations.
> Knowing that a function doesn't have any side effects at all means that it
> can not be the source of "weird" bugs, and it means that it can run
> concurrently. That it has the same return value for any given input is nice
> for optimizations -- one could even implement dynamic programming generation
> in the compiler (though I can't say I'd suggest that for D), and if the input
> is constant pure functions can always be run at compile time.
> 
> Those that haven't used pure functional or even just functional languages
> might not appreciate the simplifications pure functions brings, but it makes
> very much sense to use on "real" functions (like mathematical functions, as
> compared to procedures/subroutines).
> 
> It might be beyond the intended scope of D, but a simple pure attribute for
> pure functions would be very nice and could be beneficial. I can see the
> problems with enforcing it though, without restricting pointer and perhaps gc
> use.
> 
> Just my point of view.

Pure functions would need to be limited in more ways than that. Here's some
stuff beyond pointers and the heap which pure functions can't mess with:
	- static variables,
	- impure functions,
	- any state (non-const variables) defined outside the function.

I actually just took these from my original post on the issue (Message-ID is
e014er$22rn$1 at digitaldaemon.com, it can also be found at
http://www.digitalmars.com/pnews/read.php?server=news.digitalmars.com&group=digitalmars.D&artnum=35852).

That was in the context of templates, with Hasan Aljudy asking for CTFE, but
pure functions are IMHO notably more useful. It's a handy compile-time contract
and leads to a lot of optimization opportunities.



More information about the Digitalmars-d mailing list