Skip to content

Instantly share code, notes, and snippets.

@joost-de-vries
Created September 30, 2015 06:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joost-de-vries/949fbea6345fec1ac4ef to your computer and use it in GitHub Desktop.
Save joost-de-vries/949fbea6345fec1ac4ef to your computer and use it in GitHub Desktop.

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

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment