为什么在scalaz中没有TrieMap的Semigroup实例

时间:2015-06-19 09:34:30

标签: scala scalaz semigroup

虽然我能做到

Map("a" -> 1) |+| Map("a" -> 2)

似乎没有支持

TrieMap("a" -> 1) |+| TrieMap("a" -> 2)

为什么?

1 个答案:

答案 0 :(得分:1)

Scalaz并未提供构成半群的所有类型+操作组合,但您可以轻松实现它,例如使用以下implicit

import scala.collection.concurrent.TrieMap
import scalaz._, Scalaz._

implicit def trieMapSemigroup[K: BuildKeyConstraint, V: Semigroup]: Semigroup[TrieMap[K, V]] =
  new Semigroup[TrieMap[K, V]] {
    def append(m1: TrieMap[K, V], m2: => TrieMap[K, V]) =
      (m1 /: m2) { case (res, (k, v)) =>
        res += (k -> res.get(k).cata(Semigroup[V].append(_, v), v))
      }
  }

这可以满足您的预期:

scala> TrieMap("a" -> 1) |+| TrieMap("a" -> 2)
res: TrieMap(a -> 3)

当然,这将适用于scalaz中定义的半群作为半群。

Monoid怎么样?

如果您想要一个同样适用于Monoid的implicit的优化版本:

  implicit def trieMapMonoid[K: BuildKeyConstraint, V: Semigroup]: Monoid[TrieMap[K, V]] = new Monoid[TrieMap[K, V]] {
    def zero = TrieMap.empty[K, V]

    def append(m1: TrieMap[K, V], m2: => TrieMap[K, V]) = {
      val m2Instance: TrieMap[K, V] = m2
      val (from, to, semigroup) = {
        if (m1.size > m2Instance.size) (m2Instance, m1, Semigroup[V].append(_: V, _: V))
        else (m1, m2Instance, (Semigroup[V].append(_: V, _: V)).flip)
      }
      from.foldLeft(to) {
        case (res, (k, v)) => res += (k -> res.get(k).map(semigroup(_, v)).getOrElse(v))
      }
    }
  }

(代码无耻改编自scalaz/std/Map.scala