clojure - 从存储在 var 中的表达式定义函数

标签 clojure

我昨天问了类似的问题,但似乎我必须改变我的方法,所以我做了,但现在我又陷入困境了。

无论如何,我想做的是沿着线的事情

(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/

相关文章:

dictionary - Clojure pmap 与 map

file-io - 将文件读入列表,每个元素代表文件的一行

unit-testing - 无法解析符号: is in this context

ClojureScript + OpenLayers

clojure - 将 zip 文件写入 Clojure 中的文件

function - clojure 函数循环依赖是设计明确禁止的,还是只是读者行为?

clojure - 我可以将内容配置为 Clojure REPL 自动需要的内容吗?

clojure - 响应图为零

clojure - 我可以让 lein cloverage 跳过特定测试吗?

java - 将常规 Servlet 编码转变为我的 DSL 的起点