This post is part of a series of articles about LISP, a function called SUBST, Clojure, and other interesting stuff. You may want to read the previous posts before continuing with this post.
In part 1 of this series, we learned about the nine special forms of LISP, the building blocks that make up the language. In part 2, we went through how the SUBST function works on a small tree. In this part, we will show how SUBST can be written in a modern LISP: Clojure.
John McCarthy wrote in 1960 a paper on the programming language LISP. In the paper, he used the SUBST function to illustrate what you could do with the language. The function could go through any tree and replace all leaves that had one value with another value. Pretty-printed and with better argument names, it looked something like this:
(lambda (to from tree)
(cond ((atom? tree) (cond ((eq? tree from) to) ('t tree)))
('t (cons (subst to from (car tree))
(subst to from (cdr tree)))))))
If we want to replace 2 with 5 in a tree, we call SUBST with 2, 5, and the tree as a quoted list:
(subst 2 5 '(1 2 (1 2 3) 4))
=> (1 5 (1 5 3) 4)
We will rewrite this function step by step in Clojure, which is a modern LISP that, among other things:
Here are a few differences between Clojure and traditional LISP that we will take advantage of.
Clojure has changed some of the names (to the better, in my opinion), such as
fn instead of
def instead of
first instead of
next instead of
The syntax for a literal vector in Clojure uses square brackets,
. A vector of three numbers looks like this: