Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Order#fromLessThan #2477

Merged
merged 1 commit into from
Sep 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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