间接递归 - clojure

时间:2012-06-04 11:30:44

标签: clojure functional-programming

以下代码有什么问题: func表达式获取包含可包含表达式的术语的表达式...

(defn term[]
    (def mytmp (zip/xml-zip {:tag :term}))
    (cond 
      (= (first(:content(first vecTok))) "(")
        (do
          (def mytmp (popVecTo mytmp))
          (def mytmp (zip/append-child mytmp (expression)))
          (def mytmp (popVecTo mytmp)))
      :else 
          (def mytmp (popVecTo mytmp)))
    (zip/node mytmp))
(defn expression[]
    (def mytmp (zip/xml-zip {:tag :expression}))
    (def mytmp (zip/append-child mytmp (term)))
    (while (contains? #{"+", "-", "*","/", "&", "|", "<", ">", "="} (first(:content(first vecTok))) )
      (do
        (def mytmp (popVecTo mytmp))
        (def mytmp (zip/append-child mytmp (term)))))
    (zip/node mytmp))
(def vecTok (vec (:content(first(xml-seq (parse  "C:/Users/User/Desktop/forHekronot/BallT.xml"))))))

在文件中:

<a><symbol>(</symbol><identifier>dy</identifier><symbol>-</symbol><identifier>dx</identifier><symbol>)</symbol></a>

1 个答案:

答案 0 :(得分:0)

尽管@ jszakmeister关于如何更好地解决问题的评论,让我试着回答这个问题:

您可以先(def expression)然后(defn term [] ...),最后(defn expression [] ...)

间接递归的典型例子当然是穷人对正数的奇数/偶数函数:

clojurec.core=> (def even)
#'clojurec.core/even
clojurec.core=> (defn odd [x]  (and (not (= x 0)) (even (dec x))))
#'clojurec.core/odd
clojurec.core=> (defn even [x] (or (= x 0) (odd (dec x))))
#'clojurec.core/even
clojurec.core=> (even 10)
true 
clojurec.core=> (odd 10)
false
clojurec.core=> (odd 10000)
StackOverflowError   clojure.lang.Numbers.equal (Numbers.java:214)

哎呀,根据文件的大小(或深度),这可能是个问题。但并非所有内容都丢失了,我们甚至可以重新定义内部使用trampoline

(defn even [n] 
  (letfn [(evenrec [x] (or (= x 0) #(oddrec (dec x)))) 
          (oddrec  [x] (and (not (= x 0)) #(evenrec (dec x))))]
    (trampoline evenrec n)))