Question

I created a generic class MyClass<T: Numeric> {...} and got errors in my functions that tried to use > and <, along the lines of "Binary operator '>' cannot be applied to two 'T' operands." I spent quite a while thinking that the problem was some syntax error I had made in the declaration. But sure enough, Numeric doesn't inherit from Comparable. I am stunned. Why would this be?

Was it helpful?

Solution

There is a notable numeric type that is not comparable: complex numbers.

Complex numbers consist of a “real” and “imaginary” part, or equivalently a “magnitude” and “phase”. There is no obvious order to imaginary numbers. By not including Comparable, the Numeric protocol could also be used to represent complex numbers.

Note that Numeric also doesn't include division. I am not sure why this was excluded, but note that division is only partially defined for integers, e.g. 3/2 does not produce an integer value. Different languages tackle this differently (C rounds to zero, sensible languages produce floating point numbers, Perl6 produces rational numbers, …). It therefore seems legitimate to exclude these decisions from a very fundamental protocol like Numeric rather than forcing implementing types to make a decision.

(More formally: common numeric types are closed under addition and multiplication. Unsigned types with underflow (i.e. modular arithmetic) and signed types are also closed under subtraction. Integers are not closed under division. Closure means that the output type of an operation is the same as the input type.)

While Numeric is focussed on scalar values, there are many examples of (non-scalar) mathematical constructs that have no order and no division either. Notably, vectors and matrices.

Protocols should be as minimal as they can be while still being useful. They should not constrain types unnecessary. Compare also the SOLID principles: the Interface Segregation Principle (ISP) states that users should not be forced to depend on methods they don't use.

Licensed under: CC-BY-SA with attribution
scroll top