Copy Tree and Substitute
It is easy to write a function to copy a binary tree:
(defn copy-tree [form]
(if (cons? form)
(cons (copy-tree (first form))
(copy-tree (rest form)))
form) )
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 new for old in form
(defn subst [new old form]
(if (cons? form)
(cons (subst new old (first form))
(subst new old (rest form)))
(if (= form old)
new
form) ) )