March 21, 2014 Re: Most basic nothrow, pure, @safe functions? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Steven Schveighoffer | On 3/21/2014 11:23 AM, Steven Schveighoffer wrote:
> On Fri, 21 Mar 2014 14:18:05 -0400, Walter Bright <newshound2@digitalmars.com>
> wrote:
>
>> On 3/21/2014 12:59 AM, monarch_dodra wrote:
>>> Ok. That's a fair point. So in that case, our function is pointing at "data",
>>> and is allowed to mutate it, and observe its state.
>>>
>>> Now, if *another* piece of code is doing the same thing at the same time
>>> (potentially mutating "data", does that still violate purity?
>>
>> A mutex essentially reads and writes a global flag, which other functions can
>> also read and write.
>>
>> That makes it NOT pure.
>
> No, that's not the case. A mutex does not write a global flag, it writes a
> shared flag. And the flag is passed into it.
Here's a litmus test you can use for purity. Consider:
int foo() pure;
{
auto a = foo();
}
Now, since 'a' is never used, we can delete the assignment, and since foo is pure, we can delete foo():
{
}
Is this program distinguishable from the former? If not, then foo() is not pure.
|
March 21, 2014 Re: Most basic nothrow, pure, @safe functions? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Walter Bright | On Friday, 21 March 2014 at 19:19:06 UTC, Walter Bright wrote:
> Here's a litmus test you can use for purity. Consider:
>
> int foo() pure;
> {
> auto a = foo();
> }
>
> Now, since 'a' is never used, we can delete the assignment, and since foo is pure, we can delete foo():
>
> {
> }
>
> Is this program distinguishable from the former? If not, then foo() is not pure.
Consider this:
int foo(int* pa) pure
{
if (pa)
{
*pa = foo();
}
}
This is also pure according to D's type system, but it fails your litmus test. This, however, passes:
int foo(immutable(int)* pa) pure
{
pa = pfoo();
}
I think the case of a monitor is closer to the first example.
|
Copyright © 1999-2021 by the D Language Foundation