Purity

spir denis.spir at gmail.com
Sat Dec 18 06:25:45 PST 2010


On Sat, 18 Dec 2010 13:46:11 +0100
Don <nospam at nospam.com> wrote:

> spir wrote:
> > On Sat, 18 Dec 2010 01:08:20 -0800
> > Jonathan M Davis <jmdavisProg at gmx.com> wrote:
> > 
> > Thank you for the explanation about strongly pure funcs calling weakly pure ones --this fully makes sense.
> > 
> >>> I would like weakly pure to include output funcs, and exclude all
> >>> possibilities to modify (non-local) state.  
> >> The problem is that output is accessing global variables - which weakly pure 
> >> functions _cannot_ do.
> > 
> > Why? What is the rationale for excluding output (I don't mean I/O, only O)?
> 
> You're correct in saying that it doesn't affect the operation of the 
> program. But in practice, program output is almost always important.
> 
> For example, suppose we allowed output to be pure. Then consider:
> 
> writeln("Hello, world!");
> 
> Since it returns nothing, and has no influence on the future execution 
> of the program, the writeln can be dropped from the program.
> 
> Hmmm....

For sure, if you specify (in the compiler behaviour) that the only purpose of a pure function is to return something. Which excudes all "action-fonctions" (= funcs which purpose is to perform an effect). But why should the compiler rewrite of such a func be to erase it? Just let it alone, it won't bother anybody. And can safely be qualified as pure. So that, transitively, pure funcs can call funcs that perform output. Just what we want.
	pure Report getReport (Data data) {
	    // compute report from data (only)
	    log.write(report);
	    writefln("report computed:\n\t%s", report);   // debug
	    return report;
	}

Anyway, aside practicle & efficiency purposes, I'm even more annoyed by the "conceptual wrongness" of excluding functions that perform output from the "world of purity" ;-) I would want them included even if this did not buy anything.
All of this would be easier and clearer if D made a proper distinction between 'true' functions (that compute a result) and 'action-functions' (that perform an effect). The actual purity criteria need not be the same:
* actions must not write to state
* functions must not read from state
Just state: output ports and memory do not belong to program state, and we're done.
There is an asymmetry: runtime/variable data input (from user, file,...) must be considered as state, else a compiler cannot memoize function results.


Denis
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d mailing list