【问题标题】:Why does not Clojure allow us to write functions unordered? [duplicate]为什么 Clojure 不允许我们编写无序函数? [复制]
【发布时间】:2017-05-07 00:43:40
【问题描述】:

我不喜欢 Clojure 的一件事是我需要按如下顺序定义函数:

(defn a [] 1)
(defn b [] (+ 1 (a)))


如果 Clojure 像 Java,我可以这样写(无序)。

(defn b [] (+ 1 (a)))
(defn a [] 1)

但是如果我这样做编译器会抛出 a is not defined...

的错误

Clojure 这样设计的主要原因是什么?

PS:我知道 Clojure 提供 declare 函数,但我不想在命名空间中声明所有函数。我想像在 Java、JavaScript 等中那样编写函数。

【问题讨论】:

  • Rich Hickey 讨论了基本原理here
  • Rich Hickey 关于 @SamEstep 提到的这个问题的注释对 CL 非常困惑:特别是你无法像他暗示的那样解决 CL 中的(非)问题。
  • 我希望这个问题会在immutable namespaces 到达时得到解决,无论何时。
  • 你的意思是:如果 Clojure 像 Lisp ...
  • @tfb 实际上,基本上来自评论“Clojure,就像之前的许多 Lisps 一样,没有强烈的编译单元概念。”之后,当 CL 被用作众多 Lisps 的代表时。

标签: clojure functional-programming lisp clojurescript


【解决方案1】:

也许你觉得这个小帮手很有用

(defmacro autodeclare [& exprs]
    (let [dfns# (filter #(and (list? %) (= (first %) 'defn)) exprs)]
      (map (fn [e]
             `(declare ~(second e))) dfns#)
      `(do ~@exprs)))
(autodeclare
   (defn c [] (b))
   (defn b [] (a))
   (defn a [] :a)
   (prn :no_defn))
(c)
user>  :a

【讨论】:

  • 这不能回答问题。
  • 是的,但我想鼓励人们构建自己的解决方案。这在 clojure 中很容易实现,并且问题本身已经在评论部分得到解答。在 lisp 中,您可以构建自己的工具,如果默认行为没有解决它
猜你喜欢
  • 2019-09-11
  • 2015-02-02
  • 2019-02-06
  • 2012-01-16
  • 2017-09-02
  • 1970-01-01
  • 1970-01-01
  • 2019-01-21
  • 1970-01-01
相关资源
最近更新 更多