[swift-evolution] Proposal proposal: @pure keyword

John Randolph jcr at mac.com
Tue Jan 12 14:56:21 CST 2016


> On Jan 9, 2016, at 7:01 AM, Michel Fortin via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 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.

On a related note, I can imagine a circumstance where a function might not meet the first definition here of “pure”, but I would still want the compiler to go ahead reuse the result of the first call it gets, throughout a given scope.  Say for example that I want to expensively look up some user info, and I can rely on that not changing during a single run of my app.

Qualifying a method with something like @resultsReusable would cover the situation I have in mind.

-jcr


More information about the swift-evolution mailing list