Make Array conditionally conform to Comparable?

As of Swift 4.1, Array conforms to Equatable if its element type does, and as of Swift 4.2, Array conforms to Hashable if its element type does.

Has it been discussed whether a conditional conformance to Comparable should also be synthesized for Array (and ArraySlice, ContiguousArray)? The lexicographic comparison of the array elements seems to be the natural choice.

2 Likes

What would the semantics of such an Array comparison be, exactly? If a and b are Arrays and a < b, does this mean that every element in a is less than every element of b? Or is it a "dictionary" comparison, similar to what strings do: going element by element and returning the comparison result of the first elements that differ, or stopping returning true if the first operand is a prefix of the second?

The latter (which is what I know as the “lexicographical order”). This is also used for tuple comparison. An implementation could look like this:

extension Array: Comparable where Element: Comparable {
    public static func < (lhs: [Element], rhs: [Element]) -> Bool {
        for (leftElement, rightElement) in zip(lhs, rhs) {
            if leftElement < rightElement {
                return true
            } else if leftElement > rightElement {
                return false
            }
        }
        return lhs.count < rhs.count
    }
}
1 Like

We even have comparison operators for tuples...
I don't think those make much sense, but given that precedent, I can't see why Array shouldn't conform to Comparable.