Skip to content

Instantly share code, notes, and snippets.

@kubukoz
Last active July 12, 2017 16:36
Show Gist options
  • Save kubukoz/3fc5340c987bbed3997786a88620ca6a to your computer and use it in GitHub Desktop.
Save kubukoz/3fc5340c987bbed3997786a88620ca6a to your computer and use it in GitHub Desktop.
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