Skip to content

Commit cace36c

Browse files
committed
Have NonEmptyList.groupBy return a SortedMap instead of just a Map
1 parent 9f116d6 commit cace36c

1 file changed

Lines changed: 11 additions & 7 deletions

File tree

core/src/main/scala/cats/data/NonEmptyList.scala

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,8 @@ package data
33

44
import cats.instances.list._
55
import cats.syntax.order._
6-
76
import scala.annotation.tailrec
8-
import scala.collection.immutable.{ TreeMap, TreeSet }
7+
import scala.collection.immutable.{ SortedMap, TreeMap, TreeSet }
98
import scala.collection.mutable
109
import scala.collection.mutable.ListBuffer
1110

@@ -321,18 +320,21 @@ final case class NonEmptyList[+A](head: A, tail: List[A]) {
321320
}
322321

323322
/**
324-
* Groups elements inside of this `NonEmptyList` using a mapping function
323+
* Groups elements inside this `NonEmptyList` according to the `Order`
324+
* of the keys produced by the given mapping function.
325325
*
326326
* {{{
327+
* scala> import scala.collection.immutable.SortedMap
327328
* scala> import cats.data.NonEmptyList
328329
* scala> import cats.instances.boolean._
329330
* scala> val nel = NonEmptyList.of(12, -2, 3, -5)
330331
* scala> nel.groupBy(_ >= 0)
331-
* res0: Map[Boolean, cats.data.NonEmptyList[Int]] = Map(false -> NonEmptyList(-2, -5), true -> NonEmptyList(12, 3))
332+
* res0: SortedMap[Boolean, cats.data.NonEmptyList[Int]] = Map(false -> NonEmptyList(-2, -5), true -> NonEmptyList(12, 3))
332333
* }}}
333334
*/
334-
def groupBy[B](f: A => B)(implicit B: Order[B]): Map[B, NonEmptyList[A]] = {
335-
var m = TreeMap.empty[B, mutable.Builder[A, List[A]]](B.toOrdering)
335+
def groupBy[B](f: A => B)(implicit B: Order[B]): SortedMap[B, NonEmptyList[A]] = {
336+
implicit val ordering: Ordering[B] = B.toOrdering
337+
var m = TreeMap.empty[B, mutable.Builder[A, List[A]]]
336338

337339
for { elem <- toList } {
338340
val k = f(elem)
@@ -343,7 +345,9 @@ final case class NonEmptyList[+A](head: A, tail: List[A]) {
343345
}
344346
}
345347

346-
m.map { case (k, v) => (k, NonEmptyList.fromListUnsafe(v.result)) }
348+
m.map {
349+
case (k, v) => (k, NonEmptyList.fromListUnsafe(v.result))
350+
} : TreeMap[B, NonEmptyList[A]]
347351
}
348352
}
349353

0 commit comments

Comments
 (0)