1

So I have a polymorphic data type Tree in scala defined as follows

sealed trait Tree[+A] final case class Node[A](value: A) extends Tree[A] final case class Branch[A](value: A, left: Tree[A], right: Tree[A]) extends Tree[A] object Tree{ implicit def eqTree[T]: Eq[Tree[T]] = new Eq[Tree[T]] { override def ==(t1: Tree[T], t2: Tree[T]): Boolean = true } } 

And a type class Eq

trait Eq[T]{ def == (t1: T, t2: T) : Boolean } 

And I am trying to do

object App1 extends App{ import Tree._ def equality[T](t1: T, t2: T)(implicit eq: Eq[T]): Boolean = eq.==(t1, t2) println(equality(Node(1), Node(2))) } 

However I get the following error

Error:(35, 19) could not find implicit value for parameter eq: typeclasses.Eq[typeclasses.Node[Int]] println(equality(Node(1), Node(2))) 
1
  • Where are T1 and T2 declared? Commented Nov 20, 2016 at 17:44

1 Answer 1

4

As the error says, compiler is trying to find Eq[Node[Int]], and there is no such value in scope. You have defined Eq[Tree[T]].

So basically this is what compiler sees:

equality[Node[Int]](Node(1), Node(2)) 

But you actually want this:

println(equality[Tree[Int]](Node(1), Node(2))) 
Sign up to request clarification or add additional context in comments.

8 Comments

Not saying that your observation is wrong, but I don't think his code as is would even compile. notice T1 and T2.
Another thing to consider is ==, which is already defined for every object. (Defined is not a good word here, since it's just syntax sugar from == to equals)
I am just trying to see if I can get haskell's equivalent of typeclasses working in scala. I know I can use ==
@pedrofula This is pretty ugly but anyway == with 2 parameters isn't defined for every object, and hence everything works. I also asumed that it is just a typo and both T1 and T2 should have been simply T. @Abdul Rahman take a look at simulacrum library that can reduce the pain.
@AbdulRahman In this case you can just do the usual thing: either define Eq to be contravariant trait Eq1[-T], or define Eq instances for subclasses: implicit def eqTree[T, U](implicit ev: U <:< Tree[T]): Eq[U] = new Eq[U] { override def ==(t1: U, t2: U): Boolean = true }
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.