The example of John de Goes' Haskell's Type Classes: We Can Do Better written in Scala.
It is precisely to allow for multiple type class implementations that Scala uses implicits to implement them. So I thought it would be interesting to compare Scala and Haskell here.
Discussion on HN
object MonoidInt{
implicit val MonoidPlus = new Monoid[Int] {
def empty = 0
def append(v1: Int, v2: Int) = v1 + v2
}
implicit val MonoidMult = new Monoid[Int] {
def empty = 1
def append(v1: Int, v2: Int) = v1 * v2
}
}
def empty[A: Monoid] = implicitly[Monoid[A]].empty
def append[A: Monoid](v1: A, v2: A) = implicitly[Monoid[A]].append(v1, v2)
{
import MonoidInt.MonoidMult
append(1, 2) // res0: Int = 2
}
{
import MonoidInt.MonoidPlus
append(1, 2) // res1: Int = 3
}