2014-12-19 41 views
2

我有这个Lisp代码,我试图将它转换成Clojure代码。Clojure相当于Lisp的原子函数

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

好像是Clojure中没有Lisp的原子(或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的​​功能?

回答

1

我想你会发现此行为apropriately:

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

不同的是,它会走出低谷迟早的nil - (rest nil)()它终于不再发生,但((complement coll?) nil)回报true,所以停止递归更快一步。

+0

我认为这里有一个陷阱与懒序列。但是他们也实现了'IPersistentCollection':'(coll?(range))'=>'true'。好! – Thumbnail 2014-12-19 03:38:40