Skip to content

Commit

Permalink
Add Order#fromLessThan (#2477)
Browse files Browse the repository at this point in the history
  • Loading branch information
vlovgr authored and Luka Jacobowitz committed Sep 12, 2018
1 parent cd3f659 commit f44eb11
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
1 change: 1 addition & 0 deletions kernel-laws/src/test/scala/cats/kernel/laws/LawTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ class Tests extends FunSuite with Discipline {
checkAll("fromOrdering[Int]", OrderTests(Order.fromOrdering[Int]).order)
checkAll("Order.reverse(Order[Int])", OrderTests(Order.reverse(Order[Int])).order)
checkAll("Order.reverse(Order.reverse(Order[Int]))", OrderTests(Order.reverse(Order.reverse(Order[Int]))).order)
checkAll("Order.fromLessThan[Int](_ < _)", OrderTests(Order.fromLessThan[Int](_ < _)).order)

checkAll("Monoid[String]", MonoidTests[String].monoid)
checkAll("Monoid[String]", SerializableTests.serializable(Monoid[String]))
Expand Down
17 changes: 17 additions & 0 deletions kernel/src/main/scala/cats/kernel/Order.scala
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,23 @@ object Order extends OrderFunctions[Order] with OrderToOrderingConversion {
def compare(x: A, y: A) = f(x, y)
}

/**
* Define an `Order[A]` using the given 'less than' function `f`.
*/
def fromLessThan[@sp A](f: (A, A) => Boolean): Order[A] =
new Order[A] {
override def compare(x: A, y: A): Int =
if (f(x, y)) -1 else if (f(y, x)) 1 else 0

// Overridden for performance (avoids multiple comparisons)
override def eqv(x: A, y: A): Boolean = !(f(x, y) || f(y, x))
override def neqv(x: A, y: A): Boolean = f(x, y) || f(y, x)
override def lteqv(x: A, y: A): Boolean = !f(y, x)
override def lt(x: A, y: A): Boolean = f(x, y)
override def gteqv(x: A, y: A): Boolean = !f(x, y)
override def gt(x: A, y: A): Boolean = f(y, x)
}

/**
* An `Order` instance that considers all `A` instances to be equal.
*/
Expand Down

0 comments on commit f44eb11

Please sign in to comment.