This question is related to this one: is it possible to create a Set-like class (meaning that it's extending the Set
trait) in Scala where the equality used to define the containment relationship is defined by the user instead of being ==
?
One way to test if this really works is to check whether filter
returns the same collection type.
// typeclass for equality
trait Equals[T] {
def isEqual(t1: T, t2: T): Boolean
}
// an object representing plane coordinates
case class Coordinate(i: Int, j: Int)
// an equality saying that 2 coordinates are equal if they are on
// the same horizontal line
implicit def horizontalEquality: Equals[Coordinate] = new Equals[Coordinate] {
def isEqual(t1: Coordinate, t2: Coordinate) = t1.i == t2.i
}
// we create an EqualitySet[T] where T must verify [T : Equals]
val set = EqualitySet[Coordinate]()
// set2 must be of type EqualitySet[Coordinate]
val set2 = set.filter(_.i > 0)
We created this solution as a group in a Scala training with Miles Sabin (@milessabin).
Then, when we use the code above we get: