jedesah
jedesah

Reputation: 3033

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

Is there a good reason why Numeric in the Scala standard library does not have a maxValue and minValue function. It seems rather useful, even necessary to use it in certain contexts.

For instance, one might be able to define a scalacheck generator like such:

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

as opposed to having to write out the same thing for each Int, Long, etc:

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))
}
...

Upvotes: 2

Views: 386

Answers (1)

Rex Kerr
Rex Kerr

Reputation: 167891

Numeric is intended to be general. There are reasons why a maximum value may not exist: the number may be arbitrarily large (e.g. BigInt) and even if there is a practical limit you probably don't want your machine grinding to a halt as it tries to represent it; the maximum value may not actually be in the range of the number (e.g. the half-open interval [0, 1)); or you may have a number type for which a maximum doesn't exist (e.g. Complex) but for which the other operations can make enough sense to want to implement.

That said, one can just say, "why isn't there a maxValueOption", to which the answer is: nobody needed it at the time.

You can create your own MaximalValue typeclass if you don't want to repeat the same selection of maximum values over and over.

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

This is essentially the same pattern as using Numeric except you'd need A: Numeric : MaximalValue instead of just A: Numeric.

Upvotes: 10

Related Questions