【问题标题】:Scala Immutable MultiMapScala 不可变多映射
【发布时间】:2011-03-26 18:57:44
【问题描述】:

我希望能够在 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?
  }
}

你能优雅地解决注释行吗?地图和集合都应该成为不可变的。

谢谢!

【问题讨论】:

标签: scala map immutability scala-collections multimap


【解决方案1】:

我已经在连续的工作中两次重写了相同的方法。 :) 有人真的应该让它更通用。有一个完整的版本也很方便。

  /**
   * 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会改善答案?
【解决方案2】:

你有一个比这更大的问题,因为ImmutableMultiMap 中没有返回ImmutableMultiMap 的方法——因此不可能向其中添加元素,并且构造函数不支持使用元素创建它.请查看现有实现并注意伴随对象的builder 和相关方法。

【讨论】:

  • 谢谢丹尼尔。我确实尝试通过将伴随对象的源代码遍历到 immutable.HashSet 来破译构建器的内容。但是,我无法理解它。你介意告诉我你将如何解决构建所需的 ImmutableMultiMap 的问题吗?
猜你喜欢
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
  • 2017-09-11
相关资源
最近更新 更多