How to lexicographically compare scala tuples?

scala, tuples

Solution

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.

Problem

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 example of how to do it? ``` var x = (1,2,3) < (1,2,4) ``` Were they lists, I could define a recursive function that would compare the lists' head until a difference or the end of a list was found, but I don't think I could do that for tuples.

Original source

Related problems