8
votes

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:

  • Of course, I already tried googling, and only found map-entry? However, this document has no linked resources.
  • I know that (first {1 2}) returns [1 2], which seems a vector. However:
(class (first {1 2}))
; --> clojure.lang.MapEntry
(class [1 2])
; --> clojure.lang.PersistentVector
  • I checked in the source code, and I'm aware that both MapEntry and PersistentVector extend APersistentVector (so MapEntry is more-or-less also a vector). However, the question is still, whether I can create a MapEntry instance from Clojure code.
  • Last, but not least: "no, there is no built in way to do that in Clojure" is also a valid answer (which I strongly suspect is the case, just want to make sure that I did not accidentally miss something).
3

3 Answers

9
votes

"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))
5
votes

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")
2
votes

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}))