Lists


Purpose

Lists are the basis of scheme. A list is an ordered set of numbers, symbols, and lists.

Usage

A list can be created one of two ways. The user can use the function "list", or the user can use an apostrophe, as will be shown below.

When a list is evaluated, it returns that list.

Examples

Lists evaluate to themselves.
  ox --> (list 'a 'b 'c)
  (a b c)
  ox --> '(1 2 3)
  (1 2 3)
If the list function is used, the arguments are evaluated before being added.
  ox --> (list (+ 1 1) (+ 2 2) (+ 3 3))
  (2 4 6)
If the apostrophe is used, the arguments stay unevaluated.
  ox --> '((+ 1 1) (+ 2 2) (+ 3 3))
  ((+ 1 1) (+ 2 2) (+ 3 3))
  ox --> '(1 (a b c) (5))
  (1 (a b c) (5))
The "empty list" is the list containing nothing. It is frequently returned by functions with no information to return. It also is used to mean "false".
  ox --> '()
  ()

Lists can be combined and modified in a bewildering variety of ways. Here are a few of the most common.

"Append" can be used to combine two lists:

  ox --> (append '(a b c) '(1 2 3))
  (a b c 1 2 3)
"Cons" can be used to add an element to the begining of a list:
 ox --> (cons 'a '(b c d))
 (a b c d)
"Car" is used to get the first element of a list:
  ox --> (car '(a b c d))
  a
And "cdr" is used to get the rest of the list:
ox --> (cdr '(a b c d))
(b c d)
So one way to get the third element of the list would be...
  ox --> (car (cdr (cdr '(a b c d))))
  c
Which works because:
ox --> (cdr '(a b c d))
(b c d)
ox --> (cdr '(b c d))
(c d)
ox --> (car '(c d))
c
Ick! There is a short-hand for this and other similar tasks:
ox --> (caddr '(a b c d))
c
ox --> (cddr '(a b c d))
(c d)
ox --> (cadr '(a b c d))
b
You won't encounter expressions like "caddr" all that frequently, because Steve has gratiously included the function "list-ref" which takes a list and a number, and returns the nth element of the list (counting from zero):
ox --> (list-ref '(a b c d) 2)
c
ox --> (list-ref '(a b c d) 0)
a

Here is a practical example of a function which choses a random polygonal object to load from a list:

  (define (make-object objs)
    (accad-object (list-ref objs (floor (* (rand) (length objs))))))

  (define objects '("skull.obj" "ball.obj" "face.obj" "horse.obj"))

  (make-object objects)

Return to Scheme Introduction
mrl