scala - Updating immutable map as the side effect of getOrElse -
sometimes use map
memoization cache. mutable maps, use getorelseupdate
:
mutablemap.getorelseupdate(key, { val value = <compute value> value })
immutable maps don't have getorelseupdate
. want this
immutablemap.getorelse(key, { val value = <compute value> immutablemap += key -> value value })
this seems work in practice, have arguments believe works in theory, , it's more or less readable -- terrible idea reason i'm missing?
the other alternatives i'm considering are
immutablemap.get(key) match { case some(value) => value case none => val value = <compute value> immutablemap += key -> value value }
which not different , more cumbersome, or
if (immutablemap.contains(key)) { immutablemap(key) } else { val value = <compute value> immutablemap += key -> value value }
which dumbest , least idiomatic.
in principle rather not go solution uses helper return value , updated map, unless it's unarguably superior way.
sure, seems reasonable except 1 small issue... it's not updating collection! if you're using immutable map, map immutable. can not change it, ever.
in fact, immutable map scala collection not have +=
method defined on it, see immutable.map. methods "append" or "add" new values map return new map. you've written above compile, you'd have not using immutable.
to immutable map, you'll need work var
, replace var
new map (which can lead issues threading) or have adopt state monad type pattern in return not new value new map.
def getorcalc(m: map[key, value], k: key)(f: key => value): (map[key, value], value] ={ if(m.contains(k)) (m, m(k)) else{ val value = f(k) (m +: (k, value), value) } }
Comments
Post a Comment