This is the first Chapter of a series of posts about porting The Little Schemer to Clojure. You may wish to read the intro.
The big theme in Chapter 1 is Simplicity of Data. In The Little Schemer world there are two levels in the syntax that describes data – atoms and lists. Note that an atom in TLS refers to a a string of characters (perhaps you could consider this a list element – ie a non-list), wheras in Clojure an atom refers to a unit of a transaction.
To test for atoms – we’ll use the atom?
function:
(def atom? (fn [a] (not (seq? a))))
Note that we’re not using the defn
syntax in Clojure but def ... fn
. This is intentional because the book uses this standard, and then makes use of it later in the book when it passes anonymous functions around.
Speaking of null
– the original Scheme has a different concept of nil than what we see in Clojure today. To make Clojure act like the null
tests in the book – we use the null?
function:
(def null? (fn [a] (or (nil? a) (= () a))))
In TLS the thematic emphasis is also on the Simplicity of Syntax. All data structures are represented by lists, and lists of lists (ie nested listed). In Clojure we have several types of data structures – but the closest to what we’re dealing with here is the Sequence. (Now it’s more complex than that – because in Clojure a sequence is more like an iterator interface – but we’ll start there.)
The other concept to get in Chapter 1 is that lists are treated as stacks rather than arrays. We push elements on the end and pop them off. Our primitives to do this in TLS are cons
to push, car
to pop and cdr
to get the list remainder. In Clojure this corresponds to cons
to push, first
to pop and rest
to get the sequence remainder. (Note that Clojure also has conj
, but we’ll stick to sequences and using cons for now)
The last trick that Chapter 1 introduces are nested lists. The short summary of this is that if you push a list onto a list you get a nested list (using cons
). To reverse this then you pop the nested list off the list (using car/first
).