如何比较使用Scalatest Equality类型的Double列表?

时间:2015-04-28 05:21:30

标签: scala scalatest

这是我迄今为止所做的尝试:

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
    }
  }
}

第一个断言成功但第二个断言失败:

assert(1.0 === 1.01)

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

有没有办法让集合使用我为其元素定义的含义?

2 个答案:

答案 0 :(得分:1)

就我而言,我重新定义了areEqual方法,提供new Equality[List[Double]]这是Equivalence[List[Double]]的子类,考虑到areEqualAny作为第二个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 } } } 类型参数。

$('#val1').val()

答案 1 :(得分:1)

Equality类仅在导入TypeCheckedTripleEquals时使用:

  

提供返回Boolean的===和!==运算符,将相等性确定委托给Equality类型类,并要求比较两个值的类型为子类型/超类型关系。

这是我用来解决这个问题的基础测试类:

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
      }
    }
  }
}