Skip to content

Commit

Permalink
update comment for unreachable code and optimise sorted
Browse files Browse the repository at this point in the history
  • Loading branch information
julien-truffaut committed Mar 30, 2017
1 parent 22fd6b0 commit 4709187
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
10 changes: 6 additions & 4 deletions core/src/main/scala/cats/data/NonEmptyList.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand All @@ -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
Expand Down
6 changes: 6 additions & 0 deletions tests/src/test/scala/cats/tests/NonEmptyListTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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) =>
Expand Down

0 comments on commit 4709187

Please sign in to comment.