Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update and replace map value

Tags:

clojure

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?

like image 807
Timothy Baldridge Avatar asked Feb 23 '11 17:02

Timothy Baldridge


People also ask

How do you update map values?

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.

Can we update value in map?

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.

How do I change the value of a key in a HashMap?

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.

Can we update HashMap while iterating?

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 ...


1 Answers

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.

like image 178
sepp2k Avatar answered Oct 18 '22 19:10

sepp2k