[swift-evolution] Proposal proposal: @pure keyword

Michel Fortin michel.fortin at michelf.ca
Sat Jan 9 09:01:01 CST 2016


Le 9 janv. 2016 à 8:16, Angelo Villegas via swift-evolution <swift-evolution at swift.org> a écrit :

> I'm not yet really familiar with this term but correct me if I'm wrong, "pure" (function wise) means functions won't have access to global or static, and mutable variables through their arguments, right?

This is actually the most important part to define. There are many ways to define it, each with different tradeoffs. Here are the two base ones:

1. Pure means that the function always return the same value given the same arguments, and has no side effects (it purely computes a result from its inputs), making it possible for the compiler, or a cache, to reuse the result from a previous call. This is the simplest definition, and it provide strong guaranties. Let's call that "strongly pure".

2. Pure just mean that the function has no access to global variables. It can only mutate "outside" things through inout parameters or pointers (including class references) passed to it by the caller. So in the general case you can't reuse the results. But you can use this function to mutate the state inside a strongly pure one. A strongly pure function in this case is one with no inout or pointer in the signature.

It makes more sense to use (2) to define `@pure` in my opinion. Note that this is what the D language has done, after noticing it to be much more useful than what they had before before, which was (1).

All that's good in theory, but there is a major detail that needs addressing. Memory allocation breaks the guaranties of a "strongly pure" function. For instance, if you return a newly allocated object, or a struct with a pointer to an object, the object is going to be a different one every time. That object is mutable memory, and returning a different chunk of mutable memory is quite different in semantics from returning the same one. If you want strong purity guaranties when returning objects (and thus be able to optimize by reusing the result from a previous call), there needs to be a way to return objects that have a language-enforced guaranty of immutability... same for structs that can have a pointer to an object or other memory. Without immutability guaranties, `@pure` has almost no optimization value.

-- 
Michel Fortin
https://michelf.ca



More information about the swift-evolution mailing list