我昨天问了类似的问题,但似乎我必须改变我的方法,所以我做了,但现在我又陷入困境了。
无论如何,我想做的是沿着线的事情
(def bar '(* 2 %))
(#(bar) 2) ;this line doesn't work.
(#(* 2 %) 2) ;this is what I want the line that doesn't work to do.
事情是,我希望将表达式存储在 var 中,这样我就可以做类似的事情
(def bar2 (list (first bar) 3 (nth bar 2)))
(#(bar2) 2) ;this line obviously doesn't work either.
也许除了 #
匿名函数读取器宏之外还有另一种方法。
我正在为大学做一个遗传编程项目,所以我需要做的是有一个可以更改并使其成为函数的表达式。
最佳答案
(def bar '(* 2 %))
((eval (read-string (str "#" bar))) 3)
=> 6
如果您在表达式中使用命名参数,它看起来会更干净:
(def bar '(* 2 p))
(def f-expr (concat '(fn [p]) [bar]))
((eval f-expr) 3)
=> 6
关于clojure - 从存储在 var 中的表达式定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15621532/