-
-
Save rsuniev/1015499 to your computer and use it in GitHub Desktop.
Map implicits for scalaz
This file contains 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
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