Skip to content

Instantly share code, notes, and snippets.

@sshark
Created June 16, 2026 16:03
Show Gist options
  • Select an option

  • Save sshark/423eb8944ef6097de70872f1512015a9 to your computer and use it in GitHub Desktop.

Select an option

Save sshark/423eb8944ef6097de70872f1512015a9 to your computer and use it in GitHub Desktop.
An Eq typeclass implementation for the type constructor and type i.e. Int and List[_]
trait Eq[A] {
def eqv(lhs: A, rhs: A): Boolean
def neq(lhs: A, rhs: A): Boolean = !eqv(lhs, rhs)
extension (lhs: A) {
def ===(rhs: A): Boolean = eqv(lhs, rhs)
def !==(rhs: A): Boolean = neq(lhs, rhs)
}
}
object EqualForInt {
given Eq[Int] with {
override def eqv(lhs: Int, rhs: Int): Boolean = lhs == rhs
}
}
object EqualForList {
given [A: Eq as ev]: Eq[List[A]] with {
def eqv(lhs: List[A], rhs: List[A]): Boolean =
if lhs.length != rhs.length then false
else lhs.zip(rhs).forall(ev.eqv(_, _))
}
}
import EqualForList.given
import EqualForInt.given
val xs = List(1, 2, 3)
val ys = List(1, 2, 3)
val zs = List(1, 2, 4)
assert(3 === 3)
assert(xs === ys)
assert(xs !== zs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment