功能的方式来更新地图

问题描述:

我想检查一个密钥是否存在一个地图,如果存在,我想增加1的价值。如果不存在,我想在地图上添加一个新值,其值等于1.功能的方式来更新地图

什么是“功能性方法”?我用find和fold写过,但看起来有点奇怪。

val updatedScore = currentScores 
    .find(s => s._1.equals(score)) 
    .fold(score -> 1)(s => s._1 -> (s._2 + 1)) 

val newScores = currentScores + updatedScore 

任何人都有更好的解决方案做同样的事情吗?

你可以这样说:

val newScores = currentScores + (score -> (currentScores.getOrElse(score, 0) + 1)) 

val updatedScore = score -> (currentScores(score)+ 1) 
val newScores= currentScores - score + newScore 

val ret: mutable.Map[Int, Int] = mutable.Map[Int, Int]().withDefaultValue(1) 
val arg = 5 
ret.update(arg, ret(5)+1) 
+1

“功能性”通常意味着“避免副作用”等等。 'update'是一个副作用。 –

+1

我不明白这是为什么这是副作用?我的意思是,这整个问题是关于更新可变映射,不是吗? – user7938511

+0

这是一个有效的答案。接受的答案是OP想要的;然而,这是非常低效的,因为整个Map必须复制到新的Map。可变数据结构的原因在于scala,这对他们来说可能是一个很好的用例。 – Akavall

如果你的目标来算,可以考虑使用多重映射,即:http://lampwww.epfl.ch/~hmiller/scaladoc/library/scala/collection/mutable/MultiMap.html。既然你在积累计数,似乎没有一个很好的理由来避免副作用。