Wednesday, 24 March 2010

Using Cons To Create Lists In Lisp

Today's post looks at creating lists in Lisp. Before we do that let's have a look at the answer to yesterday's post:

Write a function called square-odd-p. This function takes a single number as input, it squares this number and tests to see if the square of the number is odd.

(defun square-odd-p (x)
   (oddp (* x x)))

Creating Lists in Lisp
cons is a Common Lisp primitive, that creates lists from an atom
(number or letter) and a list:

(cons 1 '(2 3))
(1 2 3)

 We'll use cons to help us write a function to replace the first member of a list. In order to do this we'll:
  • Have to take two inputs to our function: the new item and the list
  • We'll use the rest function to return everything but the first member of the list
  • We can then cons our new item to the start of this list:
(defun replace-first (new-item the-list)
   (cons new-item (rest the-list)))

And an example:

(replace-first 'peter-pan '(one flew over the cuckoos nest))

In the next post we'll look at some more examples of building and manipulating lists.