Clojure: A Gentle Introduction (Chapter 7, part 1)

This is the Clojure version of the exercises in chapter 7 of David Touretzky’s book ‘Common Lisp: A Gentle Introduction to Symbolic Computation’. Why this book? Why chapter 7, why not start at the beginning? I’ll discuss the motivation for this series in another blog post, so let us dive into the exercises now.

According to Touretzky, applicative programming is one of the three programming styles besides recursion and iteration. Applicative operators like map take another function as input, applying it to a sequence of data. These operators are higher-order functions, one of the concepts of functional programming.

Exercise 7.1 makes us write a function that adds one to its input. Applying this function to mapcar adds one to each element in a list.

Exercise 7.2 defines a table with some user data. Since we are interested in each user’s social security number, applying third to mapcar on this table will do the job.

Exercise 7.3 applies zerop to each element of a list. The result is a list of t’s and nil’s (according to the given input).

Exercise 7.4 lets us define a simple predicate (greater-than-5-p) which is then applied to mapcar on a list of numbers.

This is the Lisp code of exercises 7.1 to 7.4.

And this is the Clojure version of the same exercises:

Note the differences: apart from Clojure-typical syntax like “[]” for parameters, I also changed the structure of data like ‘daily-planet’. As the importance of lists has diminished a bit in Clojure, it’s often more useful to put structured data into maps, or here: a vector of maps.
This allows a rather concise syntax when accessing such data. Filtering out all social security numbers in ‘daily-planet’ can be done in a one-liner. For example, reading a peculiar value from a hash can be done using ‘get’:

Or you can use the keyword, instead. It works like a function:

This is the same mechanism like in the ‘daily-planet’ example. The difference is, we have several hashes within a vector. Solving this is simple: map over ‘daily-planet’ and apply the implicit ‘get’ to it.

This more verbose and Lisp-like way using a lambda function is equivalent:

To be continued.

About Manfred Berndtgen

Manfred Berndtgen, maintainer of this site, is a part-time researcher with enough spare time for doing useless things and sharing them with the rest of the world. His main photographic subjects are made of plants or stones, and since he's learning Haskell everything seems functional to him.