bluenote10
bluenote10

Reputation: 26729

How do I initialize a generic variable with its min/max possible value (numeric limits)?

How can I initialize a variable in a generic function with the min/max possible value of underlying generic type? I'm looking for Nim's equivalent of C++'s std::numeric_limits.

Upvotes: 3

Views: 406

Answers (1)

bluenote10
bluenote10

Reputation: 26729

Nim does not require a special module for that. The general pattern is to use low(T) or high(T) to get the min/max possible value of type T. The functions are overloaded for all integer types by default. It can be extended easily to float types or any other type by implementing low and high for them. For instance the following code would work for any standard number type:

import typetraits # only required for priting the type name

proc high(T: typedesc[SomeReal]): T = Inf
proc low(T: typedesc[SomeReal]): T = NegInf

proc requiresNumericLimits[T]() =
  let minPossible = low(T)
  let maxPossible = high(T)
  echo "Min of type ", name(T), ": ", minPossible
  echo "Max of type ", name(T), ": ", maxPossible

requiresNumericLimits[int]()
requiresNumericLimits[int16]()
requiresNumericLimits[uint16]()
requiresNumericLimits[float32]()
requiresNumericLimits[float64]()

Output:

Min of type int: -9223372036854775808
Max of type int: 9223372036854775807
Min of type int16: -32768
Max of type int16: 32767
Min of type uint16: 0
Max of type uint16: 65535
Min of type float32: -inf
Max of type float32: inf
Min of type float64: -inf
Max of type float64: inf

Upvotes: 4

Related Questions