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?

有帮助吗?

解决方案

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

其他提示

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}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top