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

Anton Zhilin antonyzhilin at gmail.com
Fri Feb 17 07:01:37 CST 2017


My vision of “pure” functions was the following:

   1. 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
   2. We can mark a function as const to *assert* that it is indeed pure
   3. 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.
>
​
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170217/f5da1774/attachment.html>


More information about the swift-evolution mailing list