Skip to content

Commit

Permalink
Require and Order instance for NonEmptyList's groupBy function
Browse files Browse the repository at this point in the history
This addresses: typelevel#1959
  • Loading branch information
igstan committed Oct 11, 2017
1 parent 523ac99 commit 2516f36
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 3 deletions.
5 changes: 3 additions & 2 deletions core/src/main/scala/cats/data/NonEmptyList.scala
Original file line number Diff line number Diff line change
Expand Up @@ -325,13 +325,14 @@ final case class NonEmptyList[+A](head: A, tail: List[A]) {
*
* {{{
* scala> import cats.data.NonEmptyList
* scala> import cats.instances.boolean._
* scala> val nel = NonEmptyList.of(12, -2, 3, -5)
* scala> nel.groupBy(_ >= 0)
* res0: Map[Boolean, cats.data.NonEmptyList[Int]] = Map(false -> NonEmptyList(-2, -5), true -> NonEmptyList(12, 3))
* }}}
*/
def groupBy[B](f: A => B): Map[B, NonEmptyList[A]] = {
val m = mutable.Map.empty[B, mutable.Builder[A, List[A]]]
def groupBy[B](f: A => B)(implicit B: Order[B]): Map[B, NonEmptyList[A]] = {
val m = mutable.TreeMap.empty[B, mutable.Builder[A, List[A]]](B.toOrdering)
for { elem <- toList } {
m.getOrElseUpdate(f(elem), List.newBuilder[A]) += elem
}
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/scala/cats/syntax/list.scala
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,6 @@ final class ListOps[A](val la: List[A]) extends AnyVal {
* }}}
*/
def toNel: Option[NonEmptyList[A]] = NonEmptyList.fromList(la)
def groupByNel[B](f: A => B): Map[B, NonEmptyList[A]] =
def groupByNel[B : Order](f: A => B): Map[B, NonEmptyList[A]] =
toNel.fold(Map.empty[B, NonEmptyList[A]])(_.groupBy(f))
}

0 comments on commit 2516f36

Please sign in to comment.