What is the built-in Clojure way (if any), to create a single map entry?
In other words, I would like something like (map-entry key value)
. In other words, the result should be more or less equivalent to (first {key value})
.
Remarks:
(first {1 2})
returns [1 2]
, which seems a vector. However:(class (first {1 2}))
; --> clojure.lang.MapEntry
(class [1 2])
; --> clojure.lang.PersistentVector
MapEntry
is more-or-less also a vector). However, the question is still, whether I can create a MapEntry
instance from Clojure code.Clojure - Maps. A Map is a collection that maps keys to values. Two different map types are provided - hashed and sorted. HashMaps require keys that correctly support hashCode and equals. SortedMaps require keys that implement Comparable, or an instance of Comparator.
Merges two maps entries into one single map entry. Following is the syntax. Parameters − ‘hmap1’ is the map of hash keys and values. ‘hmap2’ is the map of hash keys and values, which needs to be mapped with the first HashMap.
You can extract the key or value from a map entry using key or val, respectively: Note that, although all Clojure map entries are vectors, not all vectors are map entries. If you try to call key or val on anything that's not a map entry, you'll get a ClassCastException:
You can use dissoc to get a map that has all the same key-value pairs as an existing map, with possibly one mapping removed: You can get a sequence of all entries in a map using seq:
"no, there is no built in way to do that in Clojure" is also a valid answer
Yeah, unfortunately that's the answer. I'd say the best you can do is define a map-entry
function yourself:
(defn map-entry [k v]
(clojure.lang.MapEntry/create k v))
Just specify a class name as follows
(clojure.lang.MapEntry. "key" "val")
or import the class to instantiate by a short name
(import (clojure.lang MapEntry))
(MapEntry. "key" "val")
As Rich Hickey says here: "I make no promises about the continued existence of MapEntry. Please don't use it." You should not attempt to directly instantiate an implementation class such clojure.lang.MapEntry. It's better to just use:
(defn map-entry [k v] (first {k v}))
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