transforming trees in lisp

后端 未结 2 1059
长发绾君心
长发绾君心 2021-01-28 03:33

I\'m trying to modify a representation of a tree from : (A 2 B 0 C 2 D 0 E 0) in (A (B) (C (D) (E))). My code is like:

(defun transform(l)
 (cond
   ( (null l)          


        
2条回答
  •  悲哀的现实
    2021-01-28 03:42

    An answer to this is given by https://stackoverflow.com/a/34193414/1250772 as part of a response to a user who is evidently working through the same homework problem. The solution is based on reversing the prefix notation into postfix, and then interpreting it as a stack-based reverse polish notation for constructing a tree.

    By coincidence, the following code from that answer produces the same representation as what you're asking for. I came up with that representation impromptu, in order to solve the inorder traversal problem in that question:

    (defun build-tree (syntax)
      (let ((rs (reverse syntax))
            (stack))
        (dolist (item rs (pop stack))  ;; heart of the interpreter loop
          (cond ((integerp item) (push item stack))  ;; integer instruction
                ((symbolp item) (let ((num (pop stack)))  ;; sym instruction
                                  ;; construct node using backquote, and
                                  ;; put it on the stack.
                                  (push `(,item ,@(loop repeat num
                                                        collect (pop stack)))
                                        stack)))))))
    

提交回复
热议问题