Skip to content

Instantly share code, notes, and snippets.

@kubukoz
Last active Jul 12, 2017
Embed
What would you like to do?
A `groupBy` implementation in which the result's values are guaranteed not to be empty on the type level.
import scalaz.{Foldable, NonEmptyList}
import scalaz.syntax.foldable._
implicit class GroupToNel[F[_] : Foldable, T](foldable: F[T]){
def groupToNel[K](fun: T => K): Map[K, NonEmptyList[T]] = {
f.foldLeft(Map.empty[K, NonEmptyList[T]]) { (map, elem) =>
val funOfElem = fun(elem)
val newValue = map.get(funOfElem).fold(NonEmptyList(elem))(list => elem <:: list)
map + (funOfElem -> newValue)
}
}
}
//scala> List(1,2,3,4).groupToNel(_ % 2)
//res0: Map[Int,scalaz.NonEmptyList[Int]] = Map(1 -> NonEmptyList(3, 1), 0 -> NonEmptyList(4, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment