Improvement in pure functions specification

Johan Engelen via Digitalmars-d digitalmars-d at puremagic.com
Wed Dec 21 12:04:04 PST 2016


On Wednesday, 21 December 2016 at 15:40:42 UTC, Andrei 
Alexandrescu wrote:
> On 12/20/2016 05:49 PM, Andrei Alexandrescu wrote:
>> https://github.com/dlang/dlang.org/pull/1528 -- Andrei
>
> Dropped the void functions. On to the next scandal:

I think you should be very careful in making sure that `pure` 
does not become a pessimization keyword.

```
$(P Any `pure` function that is not strongly pure cannot be 
memoized. The
      compiler is required to honor all calls to the function, 
even if it appears
      to do nothing. (Example: a pure function taking no arguments 
and returning
      `int*` cannot be memoized. It also should not because it may 
be a typical
      factory function returning a fresh pointer with each call.))
```
I don't know what "required to honor all calls" means, but I 
guess it means
```
auto a = foo(); // int* foo() pure;
auto b = foo();
```
cannot be transformed to
```
auto a = foo(); // int* foo() pure;
auto b = a;
```

Super contrived, but I hope you get my drift:
```
int *awesome() pure {
   static if (ohSoAwesome) {
      return new int;
   } else {
      return null;
   }
}
```
Tagging this function with `pure` would be a pessimization.
Instead of
   "Any `pure` function that is not strongly pure cannot be 
memoized."
why not
   "Any `pure` function that is not strongly pure _may not be 
assumed to be_ memoizable."

Another example:
```
/// Note: need to mark this function as non-pure, because 
otherwise the compiler deduces it as pure and then pessimizes our 
code.
int *bar(bool returnNull) nonpure {
   if (returnNull) {
      return null;
   } else {
      return new ...;
   }
}

auto a = bar(true);
auto b = bar(true);
auto c = bar(true);
```

My concern with the current wording (like for the void function 
thing) is that it actively prohibits the compiler to do a 
transformation even if that is valid.

-Johan



More information about the Digitalmars-d mailing list