What is pure used for?

Paul Backus snarwin at gmail.com
Thu Nov 25 15:17:00 UTC 2021

On Thursday, 25 November 2021 at 07:26:48 UTC, sclytrack wrote:
> int * pureFunction()
> 1) the pointer needs to be the same.
> 2) the value that the pointer points to needs to be the same. I 
> call this the "value
> of interest" with relation to pure. The pointer doesn't matter.
> 3) both the pointer and the value the pointer is pointing too 
> needs to be the same.
> pureCalloc() satisfies (2)
> pureMalloc() violates everything.

There is a special case in the language spec to allow functions 
like `pureMalloc`. They are called "pure factory functions":

> A *pure factory function* is a strongly pure function that 
> returns a result that has mutable indirections. All mutable 
> memory returned by the call may not be referenced by any other 
> part of the program, i.e. it is newly allocated by the 
> function. Nor may the mutable references of the result refer to 
> any object that existed before the function call.

Source: <https://dlang.org/spec/function.html#pure-functions> 
(scroll down)

> Does the D compiler do any optimizations?

Yes, but those optimizations may result in implementation-defined 

> **Implementation Defined:** An implementation may assume that a 
> strongly pure function that returns a result without mutable 
> indirections will have the same effect for all invocations with 
> equivalent arguments. It is allowed to memoize the result of 
> the function under the assumption that equivalent parameters 
> always produce equivalent results. [...] An implementation is 
> currently not required to enforce validity of memoization in 
> all cases.

The term "equivalent" is not explicitly defined, but as far as I 
can tell it means something like item (2) in your list.

More information about the Digitalmars-d-learn mailing list