Last active
February 2, 2019 14:30
-
-
Save kmizu/caa1f691cb5ee52b4eae5e24fc4b01a7 to your computer and use it in GitHub Desktop.
Write instances of Ordering[T] manually
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sealed abstract class T1 | |
object T1 { | |
case class A(x: Int) extends T1 | |
case class B(x: Double) extends T1 | |
case class C(x: String) extends T1 | |
implicit val ordA: Ordering[A] = (a, b) => a.x compare b.x | |
implicit val ordB: Ordering[B] = (a, b) => a.x compare b.x | |
implicit val ordC: Ordering[C] = (a, b) => a.x compare b.x | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sealed abstract class T2(val code: Int) | |
object T2 { | |
case class A(x: Int) extends T2(0) | |
case class B(x: Double) extends T2(1) | |
case class C(x: String) extends T2(2) | |
implicit def ordT2: Ordering[T2] = (t1, t2) => t1.code compare t2.code | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sealed abstract class T3 | |
object T3 { | |
case class A(x: Int) extends T3 | |
case class B(x: Double) extends T3 | |
case class C(x: String) extends T3 | |
implicit val ordT3: Ordering[T3] = (a, b) => (a, b) match { | |
case (a1@A(_), a2@A(_)) => ordA.compare(a1, a2) | |
case (b1@B(_), b2@B(_)) => ordB.compare(b1, b2) | |
case (c1@C(_), c2@C(_)) => ordC.compare(c1, c2) | |
} | |
implicit val ordA: Ordering[A] = (a, b) => a.x compare b.x | |
implicit val ordB: Ordering[B] = (a, b) => a.x compare b.x | |
implicit val ordC: Ordering[C] = (a, b) => a.x compare b.x | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment