Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map restructuring

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?

like image 798
benekastah Avatar asked Jan 25 '12 08:01

benekastah


2 Answers

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}
like image 53
Alex Taggart Avatar answered Nov 10 '22 08:11

Alex Taggart


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

like image 26
amalloy Avatar answered Nov 10 '22 07:11

amalloy