In clojure, I can destructure a map like this:
(let [{:keys [key1 key2]} {:key1 1 :key2 2}]
...)
which is similar to CoffeeScript's method:
{key1, key2} = {key1: 1, key2: 2}
CoffeeScript can also do this:
a = 1
b = 2
obj = {a, b} // just like writing {a: a, b: b}
Is there a shortcut like this in Clojure?
It's not provided, but can be implemented with a fairly simple macro:
(defmacro rmap [& ks] `(let [keys# (quote ~ks) keys# (map keyword keys#) vals# (list ~@ks)] (zipmap keys# vals#)))
user=> (def x 1) #'user/x user=> (def y 2) #'user/y user=> (def z 3) #'user/z user=> (rmap x y z) {:z 3, :y 2, :x 1}
I wrote a simple macro for this in useful, which lets you write that as (keyed [a b])
. Or you can parallel the :strs and :syms behavior of map destructuring with (keyed :strs [a b])
, which expands to {"a" a, "b" b}
.
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