Skip to content

Instantly share code, notes, and snippets.

@nuttycom
Created June 8, 2011 21:42
Show Gist options
  • Save nuttycom/1015486 to your computer and use it in GitHub Desktop.
Save nuttycom/1015486 to your computer and use it in GitHub Desktop.
Map implicits for scalaz
implicit def MapMonoid[K, V](implicit valueSemigroup: Semigroup[V]): Monoid[Map[K, V]] = new Monoid[Map[K, V]] {
override val zero = Map.empty[K, V]
override def append(m1: Map[K, V], m2: => Map[K, V]) = {
val (from, to, semigroup) = {
if (m1.size > m2.size) (m2, m1, (v1: V, v2: V) => valueSemigroup.append(v1, v2))
else (m1, m2, (v1: V, v2: V) => valueSemigroup.append(v2, v1))
}
from.foldLeft(to) {
case (to, (k, v)) => to + (k -> to.get(k).map(semigroup(_, v)).getOrElse(v))
}
}
}
implicit def mapPlus[V](implicit valueSemigroup: Semigroup[V]): Plus[({type λ[α] = Map[α, V]})#λ] = new Plus[({type λ[α] = Map[α, V]})#λ] {
override def plus[K](m1: Map[K, V], m2: => Map[K, V]) = MapMonoid[K, V].append(m1, m2)
}
implicit def mapMA[K, V](m: Map[K, V])(implicit valueSemigroup: Semigroup[V]): MA[({type λ[α] = Map[α, V]})#λ, K] = new MA[({type λ[α] = Map[α, V]})#λ, K] {
override val value = m
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment