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子句中访问它?
答案 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名称。除非您要声明协议或类型,否则这就是惯例。