Skip to content

Commit

Permalink
Require an 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 685e949
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 6 deletions.
10 changes: 5 additions & 5 deletions core/src/main/scala/cats/data/NonEmptyList.scala
Original file line number Diff line number Diff line change
Expand Up @@ -325,20 +325,20 @@ 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
}
val b = immutable.Map.newBuilder[B, NonEmptyList[A]]
val b = immutable.TreeMap.newBuilder[B, NonEmptyList[A]](B.toOrdering)
for { (k, v) <- m } {
val head :: tail = v.result // we only create non empty list inside of the map `m`
b += ((k, NonEmptyList(head, tail)))
b += k -> NonEmptyList.fromListUnsafe(v.result)
}
b.result
}
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 685e949

Please sign in to comment.