clojure - 在 Environ (Clojure) 中定义函数,然后在代码中使用它

标签 clojure

我希望能够使用 Environ 在我的 Lieningen 项目中定义匿名函数。

项目文件的该部分如下所示:

{:env {:foo (fn [s]
                (count s))}}

然后在我的代码中,我想使用该函数。像这样的东西:

(-> "here are a few words"
    (env :foo))

然后获取s的大小。

最佳答案

Environ 将简单地调用 read-string在吸食的文件上。 :foo 处的值将是一个包含符号 fn 的列表,后跟一个内部带有符号 s 的向量,依此类推。即表单尚未被评估,因此您将无法调用匿名 fn

参见environ.core/read-env-file

考虑一下:

(def f (read-string "(fn [s] (count s))"))

(f "test")
;; => ClassCastException clojure.lang.PersistentList cannot be cast to clojure.lang.IFn

(def evaled-f (eval (read-string "(fn [s] (count s))")))
(evaled-f "test")
;; => 4

此外,您的预期用途有点偏离。 -> 是一个宏,它将采用第一个参数并将其“线程”到以下形式的第一个位置。

(macroexpand '(-> "here are a few words" (env :foo)))
;; => (env "here are a few words" :foo)

我认为您正在寻找类似的东西:

(let [f (eval (env :foo))]
  (-> "here are a few words"
      f))

关于clojure - 在 Environ (Clojure) 中定义函数,然后在代码中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28219406/

相关文章:

command-line - 用Clojure编写一个惰性的,功能性的,交互式命令行应用程序

macros - 为什么要尽可能多地删除宏?

http - get 请求中的零内容长度从 lighttpd (clj-http) 获取 400 Bad Request

clojure - Clojure 中函数名前面的 -(减号)符号是什么意思?

go - golang中是否有等效的滑动缓冲区chan?

clojure - 事务内部的deref可能会触发重试-ref状态历史记录的作用是什么?

json - 如何将json文件读入Clojure defrecord(稍后搜索)

scala - Scala/Groovy/Clojure 中的 GUI

clojure - 如何标记 Clojure 函数以便可以通过 Java 反射识别它

clojure - Enlive - 提取原始 HTML