2013-12-08 18 views
2

我想在不同函数的let窗体中重用一组本地任务。比方说,Clojure:在绑定中展开var

(def common-assign 
    [x 10 
    y 20]) 

一个办法做到这一点是eval

(eval `(defn ~'foo [] 
     (let [[email protected] 
       ~'hello "world"]) 
     balala)) 

的问题是,现在你要引用的所有其他符号,这是麻烦的。

有没有其他干净的方式来做我想要的?

+2

用'defmacro'而不是'eval'编写宏。 – dg123

回答

2
(def common-assign 
    ['x 10 
    'y 20]) 

(defmacro defn-common [name args & body] 
    `(defn ~name ~args (let ~common-assign [email protected]))) 

(defn-common foo [a b c] (+ a b c x y)) 
0

您可以使用闭合此。

(let [x 10 
     y 20] 
    (defn foo 
    [] 
    (let [hello "world"] 
     ...))) 
    (defn bar 
    [] 
    ...)) 

但是,为什么不直接引用名称空间中的值呢?

(def x 10) 

(def y 20) 

(defn foo 
    [] 
    (let [hello "world"] 
    ...)) 

(defn bar 
    [] 
    ...)