Lisp Books

Monday 5 April 2010

Lists in Lisp


Lists are are one of Lisp's most flexible and powerful data types. Here are some examples of lists:
(red orange yellow green blue indigo violet)
(10 green bottles)
(9 18 27 36 45 54 63 72 81 90 99 108)
(thisisalist)
((a)(list of) (lists))

To get the length of a list, we can use the LENGTH function. We have to put the quote mark ' in front of each word here, otherwise Lisp would try to evaluate or understand what we mean:

length '(red orange yellow green blue indigo violet))
7

(length '(10 green bottles))
3

(length '(9 18 27 36 45 54 63 72 81 90 99 108))
12

(length '(thisisalist))
1

(length '((a)(list of) (lists)))
3

As you can see from the final example, lists can contain other lists. The elements of the list are the things that appear inside only one level of parentheses, so in the final example the LENGTH function returns 3 because there are only 3 elements to the list:

(a)
(list of)
(lists)


As we saw briefly in the first steps with Lisp post we can extract individual elements from lists using these functions:


(first '(a b c d e))
A

(second '(a b c d e))
B

(third '(a b c d e))
C

(rest '(a b c d e))
(B C D E)

(last '(a b c d e))
(E) 

(first (first '((a)(list of) (lists))))
A

Creating a new list is very easy using the LIST function:
(list 'banana)
(banana) 

(list 'water 'malt 'hops 'yeast)
(WATER MALT HOPS YEAST)


Again we have to put the quote mark ' in front of each word here, otherwise Lisp would try to evaluate or understand what we mean by water, malt, hops and yeast i.e. had we assigned values to these.

We'll look more at using, creating and extracting data from lists in future posts.