[swift-evolution] Proposal proposal: @pure keyword

Andrew Bennett cacoyi at gmail.com
Sat Jan 9 06:56:45 CST 2016


Dmitri,

Thanks, that's a good point. That's related to why I was wondering about
self as inout in my reply to Howard. My rules were a starting point, I'm
sure there's things that can be improved. I'm glad we've got the
conversation started :)

The type of Array<Int>.sort is (Array<Int>) -> () -> Array<Int>

This type could be marked as pure like this:

(Array<Int>) @pure -> () @pure -> Array<Int>

The partial application of the function captures the current state of the
input array (value type), then the full application of the function sorts
and returns that array. I don't think there's a problem with purity here,
there's on *external* references.

It gets more interesting with a mutating function, Array<Int>.sortInPlace
is potentially pure as well:

(inout Array<Int>) @pure -> Void


This type signature could be considered equivalent to the type of
Array<Int>.sort. You're taking an array in, and sending an array out. It's
replacing the in array with the out one.

I think the important thing is that everything affected by the function is
in the type signature.

Andrew





On Sat, Jan 9, 2016 at 9:29 PM, Dmitri Gribenko <gribozavr at gmail.com> wrote:

> On Sat, Jan 9, 2016 at 10:53 AM, Andrew Bennett via swift-evolution <
> swift-evolution at swift.org> wrote:
>
>> 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.
>>
>
> I'm concerned that with this definition we won't be able to mark many APIs
> as pure, even though they actually are pure.  The issue is that this
> definition disallows local mutation.  Consider CollectionType.sort() -- the
> way it is implemented is that it first copies the collection into an array,
> and then sorts that array in-place.  sortInPlace() isn't pure, but because
> the mutation happens on local state, the whole operation is pure.
>
> Dmitri
>
> --
> main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
> (j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160109/c20aeb38/attachment.html>


More information about the swift-evolution mailing list