clojure - 定义函数体中的defn / def或let语句

时间:2014-06-01 19:59:58

标签: clojure defn

user=> (defn make-list [] '(1 2 3))
#'user/make-list
user=> (defn get-list [] (map #(str "foo" % ) make-list))
#'user/get-list
user=> (get-list)
IllegalArgumentException Don't know how to create ISeq from: user$make-list  clojure.lang.RT.seqFrom (RT.java:505)
user=> (defn get-list [] (let [ml (make-list)] (map #(str "foo" % ) ml) ))
#'user/get-list
user=> (get-list)
("foo1" "foo2" "foo3")

为什么不能从函数的BODY以相同的方式访问defn中的值,而不能从LET子句中访问它?

1 个答案:

答案 0 :(得分:3)

defn声明一个函数,所以你需要调用它才能得到它的结果:

(defn make-list [] '(1 2 3))
(defn get-list [] (map #(str "foo" % ) (make-list)))
(get-list)

;; ("foo1" "foo2" "foo3")

但由于您的makeList函数除了返回列表之外没有做任何事情,因此您可以使用def代替 var

(def make-list '(1 2 3))
(defn get-list [] (map #(str "foo" % ) make-list))
(get-list)

;;("foo1" "foo2" "foo3")

最后,在Clojure中使用kebab-case而不是 camelCase 来表示函数和var名称。除非您要声明协议或类型,否则这就是惯例。