Cats: Add NonEmptyList.fromListGroupBy

Created on 19 Jan 2018  路  4Comments  路  Source: typelevel/cats

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.

Most helpful comment

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.

All 4 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

SimY4 picture SimY4  路  4Comments

kailuowang picture kailuowang  路  5Comments

davidabrahams picture davidabrahams  路  3Comments

durban picture durban  路  3Comments

tg44 picture tg44  路  4Comments