From 2516f369e814e67ac7a1c50fa7cd3e34504a26ed 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 and Order instance for NonEmptyList's groupBy function This addresses: #1959 --- core/src/main/scala/cats/data/NonEmptyList.scala | 5 +++-- core/src/main/scala/cats/syntax/list.scala | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/core/src/main/scala/cats/data/NonEmptyList.scala b/core/src/main/scala/cats/data/NonEmptyList.scala index 875609c2368..22a0910645e 100644 --- a/core/src/main/scala/cats/data/NonEmptyList.scala +++ b/core/src/main/scala/cats/data/NonEmptyList.scala @@ -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 } diff --git a/core/src/main/scala/cats/syntax/list.scala b/core/src/main/scala/cats/syntax/list.scala index d354eb7c7cd..f8f21cf445e 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)) }