Name probably can be improved (fromListGroupedBy?), implementation needs to be improved for sure - I and will be happy to work on it if feature looks useful for someone. Basically idea is following:
def fromListGroupBy[A, K](as: List[A], f: A => K): Map[K, NonEmptyList[A]] =
as.groupBy(f).map { case (k, list) => list match {
case h :: t => (k, NonEmptyList(h, t)).some
case Nil => none
}}.toList.sequence.map(_.toMap).getOrElse(Map.empty)
We always know that if List[A] is not empty then values in Map will be NonEmptyList.
This also can be implemented along with https://github.com/typelevel/cats/pull/2141 as there's clear connection between two structures.
That function already exists here: https://github.com/typelevel/cats/blob/master/core/src/main/scala/cats/syntax/list.scala
:)
Ah, thank you very much, @LukaJCB. I was looking in NonEmptyList. Closing.
...and even in 0.9.0. SIgh.
groupByNel needs an Order implementation and returns a SortedMap. Would be been really nice if we also had the above version which doesn't need all that.
Most helpful comment
groupByNelneeds anOrderimplementation and returns aSortedMap. Would be been really nice if we also had the above version which doesn't need all that.