Skip to content

Commit

Permalink
Merge pull request #2225 from ceedubs/groupByNel-example
Browse files Browse the repository at this point in the history
Add doctest example for groupByNel
  • Loading branch information
johnynek authored Apr 12, 2018
2 parents 3ac3ba1 + 81c5c50 commit f19221e
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions core/src/main/scala/cats/syntax/list.scala
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,22 @@ final class ListOps[A](val la: List[A]) extends AnyVal {
* }}}
*/
def toNel: Option[NonEmptyList[A]] = NonEmptyList.fromList(la)

/**
* Groups elements inside this `List` according to the `Order` of the keys
* produced by the given mapping function.
*
* {{{
* scala> import cats.data.NonEmptyList
* scala> import scala.collection.immutable.SortedMap
* scala> import cats.implicits._
*
* scala> val list = List(12, -2, 3, -5)
*
* scala> list.groupByNel(_ >= 0)
* res0: SortedMap[Boolean, NonEmptyList[Int]] = Map(false -> NonEmptyList(-2, -5), true -> NonEmptyList(12, 3))
* }}}
*/
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))
Expand Down

0 comments on commit f19221e

Please sign in to comment.