[swift-evolution] protocol-oriented integers (take 2)

Tony Allevato tony.allevato at gmail.com
Wed Jan 25 13:01:16 CST 2017


It should already be possible to handle special cases like that since you
can reässign self in an initializer. Here's a contrived example; would it
allay your performance concerns?

```
struct Foo: ExpressibleByIntegerLiteral {
    private let value: String
    private static let zero = Foo("a really big thing")

    init(integerLiteral value: Int) {
        if value == 0 {
            self = .zero
        } else {
            self = Foo(String(value))
        }
    }

    private init(_ value: String) {
        self.value = value
    }
}

let x: Foo = 5   // value = "5"
let y: Foo = 0   // value = "a really big thing"
```

Given that, I definitely prefer the more natural literal expressibility to
the words "zero" and "one".


On Wed, Jan 25, 2017 at 10:45 AM David Sweeris via swift-evolution <
swift-evolution at swift.org> wrote:

>
> On Jan 25, 2017, at 10:03, Xiaodi Wu via swift-evolution <
> swift-evolution at swift.org> wrote:
>
> Stephen Canon wrote that Arithmetic should refine
> ExpressibleByIntegerLiteral because of certain mathematical properties of
> rings. In that case, 0 and 1 would just be spelled in that way. Otherwise,
> +1.
> On Wed, Jan 25, 2017 at 11:38 Anton Mironov via swift-evolution <
> swift-evolution at swift.org> wrote:
>
> Hi everyone,
>
> I want to suggest a tiny extension to an Arithmetic protocol. It would be
> nice to have an additive identity and a multiplicative identity constants.
> Basically zero and one.
>
> ```
> protocol Arithmetic {
>   /* ... */
>   static var zero: Self { get }  // additive identity: (value + .zero) ==
> value
>   static var one: Self { get }   // multiplicative identity: (value *
> .one) == value
> }
> ```
>
> These constants will ease implementation of math structures: vectors,
> matrices and etc.
> I’m sorry if I’m duplicating someone’s suggestion. It is really hard to
> search for something in a long thread.
>
>
> There is some merit in having them be declared as static properties... If
> it's a non-trivial process to initialize a type, it might be worth it to
> have a static property that either provides the storage directly or just
> returns a fileprivate value declared outside the type.
>
> - Dave Sweeris
> _______________________________________________
> 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/20170125/24168e20/attachment.html>


More information about the swift-evolution mailing list