Jesse Phillips wrote:
Steven Schveighoffer Wrote:
If we can define weakly pure functions this way, they most likely will be
way more common than unpure functions. I know I avoid accessing global
variables in most of my functions. Think about a range, almost all the
methods in a range can be weakly pure. So that means you need to mark
every function as pure.
I think that's true. I/O is impure, but most other things are not.
Would it not be less tedious to mark unpure functions instead of pure
functions? Or am I just going too far with this?
You can use
pure:
at the top of the file.
The problem is that there's no syntax for impure, so it can't be used if
you have a single impure function (which does logging, for example).
You can also wrap a bunch of functions in pure {}.
OR, maybe we could say, mark strongly pure functions as pure, mark
functions that access global data as something else (global?) and weakly
pure functions just aren't marked.
-Steve
This is interesting, I'm not sure if either of these approaches could make it
into D2, though a conservative approach was originally taken only because it
was the most easy to prove.
I also find it interesting that D actually takes the 3-stage approach to
several things. mutable, const, immutable; @safe, @trusted, @system. And this
being unpure, contained, pure.
D recognizes the importance of these stages in other areas, so I feel it would
be a miss if there is not a good reason the proposal doesn't work. Sadly what
you learn from one of the stated areas (mutability, safety, purity) can't be
applied to the other. But the pattern is there.
Interestingly, 'pure' is much simpler.
A weakly pure function can modify only the mutable parameters it was
given. There's no need for a different language syntax for strongly
pure, because it's just the case where the number of mutable parameters
it was given are zero.
The point is that weakly pure and strongly pure are almost the same.
int weakfoo(ref int x) pure;
is exactly the same as strongly pure, except that it can also modify one
single int, which you specify. Whereas
int impurefoo(int x);
could be doing _anything_.