Make Numeric Refine a new AdditiveArithmetic Protocol

That could be done like this:

extension AdditiveArithmetic where Self: SignedNumeric {
    prefix static func - (x: Self) -> Self {
        return Self.zero - x
    }
}

It has all the normal benefits of a default implementation, but I'm not sure that's the best way. Since prefix - wouldn't be a protocol requirement, any concrete implementation would only be used in non-generic contexts. An obvious alternative is:

protocol AdditiveSignedArithimetic : AdditiveArithmetic, SignedNumeric {
    prefix static func - (x: Self) -> Self
}
extension AdditiveSignedArithimetic {
    prefix static func - (x: Self) -> Self {
        return Self.zero - x
    }
}

That way there's still a default implementation, but it's only called for types whose authors didn't come up with a better idea since any concrete implementation would show up in the protocol's witness table (at least I think that's how that works... been a while since I looked at those rules).

The constrained extension is redundant, because SignedNumeric already refines Numeric, and Numeric refines AdditiveArithmetic.

1 Like

I assumed the reason Steve included prefix - was to have a way to get IEEE 754 -0.0, but maybe it doesn't even do that.

Good point. Element-wise multiplication, which is the Hadamard product, would indeed requalify that protocol into a ring template, albeit an order of magnitude more narrowly specialized that we would expect. The protocol targets arbitrary vector spaces where the set of elements are not said to form a ring over some product as well, while the Hadamard product probably only works fine with numeric vectors, in practice, at least. Using * for that is another source of confusion in the general case, as already mentioned.

The remaining additive arithmetic looks pretty convincing as a fundamental functional unit for the ML and vector libraries, as well as some separate vector-like types that would benefit from adopting arithmetic operations, i.e. SCNVector and even CGPoint.

5 Likes

I created a PR for the proposal: [Proposal] Make Numeric Refine a new AdditiveArithmetic Protocol by rxwei · Pull Request #942 · apple/swift-evolution · GitHub.