如何在 Scala 中以数学方式比较两个未知类型?

Gre*_*reg 5 compare scala

我正在编写一个小脚本评估器函数。它需要两个参数和一个比较运算符,如下所示:

    def compare[T,U](a:T, op:String, b:U): Boolean = {
      op match {
        case "==" => a == b
        case "<"  => a < b
        // and so on with other comparators...
      }
    }
Run Code Online (Sandbox Code Playgroud)

这段代码无法编译。“<”运算符不适用于泛型类型。我找不到带有“<”运算符的数字类型的父类,所以我什至无法执行以下操作: def compare[T<:Numeric,U<:Numeric](...)

有没有办法做到这一点(或图书馆)?现在我只能测试等于/不等于。

Lui*_*rez 6

一般来说,每当您需要某种接口来对多种类型进行通用操作时,答案就是Typeclass
在这种特殊情况下,您可以使用scala.math.Ordering.

import scala.math.Ordering
import Ordering.Implicits._

def compare[T: Ordering](a: T, op: String, b: T): Boolean = op match {
  case "==" => a == b
  case "<"  => a < b
  // and so on with other comparators...
}
Run Code Online (Sandbox Code Playgroud)

现在你可以像这样使用它。

compare(10, "==", 15) //false
compare(10, "==", 10) // true
compare(10, "<", 10) // false
compare(10, "<", 11) // true
Run Code Online (Sandbox Code Playgroud)