我需要在 Map 中累积结果。我尝试过用.map
、.reduceLeft
和.foldLeft(init(m))
来做这件事,然后才意识到我没有正确使用它们。expression
呼叫需要最新的地图才能获得正确的答案。
我最终得到了这个,它有效,但我觉得有一个在循环中更新的var
地图有点肮脏。从 Scala 最佳实践的角度来看,这是可以接受的吗?有什么好方法可以更习惯地重写它吗?
val acc = "some key name"
val id = "some other key name"
val myColl = List(1, 2, 3, 4, 5)
// oversimplification (these things actually do work and access other keys in the map)
def expression(m:Map[String, Int]) = (m(acc)) + (m(id))
def init(m:Map[String, Any]) = 0
// can this be made better?
def compute(m: Map[String, Int]) = {
var initMap = m + (acc -> init(m))
for(k <- myColl) {
initMap = initMap + (id -> k)
val exp = expression(initMap)
initMap = initMap + (acc -> exp)
}
initMap(acc)
}
compute(Map())
我不确定这是否干净,但它会避免使用 var:
def compute(m:Map[String, Int]) = {
val initMap = myColl.foldLeft(m + (acc -> init(m)))( (e, k) =>
e + (id -> k) + (acc -> expression(e + (id -> k))))
initMap(acc)
}
应返回相同的结果