LISP Problems
RECURSION: The basic means of developing LISP programs is defined by the limitations on accessing list elements. Fundamentally a list can be accessed by only two means:

Consequently most LISP functions have the form:

For example, let us develop the function to find the last element of a list.

The pseudocode could be:

To find the last item in a list,

  1. if the list is only one element long, then the last element is the head element;
  2. else find the last element of the tail.

How do we test to see if a list is of length 1? If the list is not an empty list, then the list is of length 1 when (cdr list) is null. Note that we need to eliminate the empty list case first. So our definition of the last function is:

( define last (list) 
      (cond  ((null list) nil) % eliminate the empty list case
             ((null (cdr list)) (car list)) % when the list is length 1 take first element
             (t (last (cdr list))) % otherwise get the last of the tail
      )
)

[TOC][Next]

CS1104 Main Page


Last updated 2001/04/06
© J.A.N. Lee, 2001.