Wednesday, December 24, 2008

Learning Lisp

We are going to direct our attention towards the structure of data in the Lisp language. All expressions in Lisp are in the form of a list. Even functions will be in the form of a list. And now, meet the list.

A list is a linear arrangement of objects separated by blanks and surrounded by parentheses. The obkects which make up a list are either atoms or other lists. An atom is the basic unit of data understood by the Lisp language.

Here are some atoms

carbon
eve
1
bananastand

Here are some lists:

(1 2 3 4)
((i hate) (peanut butter) (and jelly))
(you (walrus (hurt) the (one you) love))
(add 3 (mult 4 5))
(garbage (garbage) out)

Let's introduce some Lisp functions which manipulate lists. Manipulating involves taking apart, putting together, and checking the values of lists. The two functions CAR and CDR are used to get parts out of lists.

Introduced in the Lisp programming language, CAR and CDR are primitive operations upon linked lists composed of cons cells. A cons cell is composed of two pointers; the car operation extracts the first pointer, and the cdr operation extracts the second.

Thus, the expression (car (cons x y)) evaluates to x, and (cdr (cons x y)) evaluates to y.

When cons cells are used to implement singly-linked lists (rather than trees and other more complicated structures), the car operation returns the first element of the list, while cdr returns the rest of the list. For this reason, the operations are sometimes given the names first and rest or head and tail.

Small Example which describes clearly about these two. In the below example (ADD 1 2 ) is a list given as input to these two functions.
(CAR '(ADD 1 2)) results

ADD

(CDR '(ADD 1 2)) results

( 1 2 )

No comments: