Scala:为什么mapValues产生视图,有什么稳定的选择? [英] Scala: Why mapValues produces a view and is there any stable alternatives?

查看:304
本文介绍了Scala:为什么mapValues产生视图,有什么稳定的选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚才我惊讶地发现, mapValues 生成一个视图。结果显示在以下示例中:

Just now I am surprised to learn that mapValues produces a view. The consequence is shown in the following example:

case class thing(id: Int)
val rand = new java.util.Random
val distribution = Map(thing(0) -> 0.5, thing(1) -> 0.5)
val perturbed = distribution mapValues { _ + 0.1 * rand.nextGaussian }
val sumProbs = perturbed.map{_._2}.sum
val newDistribution = perturbed mapValues { _ / sumProbs }

这个想法是,我有一个分布,这是一些随机性扰乱,然后我重新归一化它。代码实际上没有达到原始意图:由于 mapValues 生成视图 _ + 0.1 * rand.nextGaussian 始终在扰动被使用时重新评估。

The idea is that I have a distribution, which is perturbed with some randomness then I renormalize it. The code actually fails in its original intention: since mapValues produces a view, _ + 0.1 * rand.nextGaussian is always re-evaluated whenever perturbed is used.

I我正在做一些类似 distribution map {case(s,p)=> (s,p + 0.1 * rand.nextGaussian)} ,但这只是一点点冗长。所以这个问题的目的是:

I am now doing something like distribution map { case (s, p) => (s, p + 0.1 * rand.nextGaussian) }, but that's just a little bit verbose. So the purpose of this question is:


  1. 提醒不了解这一事实的人。

  2. 寻找他们为什么进行 mapValues 输出视图的原因。

  3. 是否有是生成具体的替代方法 Map

  4. 有没有其他常用的收集方法有这个陷阱。
  1. Remind people who are unaware of this fact.
  2. Look for reasons why they make mapValues output views.
  3. Whether there is an alternative method that produces concrete Map.
  4. Are there any other commonly-used collection methods that have this trap.

谢谢。

推荐答案

关于此, SI-4776 (由YT)。

介绍它的提交有这样的说法:

The commit that introduces it has this to say:


根据jrudolph的建议, c $ c> filterKeys 和 mapValues
转换抽象地图,并为immutable
映射重复功能。将转换 filterNot 从不可变换到常规地图。
phaller评论

Following a suggestion of jrudolph, made filterKeys and mapValues transform abstract maps, and duplicated functionality for immutable maps. Moved transform and filterNot from immutable to general maps. Review by phaller.

我没有能够找到jrudolph的原始建议,但我认为已经完成使 mapValues 更有效率。提出这个问题,这可能会令人吃惊,但如果您不太可能多次迭代这些值,那么 c> mapValues 更有效。

I have not been able to find the original suggestion by jrudolph, but I assume it was done to make mapValues more efficient. Give the question, that may come as a surprise, but mapValues is more efficient if you are not likely to iterate over the values more than once.

作为一个解决方法,可以执行 mapValues(...)。view.force 来生成新的地图

As a work-around, one can do mapValues(...).view.force to produce a new Map.

这篇关于Scala:为什么mapValues产生视图,有什么稳定的选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆