Possible 'pure' bug with int[] slice. Programming in D page 174
Steven Schveighoffer
schveiguy at gmail.com
Sun Oct 5 21:26:01 UTC 2025
On Saturday, 4 October 2025 at 12:40:43 UTC, Brother Bill wrote:
> On Saturday, 4 October 2025 at 12:14:06 UTC, Dmitry Olshansky
> wrote:
>> It’s weakly pure in that it could only mutate things that are
>> passed in. Strongly pure would require no mutable
>> pointers/slices/references.
>> It may be misleading that it’s single keyword for both of
>> these. The good news is that strongly pure functions can call
>> weakly pure function and stay strongly pure.
>
> So if we don't want to allow mutating passing in parameters,
> add 'in' keyword to each parameter. Then it should be strongly
> cure. Is that correct?
> ```
> int[] inner(in int[] slice) pure
> ```
To give a little more context:
Traditionally, pure functions, and functional programming, do not
allow mutation of parameters. Because that would disable
functional optimizations (such as changing `pureFunc(1) +
pureFunc(1)` into `2 * pureFunc(1)`.
But what happens inside a pure function? In D we write
non-functional imperative code with mutable variables. What does
it matter to the caller of `pureFunc` whether there are some
mutations going on, as long as there are no observable side
effects?
There are some nice abstractions to be had with mutating
parameters, which could be used from both traditional pure
functions, and impure functions.
For example, consider sorting. `sort(arr)` sorts an array
in-place. But effectively, it has no side effects aside from that
one.
So as long as the swapping that occurs during sort is not causing
observable side effects, it can be considered "weakly pure".
This means it is possible to take the existing
`std.algorithm.sort` function, and use it from a strongly pure
function:
```d
const(int[]) pureSort(const(int[]) input) pure {
auto result = input.dup; // make a copy;
result.sort(); // sort the copy;
return result;
}
```
Such a function can be considered "strong" or traditionally pure,
since there are no observable side effects (other than memory
being allocated, but this is an accepted exception for functional
languages).
The benefit here is, we can mark `sort` as a pure function, even
though it modifies the parameter, and then we don't have to write
a "special" implementation for sorting for pure functions. You
just use the normal D ones.
-Steve
More information about the Digitalmars-d-learn
mailing list