Last active
July 12, 2017 16:36
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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