Proposal: Relax rules for 'pure'
Steven Schveighoffer
schveiguy at yahoo.com
Wed Sep 22 13:58:29 PDT 2010
On Wed, 22 Sep 2010 16:42:09 -0400, sclytrack <sclytrack at fake.com> wrote:
>
>> weaklypure void reverse(int[] x)
>> {
>> for(int i = 0; i * 2 < x.length; i++)
>> swap(x[i], x[$-1-i]);
>> }
>> pure int foo(const(int)[] x)
>> {
>> auto x2 = x.dup;
>> reverse(x2);
>> // do some calculation on x2
>> ...
>> return calculation;
>> }
>
> noglobal void reverse(MyClass x)
> {
> x.text = "";
> }
>
> So weakly-pure should not access global stuff. But that is harder
> to track by the compiler with mutable parameters.
No, it just means they cannot access data except through their arguments.
Global stuff is perfectly valid to pass in. However, any references must
not be shared, because those could be actively changed by other threads.
> Or weakly-pure is only noglobal when called in pure routines, because of
> the
> immutable barrier.
pure, weak or strong, means you cannot access global variables. e.g.:
int x;
shared int y;
pure foo(int *n)
{
x = 5; // illegal
*n = 5; // fine
}
foo(&x); // fine, x is TLS, it is guaranteed not to change from another
thread.
foo(&y); // nope
The difference between weak and strong is that weak pure functions cannot
be more optimized than normal functions. Strong pure functions can enjoy
the optimizations that functional languages have.
-Steve
More information about the Digitalmars-d
mailing list