One can use < with a tuple, at least if import scala.math.Ordering.Implicits._ is present. This doesn’t allow math.min to be used however, because it is only defined for mathy arguments. How can I write a def min[T](x: T, y: T): T with the correct <:, imports, implicits, and everything for it to work on a relatively generic pair of tuples?
If you have
import Ordering.Implicits._ you can even simply use the infix extension method
scala> import Ordering.Implicits._ import Ordering.Implicits._ scala> (1,2,3) min (1,2,2) val res0: (Int, Int, Int) = (1,2,2)
scala> def min[T: Ordering](x: T, y: T): T = Ordering[T].min(x, y) def min[T](x: T, y: T)(implicit evidence$1: Ordering[T]): T scala> min((1,2,3), (1,2,2)) val res0: (Int, Int, Int) = (1,2,2)
Thank you! I was missing at least this Ordering[T]. idea.
It’s a shortcut for
implicitly[Ordering[T]]. It works because companion object
Ordering has a method
def apply[T: Ordering] = implicitly[Ordering[T]]. This allows you to write
Ordering.apply[T] which can be shortened to
Another alternative is writing
def min[T](x: T, y: T)(implicit ord: Ordering[T]): T = ord.min(x, y)