【问题标题】:How to compare lists of Double using Scalatest Equality type?如何使用 Scalatest Equality 类型比较 Double 列表?
【发布时间】:2015-04-29 03:06:51
【问题描述】:

这是我迄今为止尝试过的:

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

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

【问题讨论】:

    标签: scala scalatest


    【解决方案1】:

    在我的例子中,我通过提供 new Equality[List[Double]] 重新定义了 areEqual 方法,它是 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
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      Equality 类仅在导入TypeCheckedTripleEquals 时使用:

      提供返回布尔值的 === 和 !== 运算符,将相等确定委托给 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
            }
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-16
        • 2014-06-28
        • 1970-01-01
        • 1970-01-01
        • 2021-03-16
        • 2021-12-22
        • 1970-01-01
        相关资源
        最近更新 更多