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

Dave Abrahams dabrahams at apple.com
Sun Jan 15 09:09:10 CST 2017


on Sun Jan 15 2017, Anton Zhilin <swift-evolution at swift.org> wrote:

> What about taking a mathematical approach to numbers?
>
> protocol Group : Equatable {
>     static var zero: Self { get }
>     static func + (Self, Self) -> Self
>     static func += (inout Self, Self)
>     static func - (Self, Self) -> Self
>     static func -= (inout Self, Self)
>     static prefix func - (Self) -> Self
> }
>
> protocol Ring : Group {
>     static var one: Self { get }
>     static func * (Self, Self) -> Self
>     static func *= (inout Self, Self)
>     func tryDivide(by: Self) -> Self?
>     func tryInvert() -> Self?
> }
>
> protocol Field : Ring {
>     static func / (Self, Self) -> Self
>     static func /= (inout Self, Self)
>     var inverted: Self { get }
> }
>
> protocol VectorSpace : Group {
>     associatedtype Scalar : Field
>     static func * (Self, Scalar) -> Self
>     static func *= (inout Self, Scalar) -> Self
>     static func / (Self, Scalar) -> Self
>     static func /= (inout Self, Scalar) -> Self
>     static func * (Scalar, Self) -> Self
> }

The first test for the inclusion of any protocol in the standard library
is: “what generic algorithm that uses this protocol as a constraint
would be appropriate for inclusion in the standard library?”

I don't think we have a use for any of the above directly in the
standard library.  All the generic algorithms I know of that would be
appropriate to those protocols are part of some specialized domain that
should have its own library built on top of the Swift standard lib.

> Detalization of mathematical terminology will be determined by what kind of
> types we have in the standard library. Integer types are rings (except for
> overflow), floating-point types are fields (except for precision), point
> types are linear spaces, so I thought the abstractions above are the bare
> minimum.
>
> Unfortunately, Swift doesn’t have rename operations for protocol
> requirements, so we can’t express groups that use operations other than +
> and -. What we can do is to include an adapter to wrap current instance in
> an additive group interface:
>
> struct MultiplicativeGroupAdapter<T: Field> : Group {
>     // ...
> }
>
> extension Field {
>     var multiplicativeGroup: MultiplicativeGroupAdapter<Self>
> }
>
>> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>

-- 
-Dave



More information about the swift-evolution mailing list