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
public static int length (Cons arg) {
int n = 0;
for (Cons lst=arg; lst != null; lst = rest(lst) )
n++;
return n; }
(defun length (lst)
(let (n) ; let declares variables
(setq n 0) ; setq is like =
(while (not (null lst)) ; while it is 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; }