The Order
typeclass abstracts the ability to compare two instances of any object and determine their total order.
Depending on your needs, this comparison can be structural (the content of the object), referential (the memory address of the object), based on an identity (like an Id field), or any combination of these.
It can be considered the typeclass equivalent of Java’s Comparable
.
fun F.compare(b: F): Ordering
import arrow.*
import arrow.typeclasses.*
import arrow.core.extensions.*
Int.order().run { 1.compare(2) }
// LT
Additionally, Order
overloads operators >
, <
, <=
, and >=
, following the Kotlin compareTo
convention for every type where an Order
instance exists.
Int.order().run { 1 > 2 }
// false
Lesser than or equal to defines total order in a set, it compares two elements, and returns true if they’re equal or the first is lesser than the second.
It is the opposite of gte
.
Int.order().run {
1.lte(2)
}
// true
Greater than or equal compares two elements and returns true if they’re equal or the first is lesser than the second.
It is the opposite of lte
.
Int.order().run {
1.gte(2)
}
// false
Compares two elements and respectively returns the maximum or minimum in respect to their order.
Int.order().run {
1.min(2)
}
// 1
Int.order().run {
1.max(2)
}
// 2
Sorts the elements in a Tuple2
.
Int.order().run {
1.sort(2)
}
// (2, 1)
Arrow provides OrderLaws
in the form of test cases for internal verification of lawful instances and third party apps creating their own Order
instances.
Order
instancesOrder has a constructor to create an Order
instance from a compare function (F, F) -> Ordering
.
import arrow.core.Ordering
Order { a: Int, b: Int -> Ordering.fromInt(b - a) }.run {
1.lt(2)
}
// false
See Deriving and creating custom typeclass to provide your own Order
instances for custom datatypes.
Do you like Arrow?
✖