Do pure functions solve the "return const" problems?

Janice Caron caron800 at googlemail.com
Sun Apr 27 09:54:03 PDT 2008


On 27/04/2008, Christopher Wright <dhasenan at gmail.com> wrote:
> > An out parameter is global state. Sometimes literally:
> >
> >    void foo(out int x, int y) { x = y; }
> >
> >    foo(globalVariable, 3);
> >
>
>  Then the calling function isn't pure!

The function itself isn't pure!
foo() isn't pure!


>  I could also do:
>  int foo(int y) { return y; }
>  globalVariable = foo(3);

That's irrelevant. globalVariable is assigned /after/ the function
returned (not during function execution, as would be the case with an
out parameter).

Assigning a global variable *during function execution* violates the
contract for purity, but you can do whatever you like with return
values, after the function exits.


> > Out parameters must
> > be forbidden, or those assumptions fail.
>
>  Then so must return values!

Watch closely. Given

    int f(out int x, int y) { x = y+2; return y-1; }
    int g(out int x, int y) { x = y-1; return y+1; }

the expression

    int n = f(x,3) + g(x,3)

will result in

    n = 6 always, but
    x = 2 (if f was evaluated first), or 5 (if g was evaluated first).

The PURE way to do it is:

    alias Tuple!(int,int) pair;
    pure pair f(int y) { return tuple(y+2,y-1); }
    pure pair g(int y) { return tuple(y-1,y+1); }
    pure pair add(pair lhs, pair rhs)
        { return tuple(lhs._0 + rhs._0, lhs._1 + rhs._1); }

and now the expression

    add( f(3), g(3) );

will result in the pair { 7, 6 } always, /regardless/ of which of f or
g gets evaluated first.



More information about the Digitalmars-d mailing list