1

虽然我能做到

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

好像没有支持

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

为什么 ?

4

1 回答 1

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呢?

如果你想要一个implicit也可以作为 Monoid 的优化版本:

  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

于 2015-06-21T02:19:43.267 回答