Scala 不可变 MultiMap

11
在Scala中,我希望能够编写以下代码
val petMap = ImmutableMultiMap(Alice->Cat, Bob->Dog, Alice->Hamster)

底层的Map[Owner,Set[Pet]]应该同时使用不可变的Map和Set。这是ImmutibleMultiMap与伴生对象的初稿:

import collection.{mutable,immutable}

class ImmutableMultiMap[K,V] extends immutable.HashMap[K,immutable.Set[V]]

object ImmutableMultiMap {
  def apply[K,V](pairs: Tuple2[K,V]*): ImmutableMultiMap[K,V] = {
    var m = new mutable.HashMap[K,mutable.Set[V]] with mutable.MultiMap[K,V]
    for ((k,v) <- pairs) m.addBinding(k,v)
    // How do I return the ImmutableMultiMap[K,V] corresponding to m here?
  }
}

你能优雅地解决这个注释行吗?map和set都应该变成不可变对象。

谢谢!


1
这可能是将可变映射转换为不可变映射的示例,可能会很有用:https://dev59.com/93E85IYBdhLWcg3wXCIv - Arjan Blokzijl
2个回答

5
我现在已经写了两次这个方法,在接连的工作中。 :) 有人真的应该把它变得更加通用化。同时,拥有一个完整版本也很方便。
  /**
   * Like {@link scala.collection.Traversable#groupBy} but lets you return both the key and the value for the resulting
   * Map-of-Lists, rather than just the key.
   *
   * @param in the input list
   * @param f the function that maps elements in the input list to a tuple for the output map.
   * @tparam A the type of elements in the source list
   * @tparam B the type of the first element of the tuple returned by the function; will be used as keys for the result
   * @tparam C the type of the second element of the tuple returned by the function; will be used as values for the result
   * @return a Map-of-Lists
   */
  def groupBy2[A,B,C](in: List[A])(f: PartialFunction[A,(B,C)]): Map[B,List[C]] = {

    def _groupBy2[A, B, C](in: List[A],
                           got: Map[B, List[C]],
                           f: PartialFunction[A, (B, C)]): Map[B, List[C]] =
    in match {
      case Nil =>
        got.map {case (k, vs) => (k, vs.reverse)}

      case x :: xs if f.isDefinedAt(x) =>
        val (b, c) = f(x)
        val appendTo = got.getOrElse(b, Nil)
        _groupBy2(xs, got.updated(b, c :: appendTo), f)

      case x :: xs =>
        _groupBy2(xs, got, f)
    }

    _groupBy2(in, Map.empty, f)
  }

你可以像这样使用它:

val xs = (1 to 10).toList
groupBy2(xs) {
  case i => (i%2 == 0, i.toDouble)
}   

res3: Map[Boolean,List[Double]] = Map(false -> List(1.0, 3.0, 5.0, 7.0, 9.0),       
                                      true -> List(2.0, 4.0, 6.0, 8.0, 10.0)) 

使用了这个答案很多次。请注意,Seq比列表更通用,只需要更改签名并将c :: appendTo转换为c +: seq。我认为升级到Seq会使答案更好? - simbo1905

3

您面临的问题比这个更大,因为ImmutableMultiMap中没有返回ImmutableMultiMap的方法 - 因此无法向其中添加元素,并且构造函数也不支持使用元素创建它。请查看现有实现并注意伴生对象的builder和相关方法。


谢谢丹尼尔。我确实尝试通过查看不可变 HashSet 的伴生对象的源代码来解密构建器部分。但是,我无法理解它。您介意向我展示如何解决构造所需的 ImmutableMultiMap 问题吗? - PerfectTiling

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接