From 685e949545036bd67c936d930b268ce6dea7ba44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ionu=C8=9B=20G=2E=20Stan?= Date: Wed, 11 Oct 2017 19:31:06 +0300 Subject: [PATCH] Require an Order instance for NonEmptyList's groupBy function This addresses: #1959 --- core/src/main/scala/cats/data/NonEmptyList.scala | 10 +++++----- core/src/main/scala/cats/syntax/list.scala | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/core/src/main/scala/cats/data/NonEmptyList.scala b/core/src/main/scala/cats/data/NonEmptyList.scala index 875609c236..ee66a9e11f 100644 --- a/core/src/main/scala/cats/data/NonEmptyList.scala +++ b/core/src/main/scala/cats/data/NonEmptyList.scala @@ -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 } diff --git a/core/src/main/scala/cats/syntax/list.scala b/core/src/main/scala/cats/syntax/list.scala index d354eb7c7c..f8f21cf445 100644 --- a/core/src/main/scala/cats/syntax/list.scala +++ b/core/src/main/scala/cats/syntax/list.scala @@ -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)) }