Iterative Processing of List

The basic operation on a list is to walk along it, processing one element at a time. We will illustrate the design patterns for doing this with the length function.


(length '(a b c))       ->  3


(defun length (lst)
  (let (n)              ; let declares variables
    (setq n 0)          ; setq is like =
    (while (consp lst)  ; is it a cons
      (setq n (+ n 1))
      (setq lst (rest lst)) )
    n ))


public static int length (Cons lst) {
  int n = 0;
  while ( lst != null ) {
    n++;
    lst = rest(lst); }
  return n; }


public static int length (Cons arg) {
  int n = 0;
  for (Cons lst=arg; lst != null; lst = rest(lst) )
      n++;
  return n; }

Contents    Page-10    Prev    Next    Page+10    Index