Idea: partially pure functions
Steven Schveighoffer
schveiguy at yahoo.com
Thu May 1 08:57:58 PDT 2008
"Bruno Medeiros" wrote
> Steven Schveighoffer wrote:
>>
>>
>> So in the case of a partially pure function that takes a char array:
>>
>> pure void f(char[] x) {...}
>>
>> Let's say I have a non-pure function g:
>>
>> void g()
>> {
>> char[] v;
>> ...
>> f(v);
>> }
>>
>> In the ..., v can be set to local mutable heap data (via new char[x] or
>> whatever), or it could be set to point to a global mutable string. How
>> can the compiler be sure without severe context analysis? The point is,
>> in order to ensure context-free lexical analysis by the compiler, it must
>> disallow calling f from a non-pure function.
>>
>
> Huh? You're mixing things up.
> Yes, if g() is not pure, then the compiler will not check if v points to
> global data or not. Thus we cannot guarantee that calling "f(v)" will not
> change global state. But so what?
> That doesn't mean we shouldn't allow it. It just means such call may have
> side-effects, and the compiler should threat that as a normal function
> call (make no particular pure optimizations). Thus "partially" pure: pure
> in some contexts, impure in other contexts.
OK, I think I see what the barrier here is. Walter and Andrei's version of
pure is supposed to be for solving multithreading issues. There is an
attribute of D pure functions that is inherently true in functional
programming languages. Not only does a pure function have no side effects,
but nothing outside the pure function can affect its execution. If v points
to global data, and some other thread changes that data mid-way through the
function execution, the function might crash or throw an exception because
it is expecting to be the only one that can change it's own data. With that
in mind, partially pure functions that have mutable parameters cannot have
that attribute unless it is guaranteed that those mutable parameters won't
be changed by anything outside the partially pure function. The only way to
guarantee that is to only allow calling that function from another pure or
partially pure function.
-Steve
More information about the Digitalmars-d
mailing list