www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Less pure for objects

reply bearophile <bearophileHUGS lycos.com> writes:
I don't use pure functions all the time, but I appreciate them for the help
they give to reduce bugs. A problem is that pure functions are mostly for
functional programming, not for OOP.

For classes the pure functions are less useful, they can be virtual and be
overridden, but they can't change the instance, so they are a subset of the
const methods.

So it can be invented an attribute for class/struct methods that like 'pure'
helps reducing side effects, but more useful (and less restrictive) for OOP.
This attribute can be a superset of pure, it allows to call pure
functions/methods, but pure functions can't call them.

A possible way to design this idea: an attribute that allows a method to modify
only its instance attribute and nothing else (no the input arguments, variable
in outer scopes, no modify other object, etc.).

I don't know if this can be useful in practice. It doesn't look good. Maybe you
can invent something else.

Bye,
bearophile
Apr 25 2010
parent reply bearophile <bearophileHUGS lycos.com> writes:
I have done a little experiment, and this code runs:


struct Foo {
    int x;
    pure int bar(int y) {
        return this.x + y;
    }
}
void main() {
    auto f = Foo(10);
    assert(f.bar(7) == 17);
}


So the current D2 implementation works already as in my "half_pure" proposal :o)
I think this can be seen as a bug, but I have not filed it yet.

Bye,
bearophile
Apr 29 2010
parent bearophile <bearophileHUGS lycos.com> writes:
 I think this can be seen as a bug, but I have not filed it yet.
I like it, it's more useful this way, I don't want to file a bug. Bye, bearophile
Apr 29 2010