[swift-evolution] Proposal proposal: @pure keyword
Howard Lovatt
howard.lovatt at gmail.com
Sat Jan 9 02:56:07 CST 2016
I would rather you mark a function as impure and have the default as pure!
> On 9 Jan 2016, at 7:53 PM, Andrew Bennett via swift-evolution <swift-evolution at swift.org> wrote:
>
> I'd like to discuss adding a @pure keyword, and see what it requires and how possible it is to include.
>
> I'd like to use the annotation @pure on functions, methods and closures.
>
> This will allow us to make more guarantees about what a protocol does, and what it cannot do. It will also allow APIs like `.map` and `.forEach` to have a meaningful distinction. It could also allow for something like an assert to be removed as an optimisation with no side-effects in a release build.
>
> If something is pure it can be annotated with @pure, if it is not-pure this will be a compile-time error. The compiler could automatically add this annotation in the interface.
>
> A function, method or closure is pure if:
> * all functions, methods and closures it calls are also pure (this includes referencing self from a method or property)
> * it only externally references let variables of pure type, let properties on those variables, and methods/computer-properties marked as pure.
>
> A computed property can be marked as pure like this:
> @pure var test: A
>
> A function/method/closure signature is marked as pure like this:
> (a: A, b: A -> B) @pure -> B
>
> If the function/method/closure is only pure if an argument is pure (similar to @rethrows), then you could do this:
> (start: A, a: A -> B) @pure(b) -> B
>
> Potentially this could be extended to allow a pure closure to be composed of other pure closures:
> func compose(a: A -> B, b: B -> C) @pure -> A @pure(a,b) -> C {
> return { b(a($0)) }
> }
>
> Of course this doesn't preclude you from requiring some of those closures to be pure:
> func compose(a: A @pure -> B, b: B -> C) @pure -> A @pure(b) -> C {
> return { b(a($0)) }
> }
>
> Impact on existing code:
> No negative impact as if automatic annotation was allowed it would only happen where it was safe to do so. If it was not allowed then libraries could be slowly annotated to be marked as pure.
>
> c and objective-c would not be marked as pure.
>
> Pure functions can be safely removed by the optimiser if their result is not used. From this perspective assert and print should not be marked as pure (they would have to be an exception anyway).
>
> Ideally existing libraries would be annotated, the more the better, but this can be a gradual process.
>
>
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160109/502ed499/attachment.html>
More information about the swift-evolution
mailing list