Clojure - 具有未绑定函数的映射
Clojure - map with unbound function
我正在学习 Try Clojure 中的 Clojure 教程,其中介绍了如何定义我们的函数 -
(defn square [x] (* x x))
然后将其应用于数字列表:
(map square [1 2 3 4])
这会立即打印出一个错误:java.lang.IllegalStateException: Attempting to call unbound fn: #'sandbox14750/square
当我尝试映射例如函数 inc
时,效果很好 - 内置函数 inc
和我的 square
之间有什么区别?
我第一次尝试 运行 时遇到了一些麻烦,但在刷新页面后一切正常。
Give me some Clojure:
> (defn square [x] (* x x))
#'sandbox6361/square
> (square 4)
16
> (map square [1 2 3 4])
(1 4 9 16)
如果你想确保你的函数在你需要时仍然可用,你可以将你的函数存储在本地而不是像这样的变量中:
> (let [square (fn [x] (* x x))] (map square [1 2 3 4]))
(1 4 9 16)
>
#clojure 上的 Clojurebot 等许多 sandbpxed 环境不允许您定义任意状态,因此值得知道函数可以以多种方式存储,而不仅仅是在 vars 中。
我正在学习 Try Clojure 中的 Clojure 教程,其中介绍了如何定义我们的函数 -
(defn square [x] (* x x))
然后将其应用于数字列表:
(map square [1 2 3 4])
这会立即打印出一个错误:java.lang.IllegalStateException: Attempting to call unbound fn: #'sandbox14750/square
当我尝试映射例如函数 inc
时,效果很好 - 内置函数 inc
和我的 square
之间有什么区别?
我第一次尝试 运行 时遇到了一些麻烦,但在刷新页面后一切正常。
Give me some Clojure:
> (defn square [x] (* x x))
#'sandbox6361/square
> (square 4)
16
> (map square [1 2 3 4])
(1 4 9 16)
如果你想确保你的函数在你需要时仍然可用,你可以将你的函数存储在本地而不是像这样的变量中:
> (let [square (fn [x] (* x x))] (map square [1 2 3 4]))
(1 4 9 16)
>
#clojure 上的 Clojurebot 等许多 sandbpxed 环境不允许您定义任意状态,因此值得知道函数可以以多种方式存储,而不仅仅是在 vars 中。