Penguin

LISP’s very basics

In the examples, any bold stuff is the result of running the code above it.

This is a list:

(apple orange banana)

Lists can be nested:

((fruit (apple orange banana)) (colour (red green)))

Lisp usually interprets lists as function calls:

(+ 40 2)
42

Lisp usually interprets symbols (i.e. identifiers) as variable references:

(* pi 2)
6.2831853071795862

A single-quote character "quotes" something, i.e. prevents Lisp from interpreting it. So the following is a list of symbols:

'(elem1 elem2 elem3)

let creates a list of variables that can be used in an expression:

(let ((a 1) (b 2) (mylist '(a b))) expression)

Hereafter, a will be 1, b = 2, mylist will contain the list '(a b).

setq changes the value of a variable:

(setq mylist '(a b c))

The cons function makes a pair:

(cons 'first 42)

Cons pairs are usually used to make lists: the first element is the first element on the list; the second element is either a cons pair for the rest of the list or a nil to mark the end of the list. Consider the following list:

'(1 2 3)

This list is a shorthand for:

(cons 1 (cons 2 (cons 3 nil)))

car returns the first element of a list:

(print (car mylist))
a

cdr returns the rest of the list (ie all-but-first):

(print (cdr mylist))
(b c)

And that is basically LISP.

A somewhat realistic example

The following example is an inefficient factorial function:

(defun fact (x)               ;a recursive function
  (if (> x 0)
    (* x (fact (- x 1)))
    1))

(This stupid function has become the HelloWorld of functional ProgrammingLanguages for some reason.)

Further reading

Look for the tutorial links on the LISP page.

Aside: where do these weird names come from?

The names "car" and "cdr" came from the first machine that Lisp was written for: there were 2 registers and the commands "contents of address register" and "contents of decrement register". CommonLisp allows the more sensible names "first" and "rest".

lib/main.php:944: Notice: PageInfo: Cannot find action page

lib/main.php:839: Notice: PageInfo: Unknown action