【问题标题】:Clojure's equivalent to Lisp's atom functionClojure 等价于 Lisp 的 atom 函数
【发布时间】:2014-12-19 02:12:45
【问题描述】:

我有这个 Lisp 代码,我正在尝试将其转换为 Clojure 代码。

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

Clojure 好像没有 Lisp 的 atom(或者 Clojure 中的 atom 含义很不一样),我只好修改代码如下。 (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 函数?

【问题讨论】:

    标签: clojure lisp


    【解决方案1】:

    我想你会发现这表现得恰到好处:

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

    不同的是,nil 会更早见底——(rest nil) 是 (),最终不会递归,但 ((complement coll?) nil) 返回 true,所以更早停止递归。

    【讨论】:

    • 我认为这里存在惰性序列的陷阱。但他们也实现了IPersistentCollection:(coll? (range)) => true。好!
    猜你喜欢
    • 1970-01-01
    • 2011-05-16
    • 2014-03-15
    • 2021-09-05
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多