Clojure 等价于 Lisp 的 atom 函数

标签 clojure lisp

我有这段 Lisp 代码,我正在尝试将它转换成 Clojure 代码。

(defun copy-tree (tr)
  (if (atom tr)
    tr
    (cons (copy-tree (car tr))
          (copy-tree (crd tr)))))

Clojure 好像没有Lisp 的atom(或者atom 在Clojure 中的意思很不一样),只好修改代码如下。 ( Am I using atom? wrong or there is something else....? )

(defn single-valued?
     [x]
     (not (or (nil? x) 
              (.. x getClass isArray)
              (some #(instance? % x) [clojure.lang.Counted
                                      clojure.lang.IPersistentCollection
                                      java.util.Collection
                                      java.util.Map]))))

(defn copy-tree [tr]
  (if (or (= tr ()) (single-valued? tr))
    tr
    (cons (copy-tree (first tr))
          (copy-tree (rest tr)))))

代码工作正常,但是有没有更好的方法来替换 Lisp 的 atom 函数?

最佳答案

我想你会发现这个行为很恰当:

(def single-valued? (complement coll?))

不同的是,对于nil它会更快触底——(rest nil)(),它最终不会重现,但是 ((complement coll?) nil) 返回 true,因此提前一步停止递归。

关于Clojure 等价于 Lisp 的 atom 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27558813/

相关文章:

clojure 映射,%2 和 %1 是什么

map - 我可以使用 require :as with Java interop? 吗

clojure - 使用clojure.zip进行树后遍历以编辑节点

lisp - 了解 Common Lisp aref 行为

ide - 即插即用的 Lisp 实现

lisp - Common Lisp 中的属性列表是否引用某些全局状态?

database - 处理大型结构化数据集

clojure - 如何在 Clojure 中实现这种快速加倍斐波那契算法?

emacs - 在 Lisp/Emacs 中打印彩色字符

clojure - 为什么 Clojure 中需要 attr-map?