Recently I was writing some Clojure with a coworker and we needed to insert values into a nested map structure. Our first solution (and example of using it at the repl) looked something like this.
1 2 3 4 5 6 7 8 9 |
|
This worked but seemed overly verbose for doing what (in our minds) should have been a simple operation. After some digging around in the docs we found the function assoc-in
. This useful function allowed us to greatly simplify the code.
1 2 3 4 5 6 7 |
|
Much simpler and easier to read. The next person to look at the code will be able to quickly skim and tell what the code is doing.
assoc-in
can also be used with nested associative structures like vectors.
1 2 3 4 |
|
Hopefully this post makes searching for how to insert into nested maps slighly easier for the next person who thinks there must be a better way for doing this.