The easiest way is to define the implicit Ordering [T] on them, but then you must pass this ordering to the sort function (or any other function that wants to compare them). It can also be passed implicitly.
Another way would be: extend the tuple class to <statement via implicit listing:
implicit def compareTuple[T](lhs: (T,T)) = new { def <(rhs: (T,T)) = lhs._1<rhs._1 || (lhs._1==rhs._1 && lhs._2<rhs._2) }
edit If you want to have other comparison operators, you can get them by inheriting from Ordered [T]:
implicit def compareTuple[T](lhs: (T,T)) = new Ordered[(T,T)] { def compare(rhs: (T,T)) = ... }
edit2: If you also need to compare tuples of different sizes, you can use the productIterator function, which is defined in all tuple classes ( see the documentation ) and allows you to get an iterator over a tuple. This way you can write a function as if you did it with a list.
Edit3: It will be something like this:
implicit def compareTuple[T <: Product](lhs: T) = new Ordered[T] { def compare[U <: Product](rhs: U) = { def compare(lhs: Any, rhs: Any) = ... def iteratorCompare(lhs: Iterator[Any], rhs: Iterator[Any]):Int = if(!lhs.hasNext) if(!rhs.hasNext) 0 else -1 else if(!rhs.hasNext) 1 else compare(lhs.next,rhs.next) iteratorCompare(lhs.productIterator,rhs.productIterator) } }
But with this approach, you need to take care of the types. Since the function does not know the types of elements of the tuple (they can be different within the same tuple), it can provide only Iterator [Any]. Therefore, you need to define a comparison function (Any, Any) to handle what you want.
Heinzi Jun 19 2018-12-12T00: 00Z
source share