clojure - 有没有办法在 clojure 中创建一个仅在函数范围内可见的命名函数?

标签 clojure scope scheme

方案 我可以做这样的事情:

(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)))
onetwo会污染我的命名空间,因为 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/

相关文章:

scheme - 在没有条件的情况下将 Scheme/Racket 中的 bool 值转换为整数?

clojure - 在应用程序中嵌入来自 leiningen 项目的版本字符串

clojure - 实时能力?

dictionary - Clojure:将元素添加到 map 内的向量中

haskell - 在 Haskell 中,处理守卫时 where 子句的范围是什么?

javascript - JavaScript 范围内 if(true) 的奇怪行为..?

clojure - 为什么 Clojure 有 5 种定义类的方法而不是只有一种?

javascript - Angular : Why isn't Component scope binding?

list - 将字符添加到频率列表

scheme - 合并排序输出 - 方案