scala 连接两个不可变映射 - 首选哪些元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11742451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:24:18  来源:igfitidea点击:

Concatenate two immutable maps - which elements are preferred?

scalamap

提问by John Threepwood

When concatenating two immutable maps, it seems that the elements of the right operand will "overwrite" the elements of the left one:

当连接两个不可变映射时,右操作数的元素似乎会“覆盖”左操作数的元素:

scala> List((1, 2), (5, 6)).toMap ++ List((5, 9)).toMap
res13: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 5 -> 9)

scala> List((5, 9)).toMap ++ List((1, 2), (5, 6)).toMap
res14: scala.collection.immutable.Map[Int,Int] = Map(5 -> 6, 1 -> 2)

I would like to know, if this is a rule in Scala ?

我想知道,这是否是 Scala 的规则?

From the Scala API I could not figure out this question.

从 Scala API 我无法弄清楚这个问题。

回答by Nikita Volkov

Yes, this behaviour is constant

是的,这种行为是恒定的

回答by Malte Schwerhoff

Map.++is defined as:

Map.++定义为

override def ++[B1 >: B](xs: GenTraversableOnce[(A, B1)]): immutable.Map[A, B1] =
    ((repr: immutable.Map[A, B1]) /: xs.seq) (_ + _)

where repris your current map and xs.seqgives you a sequence of the pairs/mappings stored in the map you pass to ++.

repr您当前的地图在哪里,并xs.seq为您提供一系列存储在您传递给的地图中的对/映射++


Map./:is described as:


Map./:被描述为

def /:[B](z: B)(op: (B, (A, B)) ? B): B

Applies a binary operator to a start value and all elements of this
immutable map, going left to right.

Note: /: is alternate syntax for foldLeft;
z /: xs is the same as xs foldLeft z.

Note that it is not specified what "from left to right" means for an unordered map.

请注意,未指定“从左到右”对于无序映射的含义。


The following illustrates what happens behind the scene by reimplementing ++and augmenting it with debug printlnstatements:


下面通过++使用调试println语句重新实现和扩充它来说明在幕后发生的事情:

val m1 = Map(1 -> "A", 2 -> "B", 3 -> "C")
val m2 = Map(2 -> "X", 3 -> "Y", 4 -> "Z")

println(m1.repr)
  /* Map(1 -> A, 2 -> B, 3 -> C) */
println(m1.repr.getClass.getName)
  /* scala.collection.immutable.Map$Map3 */

def ++[K, V](ts: Map[K, V], xs: Map[K, V]): Map[K, V] =
  (ts /: xs)  {case (acc, entry) =>
                println("acc = " + acc)
                println("entry = " + entry)
                acc + entry
              }

val m3 = ++(m1, m2)
  /*
    acc = Map(1 -> A, 2 -> B, 3 -> C)
    entry = (2,X)
    acc = Map(1 -> A, 2 -> X, 3 -> C)
    entry = (3,Y)
    acc = Map(1 -> A, 2 -> X, 3 -> Y)
    entry = (4,Z)
  */

println(m3)
  /* Map(1 -> A, 2 -> X, 3 -> Y, 4 -> Z) */