I'm sure it's right here in front of me, but I'm missing it. Examine the following:
(assoc :position entity
(add (:position entity) (:velocity entity)))
What I want to do is something like this (with a fake function called altermap):
(altermap :position entity #((add % (:velocity entity)))
What is the suggested method? Is there a built-in function to do #2?
You can use computeIfPresent method and supply it a mapping function, which will be called to compute a new value based on existing one. For example, Map<String, Integer> words = new HashMap<>(); words.
The Combination of containsKey and put Methods. The combination of containsKey and put methods is another way to update the value of a key in HashMap. This option checks if the map already contains a key. In such a case, we can update the value using the put method.
Example 2: Update value of HashMap using computeIfPresent() In the above example, we have recomputed the value of the key Second using the computeIfPresent() method. To learn more, visit HashMap computeIfPresent(). Here, we have used the lambda expression as the method argument to the method.
Well, you can't do it by iterating over the set of values in the Map (as you are doing now), because if you do that then you have no reference to the keys, and if you have no reference to the keys, then you can't update the entries in the map, because you have no way of finding out which key was associated with the ...
update-in
is almost exactly like your altermap
function, except that it takes a vector of keys instead of a single key. So:
(update-in entity [:position] #(add % (:velocity entity)))
To the best of my knowledge there is no single-key variant of update-in
, but having to put brackets around the key shouldn't be too cumbersome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With