2017-05-04 83 views
2

我想檢查一個密鑰是否存在一個地圖,如果存在,我想增加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 

任何人都有更好的解決方案做同樣的事情嗎?

回答

8

你可以這樣說:

val newScores = currentScores + (score -> (currentScores.getOrElse(score, 0) + 1)) 
0
val updatedScore = score -> (currentScores(score)+ 1) 
val newScores= currentScores - score + newScore 
1
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