From 4709187f0ab17a60b2b2a35390f2d659dd2304cc Mon Sep 17 00:00:00 2001 From: Julien Truffaut Date: Tue, 28 Mar 2017 09:29:37 +0100 Subject: [PATCH] update comment for unreachable code and optimise sorted --- core/src/main/scala/cats/data/NonEmptyList.scala | 10 ++++++---- .../src/test/scala/cats/tests/NonEmptyListTests.scala | 6 ++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/core/src/main/scala/cats/data/NonEmptyList.scala b/core/src/main/scala/cats/data/NonEmptyList.scala index b297b75a1a..0bfcd50010 100644 --- a/core/src/main/scala/cats/data/NonEmptyList.scala +++ b/core/src/main/scala/cats/data/NonEmptyList.scala @@ -231,12 +231,11 @@ final case class NonEmptyList[+A](head: A, tail: List[A]) { * res0: cats.data.NonEmptyList[(Char, Int)] = NonEmptyList((z,1), (a,4), (e,22)) * }}} */ - def sortBy[B: Order](f: A => B): NonEmptyList[A] = { + def sortBy[B: Order](f: A => B): NonEmptyList[A] = toList.sortBy(f)(Order[B].toOrdering) match { case x :: xs => NonEmptyList(x, xs) - case Nil => sys.error("absurd") + case Nil => sys.error("unreachable: sorting a NonEmptyList cannot produce an empty List") } - } /** * Sorts this `NonEmptyList` according to an `Order` @@ -250,7 +249,10 @@ final case class NonEmptyList[+A](head: A, tail: List[A]) { * }}} */ def sorted[AA >: A](implicit AA: Order[AA]): NonEmptyList[AA] = - sortBy(a => a: AA) + toList.sorted(Order[AA].toOrdering) match { + case x :: xs => NonEmptyList(x, xs) + case Nil => sys.error("unreachable: sorting a NonEmptyList cannot produce an empty List") + } /** * Groups elements inside of this `NonEmptyList` using a mapping function diff --git a/tests/src/test/scala/cats/tests/NonEmptyListTests.scala b/tests/src/test/scala/cats/tests/NonEmptyListTests.scala index dd4cdffb6f..ede96b81df 100644 --- a/tests/src/test/scala/cats/tests/NonEmptyListTests.scala +++ b/tests/src/test/scala/cats/tests/NonEmptyListTests.scala @@ -244,6 +244,12 @@ class NonEmptyListTests extends CatsSuite { } } + test("NonEmptyList#sortBy is consistent with List#sortBy") { + forAll { (nel: NonEmptyList[Int], f: Int => Int) => + nel.sortBy(f).toList should === (nel.toList.sortBy(f)) + } + } + test("NonEmptyList#groupBy is consistent with List#groupBy") { forAll { (nel: NonEmptyList[Int], f: Int => Int) =>