Do pure functions solve the "return const" problems?

Michel Fortin michel.fortin at michelf.com
Sun Apr 27 18:43:48 PDT 2008


On 2008-04-27 02:29:19 -0400, "Janice Caron" <caron800 at googlemail.com> said:

> On 27/04/2008, Christopher Wright <dhasenan at gmail.com> wrote:
>> An out parameter is a return value. What else is there to get?
> 
> An out parameter is global state. Sometimes literally:
> 
>     void foo(out int x, int y) { x = y; }
> 
>     foo(globalVariable, 3);

Well, its the caller that binds it to a global state, not the function. 
How is the above different from:

	int bar(int y) pure { return y; }

	globalVariable = bar(3);

?

By the way, the ABI specifies that a function returning a struct 
recieves the address to write the struct to as a hidden parameter and 
write the final struct value there. Even returning a tuple (which is a 
struct) is implemented under the hood as a hidden out parameter; that 
shouldn't prevent its use as a return value in a pure function.


> Also, as has been repeatedly pointed out, one of the benefits of pure
> is that given an expression like
> 
>     f(x,y) + g(x,y)
> 
> the compiler is free to evaluate f first then g, or g first then f, at
> its discression. It is also free not to call either of these functions
> at all if it has a previously cached result handy. Out parameters must
> be forbidden, or those assumptions fail.

Well the compiler could just decide to not optimize pure function calls 
with out parameters. It doesn't prevent in any way optimization of pure 
function calls for functions with only in parameters.

In the example above, a clever compiler could even notice how you're 
always discarting the result of the call to f and just bind it to a 
different, otherwise unused, placeholder local variable; allowing it to 
paralellize the code. It shouldn't be much harder to optimize than 
silly repetitive assignments such as these:

	int x, y = 1;
	x = f(y);
	x = g(y);
	return x;

Pure should just mean "no side effects beyond what its signature says". 
The compiler should be able decide if it can, and should, paralelize 
calls by examining the function signature.


> If you want to return multiple values, use a tuple.
> 
>     import std.typecons;
> 
>     Tuple!(int,double) f(int x, double y) pure
>     {
>         return tuple(x+1, y+1);
>     }
> 
> It's not rocket science.

That'll work. The question is should you be forced to resort to that? I 
don't think so.


-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/




More information about the Digitalmars-d mailing list