Contents    Page-10    Prev    Next    Page+10    Index   

Copy Tree and Substitute

It is easy to write a function to copy a binary tree:


(defun copy-tree (z)
  (if (consp z)
      (cons (copy-tree (first z))
            (copy-tree (rest z)))
      z) )

Why make an exact copy of a tree that we already have? Well, if we modify copy-tree slightly, we can make a copy with a substitution:


; substitute x for y in z
(defun subst (x y z)
  (if (consp z)
      (cons (subst x y (first z))
            (subst x y (rest z)))
      (if (eql z y) x z)) )


>(subst 'axolotl 'banana '(banana pudding))
(AXOLOTL PUDDING)

>(subst 10 'r '(* pi (* r r)))
(* PI (* 10 10))

>(eval (subst 10 'r '(* pi (* r r))))
314.15926535897933