Last active
March 30, 2016 18:23
-
-
Save yawaramin/ad75ebb105b379dff1d11d6b3051054a to your computer and use it in GitHub Desktop.
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
/* | |
Low-priority implicits | |
Thanks to | |
http://www.slideshare.net/NLJUG/scala-design-patterns-age-mooij for | |
pointing me in the right direction | |
*/ | |
trait Ord[A] { | |
/** Returns a1 <= a2 */ | |
def lteq(a1: A, a2: A): Boolean | |
} | |
object Ord { | |
def apply[A](implicit ordA: Ord[A]): Ord[A] = ordA | |
implicit val intOrd: Ord[Int] = | |
new Ord[Int] { | |
override def lteq(i1: Int, i2: Int): Boolean = i1 <= i2 | |
} | |
implicit val doubleOrd: Ord[Double] = | |
new Ord[Double] { | |
override def lteq(d1: Double, d2: Double): Boolean = d1 <= d2 | |
} | |
} | |
trait Eq[A] { | |
def equal(a1: A, a2: A): Boolean | |
} | |
/** | |
Low-priority implicit so that implicits defined in companion objects of | |
Eq or A are picked first! | |
*/ | |
trait Ord2Eq { | |
/** We kow how to compare two As for equality if we can order them. */ | |
implicit def ord2Eq[A: Ord]: Eq[A] = | |
new Eq[A] { | |
override def equal(a1: A, a2: A): Boolean = { | |
val ordA = Ord[A] | |
ordA.lteq(a1, a2) && ordA.lteq(a2, a1) | |
} | |
} | |
} | |
object Eq extends Ord2Eq { | |
def apply[A](implicit eqA: Eq[A]): Eq[A] = eqA | |
implicit val eqDouble: Eq[Double] = | |
new Eq[Double] { | |
// Wrong implementation for testing | |
override def equal(d1: Double, d2: Double): Boolean = d1 != d2 | |
} | |
} | |
/* | |
Usage: | |
Eq[Int].equal(1, 1) // -> true | |
Eq[Int].equal(1, 2) // -> false | |
This proves we're finding an Eq[Int] typeclass instance in the Eq | |
companion object's inheritance hierarchy! | |
Eq[Double].equal(1.0, 2.0) // -> true | |
Eq[Double].equal(1.0, 1.0) // -> false | |
This proves our faulty Eq[Double] typeclass instance in the companion | |
object is given higher priority, even though a correct implementation | |
can be found in the inheritance hierarchy! | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment