I have the following extension to Comparable where Self: Strideable
that adds a new method:
extension Comparable where Self: Strideable {
/// Inspects the correctness of the Bacon number (or `degrees` of separation) between this value and the given other value.
/// - Parameters:
/// - other: The given other value.
/// - degrees: The Bacon number.
/// - Returns: `true` if the Bacon number is correct, `false` otherwise.
func separates(from other: Self, byDegrees degrees: Self.Stride) -> Bool {
// Implementation omitted for now...
}
}
This is how I intend for the new method to work:
0.separates(from: 0, byDegrees: 0) // true
0.separates(from: 1, byDegrees: 1) // true
0.separates(from: 2, byDegrees: 5) // false
200.separates(from: 100, byDegrees: 100) // true
I tried 2 different implementations of this method:
// Implementation 1
func separates(from other: Self, byDegrees degrees: Self.Stride) -> Bool {
precondition(degrees > 0)
if self < other {
return other == self.advanced(by: degrees)
} else {
return self == other.advanced(by: degrees)
}
}
// Implementation 2
func separates(from other: Self, byDegrees degrees: Self.Stride) -> Bool {
precondition(degrees > 0)
if self < other {
return self.distance(to: other) == degrees
} else {
return other.distance(to: self) == degrees
}
}
Both implementations have problems.
Implementation 1 runs into error when degrees
is larger than max Self
. For example,
100.separates(from: 100, byDegrees: Int.max) // should be false,
// but runs into error because `Int.max`
// is too much to advance 100 by.
Int8.min.separates(from: Int8.max, byDegrees: 9999) // should be false,
// but runs into error because
// 9999 is too much to advance
// `Int8.min` by.
Implementation 2 runs into error when the actual separation is larger than max Stride
. For example,
Int.min.separates(from: Int.max, byDegrees: 20) // should be false,
// but runs into error because the
// distance between `Int.min` and
// `Int.max` is too large for `Stride`,
// which is `Int`.
Implementation 1 doesn't have implementation 2's problem, and vice versa.
Is there a way to implement this method without running into either of the 2 problems?