【问题标题】:Why `Numeric` in the Scala standard library does not have a `maxValue`?为什么 Scala 标准库中的“Numeric”没有“maxValue”?
【发布时间】:2016-03-19 03:35:12
【问题描述】:

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[BigDecimal]MaxValue 会是什么?
  • BigDecimal 与这个想法有何矛盾?
  • 数字的每个“类型”都有不同的限制...

标签: scala max standard-library


【解决方案1】:

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

也就是说,你可以说,“为什么没有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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    • 2011-03-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多