在 方案 我可以做这样的事情:
(define (adder)
(define (one) 1)
(define (two) 2)
(+ (one) (two)))
调用
adder
结果 3
打电话时one
将产生一个错误,因为 one
仅在 adder
范围内可见.在 Clojure 如果我做类似的事情
(defn adder []
(defn one [] 1)
(defn two [] 2)
(+ (one) (two)))
one
和 two
会污染我的命名空间,因为 defn
使用 def
在内部创建当前命名空间中的绑定(bind)。是否有在本地范围内创建命名函数的函数/宏?
我提出问题的原因是我已经习惯了 Scheme 的工作方式。以这种方式命名我的本地函数通常会使我的代码更具可读性。
最佳答案
试试 letfn :
Takes a vector of function specs and a body, and generates a set of bindings of functions to their names. All of the names are available in all of the definitions of the functions, as well as the body.
(defn adder []
(letfn [(one [] 1)
(two [] 2)]
(+ (one) (two))))
关于clojure - 有没有办法在 clojure 中创建一个仅在函数范围内可见的命名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22849110/