おっしゃるように、末尾再帰を使用してこれを実装する唯一の方法は、明示的なスタックの使用に切り替えることです。考えられるアプローチの1つは、ツリー構造を、本質的にツリーの逆ポーランド記法表現であるスタック構造に変換することです(これを実現するためにループと中間スタックを使用します)。次に、別のループを使用してスタックをトラバースし、結果を構築します。
これを実現するために私が作成したサンプルプログラムを次に示します。末尾再帰をインスピレーションとして使用して、ポストオーダーでJavaコードを使用します。
(def op-map {'+ +, '- -, '* *, '/ /})
;; Convert the tree to a linear, postfix notation stack
(defn build-traversal [tree]
(loop [stack [tree] traversal []]
(if (empty? stack)
traversal
(let [e (peek stack)
s (pop stack)]
(if (seq? e)
(recur (into s (rest e))
(conj traversal {:op (first e) :count (count (rest e))}))
(recur s (conj traversal {:arg e})))))))
;; Pop the last n items off the stack, returning a vector with the remaining
;; stack and a list of the last n items in the order they were added to
;; the stack
(defn pop-n [stack n]
(loop [i n s stack t '()]
(if (= i 0)
[s t]
(recur (dec i) (pop s) (conj t (peek s))))))
;; Evaluate the operations in a depth-first manner, using a temporary stack
;; to hold intermediate results.
(defn eval-traversal [traversal]
(loop [op-stack traversal arg-stack []]
(if (empty? op-stack)
(peek arg-stack)
(let [o (peek op-stack)
s (pop op-stack)]
(if-let [a (:arg o)]
(recur s (conj arg-stack a))
(let [[args op-args] (pop-n arg-stack (:count o))]
(recur s (conj args (apply (op-map (:op o)) op-args)))))))))
(defn eval-tree [tree] (-> tree build-traversal eval-traversal))
あなたはそれをそのように呼ぶことができます:
user> (def t '(* (+ 1 2) (- 4 1 2) (/ 6 3)))
#'user/t
user> (eval-tree t)
6
これをAntlrAST構造で動作するように変換するための演習として読者に任せます;)