[swift-evolution] [Pitch] Support for pure functions. Part n + 1.

Abe Schneider abe.schneider at gmail.com
Fri Feb 17 10:08:03 CST 2017


+1. I think this is a great idea. As I was following this thread, I
was wondering if someone might suggest the C++ constexpr syntax.

Would this support generics? E.g. could you do:

    @constepxr
    func foo<S>(a:S, b:S) {
       return a+b
    }

and have that be done at compile time? While this could potentially
add a huge amount of complication on the backend, I could this as
being useful (also related to my previous postings as to having a way
of determining generic types at compile time).


On Fri, Feb 17, 2017 at 8:01 AM, Anton Zhilin via swift-evolution
<swift-evolution at swift.org> wrote:
> My vision of “pure” functions was the following:
>
> Compiler automatically marks all functions and expressions as pure, wherever
> possible
>
> We should be interested not in “Haskell-ish pure” functions, but in
> “computable during compilation” functions
> Therefore I prefer to use @constexpr or const instead of @pure
>
> We can mark a function as const to assert that it is indeed pure
> We can mark a variable as const to ensure that it’s computed at compilation
> time
>
> Compiler might compute some non-const expressions, but no guarantees given
>
> One issue is, we don’t have or suggest any facilities to make use of pure
> functions, other than some optimization, which can be performed anyway as of
> now.
>
> One use-case would be conversion of metatypes to types:
>
> const let x: Any = makeSomething()
> typealias T = type(of: x)
>
> This feature can be powerful enough to fill the niche of macros in Swift,
> without unsafety of C++ or specific syntax of Rust.
>
> 2017-02-17 14:14 GMT+03:00 Haravikk via swift-evolution
> <swift-evolution at swift.org>:
>>
>> I like the idea of having pure functions in Swift, but my first thought
>> is; should we have to declare it at all? Is it not easier to just have the
>> compiler automatically flag a function as pure or not?
>>
>> With that in mind we don't need any new syntax, but a simple @pure
>> attribute should be sufficient. This can be used anywhere that a function is
>> declared, or a closure is accepted as a parameter, allowing us to be
>> explicit that we are trying to define a pure function, or only accept pure
>> closures.
>>
>> The big benefit of this is that it is retroactive; all existing functions
>> that are pure will be automatically detected as such, and can be passed into
>> any method accepting only pure functions. The new capability will be that
>> developers can specify that a function *must* be pure and thus produce an
>> error if it isn't.
>
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>


More information about the swift-evolution mailing list