This does what I want:
val ord = Ordering.Tuple2(Ordering[String].reverse, Ordering[Int])
But given that Tuple2
is an implicit function of implicit arguments, this feels too explicit. Am I missing a nicer way to express the same thing?
This does what I want:
val ord = Ordering.Tuple2(Ordering[String].reverse, Ordering[Int])
But given that Tuple2
is an implicit function of implicit arguments, this feels too explicit. Am I missing a nicer way to express the same thing?
This was the best I could do:
val reversed = Ordering[String].reverse
val bigBrainOrd: Ordering[(String, Int)] =
given Ordering[String] = reversed
summon
bigBrainOrd.compare("Elmer" -> 1, "Esmerelda" -> 2) // 7
summon[Ordering[(String, Int)]].compare("Elmer" -> 1, "Esmerelda" -> 2) // -7
Honestly, this grug thinks your way is much better. Will club own head now.
This also works:
given Ordering[String] = Ordering.String.reverse
val ord = Ordering[(String, Int)]
but it doesn’t solve my actual problem (where instead of String
I have a type argument A
). I can make it work by replacing [A: Ordering]
with (using ordA: Ordering[A])
in my signature (so I can get to ordA
without a summon
). All in all, probably not worth it.
I was going to say just the same thing.
scala> locally:
| given Ordering[String] = Ordering.String.reverse
| Ordering[(String,Int)].compare("A"->42, "B"->27)
|
val res0: Int = 1
More generally
scala> extension (x: Ordering.type) def derived[A: Ordering, B: Ordering]: Ordering[(A, B)] = Ordering.Tuple2(Ordering[A].reverse, Ordering[B])
def derived(x: Ordering.type)[A, B](implicit evidence$1: Ordering[A], evidence$2: Ordering[B]): Ordering[(A, B)]
scala> Ordering.derived[String, Int]
val res0: Ordering[(String, Int)] = scala.math.Ordering$Tuple2Ordering@6b747d38
scala> type P = (String, Int); def cmp(p: P, q: P)(using ord: Ordering[P]) = ord.compare(p, q)
// defined alias type P = (String, Int)
def cmp(p: P, q: P)(using ord: Ordering[P]): Int
scala> cmp("a"->42, "b"->27)(using res0)
val res1: Int = 1
maybe add that it would be natural to define
opaque type RStr = String
to make Ordering[(RStr, Int)]
distinct. I’m not sure about the ergonomics of entering bizarro world to do the comparison, that is, obtain an RStr
which is a string that sorts backward.