How can I add a keyword to an existing clojure.lang.PersistentArrayMap? For example, given:
(def options {:abc :xyz})
How can I add a new keyword entry? Something like: :def
. So that I will have:
{:abc :def :xyz}
Also, is there an idomatic way to only add it if it’s missing?
xfthhxk
September 9, 2021, 12:29am
2
A map is a dictionary and requires a value for every key so the following is not possible
{:abc :def :xyz}
.
You can add an entry with assoc
.
(assoc options :foo :bar)
which yields a new map {:abc :xyz :foo :bar}
To add only if a key is missing use merge
(merge {:abc :baz :foo :bar} options)
will yield {:abc :xyz :foo :bar}
.
Maybe you want a set?
(def options #{:abc :xyz})
Then you could (conj options :def)
which would yield #{:abc :xyz :def}
.
Adding to a set is idempotent so (conj options :abc)
yields #{:abc :xyz}
1 Like
Okay. I guess I was confused with some code I was looking at. I thought I had a function parameter which was a PersistentArrayMap
of keywords. However, it was probably a Vector
or List
…
Thanks.
system
Closed
March 10, 2022, 1:19pm
4
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.