Bounded
Bounded is a type class that defines the minimum and maximum values for a specific type.
It provides methods for obtaining these bounds, enabling work with types that have a limited range of values.
Bounded is used in various scenarios where knowing the bounds of a type's values is important. Here are some examples:
- Working with numbers:
Boundedcan be used to define the minimum and maximum values of numeric types such asInt,Long, and others. - Characters: For the
Chartype, you can define the minimum and maximum values, such as the minimum and maximum characters in the Unicode table. - Custom types: If you have a custom data type,
you can implement a
Boundedinstance for it to define its bounds. - Algorithms: In algorithms that work with limited value ranges,
Boundedcan be used for boundary checking.
Formal definition
Bounded is a type class extending Order
that defines the minimum and maximum values for a specific type.
Bounded provides methods for obtaining these bounds (min and max),
enabling work with types that have a limited range of values.
Laws
For a correct implementation of Bounded, the following laws must hold:
- Minimum value: For any value
xof typeA,xmust be greater than or equal tomin(x >= min). - Maximum value: For any value
xof typeA,xmust be less than or equal tomax(x <= max).
Code definition in Scala
trait Equal[F]:
def equal(a1: F, a2: F): Boolean
enum Ordering:
case LT
case EQ
case GT
trait Order[F] extends Equal[F]:
def order(x: F, y: F): Ordering
trait Bounded[F] extends Order[F]:
def min: F
def max: F
- Type parameter
F:Boundedis parameterized by typeFfor which bounds are defined. minmethod: Returns the minimum value of typeF.maxmethod: Returns the maximum value of typeF.
Diagram
classDiagram
class Equal~A~{
+equal(x: A, y: A) Boolean
}
class Ordering{
<<enumeration>>
LT
EQ
GT
}
class Order~A~{
+order(x: A, y: A) Ordering
}
Ordering .. Order
Equal <|-- Order
class Bounded~A~{
+min: A
+max: A
}
Order <|-- Bounded
References: