Experiments with weak purity for the win, @outer

bearophile bearophileHUGS at lycos.com
Tue Oct 26 17:29:23 PDT 2010


The weak purity is big. With DMD 2.050 many Phobos functions will be able to support the pure attribute.

This is just a little example, swap:
http://d.puremagic.com/issues/show_bug.cgi?id=5121

A more complex example, sort, with the problems I've found (using 2.050alpha):
http://d.puremagic.com/issues/show_bug.cgi?id=5124

One of the troubles I've found is with "auto pure" nested functions, this asserts:

// see http://d.puremagic.com/issues/show_bug.cgi?id=5006
import std.traits: FunctionAttribute, functionAttributes;
void main() {
    static pure int foo1(int x) { return x; }
    pure int foo2(int x) { return x; }
    static assert(functionAttributes!(foo1) & FunctionAttribute.PURE); // asserts
    static assert(functionAttributes!(foo2) & FunctionAttribute.PURE); // asserts
}


Weak pure functions may become so common in my code that I'd like them to be weak pure on default :-) I know that because of C compatibility this is not an acceptable change in D.


Another step forward may come from an @outer attribute, that allows to put a final stop to the unruly usage of globals (outer) variables as done in C (Spark language already has something similar, and its usage is obligatory. In D the @outer is meant to be optional):


int x = 100;
int y = 200;

@outer(in x, inout y)
int foo(int z) {
    y = x + z;
    return y;
}

The usage of #outer is optional, but if you use it then all constraints implied you see in that code are enforced. See for more info:
http://d.puremagic.com/issues/show_bug.cgi?id=5007


Eventually it will become useful to have a way to apply or not apply the pure attribute to a function according to a compile-time test, so a function template may become pure or not according to the kind of template arguments it receives.

Bye,
bearophile


More information about the Digitalmars-d mailing list