How do I compare Double lists using the Scalatest Equality type?

Here's what I've tried so far:

implicit val doubleEq = TolerantNumerics.tolerantDoubleEquality(0.1)

implicit val listEq = new Equivalence[List[Double]] {
  override def areEquivalent(a: List[Double], b: List[Double]): Boolean = {
    (a, b) match {
      case (Nil, Nil) => true
      case (x :: xs, y :: ys) => x === y && areEquivalent(xs, ys)
      case _ => false
    }
  }
}

      

The first statement succeeds, but the second fails:

assert(1.0 === 1.01)

assert(List(1.0) === List(1.01))

      

Is there a way to use the collections I have defined for my elements?

+3


source to share


2 answers


Equality

classes are used only when importing TypeCheckedTripleEquals

:

Provides === and! == operators that return Boolean delegate the definition of equality to a class of type Equality and require two value types over a subtype / supertype relationship.



Here's the base test class I'm using to solve this problem:

import org.scalactic.{Equivalence, TolerantNumerics, TypeCheckedTripleEquals}
import org.scalatest.FunSuite

abstract class UnitSpec extends FunSuite with TypeCheckedTripleEquals {
  implicit val doubleEq = TolerantNumerics.tolerantDoubleEquality(0.001)

  implicit val listEq = new Equivalence[List[Double]] {
    override def areEquivalent(a: List[Double], b: List[Double]): Boolean = {
      (a, b) match {
        case (Nil, Nil) => true
        case (x :: xs, y :: ys) => x === y && areEquivalent(xs, ys)
        case _ => false
      }
    }
  }
}

      

+1


source


In my case, I have overridden: a areEqual

method by providing new Equality[List[Double]]

, which is a subclass Equivalence[List[Double]]

, assuming that it areEqual

takes Any

as the second type parameter.



implicit val listEq = new Equality[List[Double]] {
  def areEqual(a: List[Double], b: Any): Boolean = {
    def areEqualRec(a: List[Double], b: List[Double]): Boolean = {
      (a, b) match {
        case (Nil, Nil) => true
        case (x :: xs, y :: ys) => x === y && areEquivalent(xs, ys)
        case _ => false
      }
    }
    b match {
      case daList: List[Double] => areEqualRec(a, daList)
      case _ => false
    }
  }
}

      

+1


source







All Articles