Typeclasses in Haskell v. Scala

Given the following implementations of f in Haskell and Scala:

 Prelude> let fxy = x == y Prelude> :tf f :: Eq a => a -> a -> Bool 

Scala:

 scala> trait Equal[A] { def ===(x: A, y: A): Boolean } defined trait Equal scala> implicit val equalsInt = new Equal[Int] { | def ===(x: Int, y: Int):Boolean = (x == y) | } equalsInt: Equal[Int] = $anon$1@3daa422a scala> def f[A : Equal](x: A, y: A): Boolean = | implicitly[Equal[A]].===(x, y) f: [A](x: A, y: A)(implicit evidence$1: Equal[A])Boolean scala> f(10, 20) res0: Boolean = false scala> f(55, 55) res1: Boolean = true 

Watching this video, Typeclasses v. the World , my incomplete understanding is that Scala implicit resolution, that is, how it reaches type classes, is subject to incorrect / inconsistent resolution of implications. But Haskell does not use implicits for typeclasses, so there is no such problem in Haskell.

Given the differences between Scala and Haskell class implementations, what are the possible problems of the above definition of f in Scala that are not present in Haskell?

+6
source share
1 answer

One of the problems that the Scala version of Haskell may have is that in Scala you can define more than one Equal[Int] instance in scope when the implicit resolution mechanism tries to find the instance. This is when you can get an error, for example :

 <console>:12: error: ambiguous implicit values: both value EqualInt1 of type => Equal[Int] and value EqualInt2 of type => Equal[Int] match expected type Equal[Int] f(1, 2) ^ 

Update As Carl observes in a comment, another problem is that you can have different instances in scope at different points in the code, so calling f can use these different instances with very different results and without compilation or error execution time.

+5
source

All Articles