scala - 与 Scala 的数字类型进行比较?

标签 scala math numeric

如何创建一个做数学的类 Scala 中任何数字类型的比较?

一种明显的方法:

import math.Numeric.Implicits._

class Ops[T : Numeric] {
    def add(a: T, b: T) = a + b
    def gt(a: T, b: T) = a > b
}

赚我这个...
Ops.scala:7: value > is not a member of type parameter T

嗯...我们可以用数字类型做数学,但我们不能比较它们?

所以我们也说 TOrdered[T] ...
class Ops[T <: Ordered[T] : Numeric] {
    def add(a: T, b: T) = a + b
    def gt(a: T, b: T) = a > b
}

这样编译。但是尝试使用它?
new Ops[Int].gt(1, 2)

我得到...
Ops.scala:13: type arguments [Int] do not conform to class Ops's type parameter bounds [T <: Ordered[T]]

那么如何对某种既有序又数字的类型进行操作呢?

最佳答案

scala> import Ordering.Implicits._
import Ordering.Implicits._

scala> import Numeric.Implicits._
import Numeric.Implicits._

scala> class Ops[T : Numeric] {
     |   def add(a: T, b: T) = a + b
     |   def gt(a: T, b: T) = a > b
     | }
defined class Ops

scala> new Ops[Int].gt(12, 34)
res302: Boolean = false

关于scala - 与 Scala 的数字类型进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8169333/

相关文章:

python - 周期性高斯的实现

python - 使用 Python 在 Kivy 中输入数字

scala - 通过python脚本在命令行中执行sbt并输出到文件

Ada 中的 double ?

java - 斯卡拉 : function to measure the runtime of any other function

algorithm - 如何分离多项式的根

math - 防止TI BASIC表达式扩展

javascript - 从数组中的所有 javascript 对象添加特定属性的值

class - 带有父类(super class)的案例类副本 'method'

scala - Cassandra (CQL) 使用 Cassandra4IO 选择 IN 查询