jed*_*sah 2 scala standard-library
有没有一个很好的理由为什么NumericScala标准库中没有maxValue和minValue函数.它似乎相当有用,甚至在某些情况下使用它也是必要的.
例如,一个人可能能够定义像这样的scalacheck生成器:
def arbNumeric[T:Choose](implicit num: Numeric[T): Arbitrary[T] = {
Arbitrary(Gen.chooseNum(num.MinValue, num.MaxValue))
}
Run Code Online (Sandbox Code Playgroud)
而不是必须为每个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))
}
...
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
这基本上与使用相同的模式,Numeric除了你需要A: Numeric : MaximalValue而不仅仅是A: Numeric.
| 归档时间: |
|
| 查看次数: |
250 次 |
| 最近记录: |