为什么 Scala 标准库中的 Numeric 没有 maxValue?

Why `Numeric` in the Scala standard library does not have a `maxValue`?

为什么 Scala 标准库中的 Numeric 没有 maxValueminValue 函数是有充分理由的。它似乎很有用,甚至在某些情况下有必要使用它。

例如,可以像这样定义一个 scalacheck 生成器:

def arbNumeric[T:Choose](implicit num: Numeric[T): Arbitrary[T] = {
  Arbitrary(Gen.chooseNum(num.MinValue, num.MaxValue))
}

与必须为每个 Int、Long 等写出相同的东西相反:

val arbInt: Arbitrary[Int] = {
  Arbitrary(Gen.chooseNum(Int.MinValue, Int.MaxValue))
}
def arbLong: Arbitrary[Long] = {
  Arbitrary(Gen.chooseNum(Long.MinValue, Long.MaxValue))
}
def arbShort: Arbitrary[Short] = {
  Arbitrary(Gen.chooseNum(Short.MinValue, Short.MaxValue))
}
...

Numeric 旨在通用。最大值可能不存在的原因有:数字可能任意大(例如 BigInt),即使有实际限制,您可能也不希望机器在试图表示时停止运转它;最大值可能实际上不在数字范围内(例如半开区间[0, 1));或者您可能有一个数字类型,其最大值不存在(例如 Complex),但其他操作可能足够有意义以实现。

也就是说,可以说,"why isn't there a maxValueOption",答案是:当时没有人需要它。

如果您不想一遍又一遍地重复相同的最大值选择,您可以创建自己的 MaximalValue 类型类。

trait MaximalValue[A] { def value: A }
implicit val MaximalInt = new MaximalValue[Int] { def value = Int.MaxValue }
// Fill in others here

def biggest[A: MaximalValue] = implicitly[MaximalValue[A]].value

> biggest[Int]
res0: Int = 2147483647

这与使用 Numeric 的模式基本相同,只是您需要 A: Numeric : MaximalValue 而不是 A: Numeric.