Reputation: 1404
I want to do this
(let [[a b c] '(1 2 3)]
{:a a :b b :c c}) ;; gives {:a 1, :b 2, :c 3}
But with [a b c]
saved in a vector like this
(def vect '[a b c])
(let [vect '(1 2 3)]
{:a a :b b :c c}) ;; complains that a is unresolved
Is it possible to somehow use a var to define how to destructure?
Upvotes: 0
Views: 89
Reputation: 22519
I would agree with Daniel to possibly rethink the reason why you need to do it, e.g. what exactly the problem is you are after.
But if you insist :), pretending that we literally work with "a b c.."s, you can do this:
user=> (def xs '[a b c])
#'user/xs
user=> (into {} (for [v xs] [(keyword v) v]))
{:a a, :b b, :c c}
Upvotes: 1
Reputation: 4173
The error occurs, because in this snippet:
(let [vect '(1 2 3)]
{:a a :b b :c c})
You're binding vect
to '(1 2 3)
. The vect
earlier defined as '[a b c]
earlier will be shadowed by the local let binding. a
,b
and c
will be left unbound.
The only way I think you can do what you ask is by using (abusing?) eval/macros, and building up the exact form that you need.
(eval (list 'let [vect ''(1 2 3)] '{:a a :b b :c c}))
;; => {:a 1 :b 2 :c 3}
However, I really urge you to put in some hammock time here and think about why you need to destructure using a var, and possible alternative designs. The solution above is already pretty hacky and using it could get very ugly...
Upvotes: 2