How to lexicographically compare scala tuples?

后端 未结 3 2052
暗喜
暗喜 2020-12-14 08:54

Given two tuples of the same arity, how can I lexicographically compare them? It seems like this should be as simple as in the following snippet, but it isn\'t. Any simple e

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-14 09:41

    It's not simple because while

    var x = (1,2,3) < (1,2)
    

    looks pretty simple,

    var x = (1,false,3) < (1,2)
    

    is not. How do you deal with non-ordered types? How do you deal with different types in the same tuple position?

    Do you mandate all types to be the same? In that case, you do not have a tuple. The whole point of a tuple is that its arity is fixed (you statically know how big it is) and each element can be of a different type.

    If I found myself with that problem -- and I'd try very hard not to -- I'd grab Shapeless, convert the tuples into something like HLists, and then try to compare on that.

    EDIT

    Ah, now it is much easier:

    import scala.math.Ordering.Implicits._
    var x = (1,2,3) < (1,2,4)
    

    These extra implicits are not automatically available because they can result in diverging implicits under some circumstances.

提交回复
热议问题