Skip to content

Commit

Permalink
Have List.groupByNel return a SortedMap as well
Browse files Browse the repository at this point in the history
  • Loading branch information
igstan committed Oct 12, 2017
1 parent cace36c commit 2f0a165
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
3 changes: 1 addition & 2 deletions core/src/main/scala/cats/NonEmptyTraverse.scala
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,8 @@ import simulacrum.typeclass
* {{{
* scala> import cats.implicits._
* scala> import cats.data.NonEmptyList
* scala> def countWords(words: List[String]): Map[String, Int] = words.groupBy(identity).mapValues(_.length)
* scala> val x = NonEmptyList.of(List("How", "do", "you", "fly"), List("What", "do", "you", "do"))
* scala> x.nonEmptyFlatTraverse(_.groupByNel(identity))
* scala> x.nonEmptyFlatTraverse(_.groupByNel(identity) : Map[String, NonEmptyList[String]])
* res0: Map[String,cats.data.NonEmptyList[String]] = Map(do -> NonEmptyList(do, do, do), you -> NonEmptyList(you, you))
* }}}
*/
Expand Down
7 changes: 5 additions & 2 deletions core/src/main/scala/cats/syntax/list.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cats
package syntax

import scala.collection.immutable.SortedMap
import cats.data.NonEmptyList

trait ListSyntax {
Expand All @@ -27,6 +28,8 @@ final class ListOps[A](val la: List[A]) extends AnyVal {
* }}}
*/
def toNel: Option[NonEmptyList[A]] = NonEmptyList.fromList(la)
def groupByNel[B : Order](f: A => B): Map[B, NonEmptyList[A]] =
toNel.fold(Map.empty[B, NonEmptyList[A]])(_.groupBy(f))
def groupByNel[B](f: A => B)(implicit B: Order[B]): SortedMap[B, NonEmptyList[A]] = {
implicit val ordering = B.toOrdering
toNel.fold(SortedMap.empty[B, NonEmptyList[A]])(_.groupBy(f))
}
}

0 comments on commit 2f0a165

Please sign in to comment.