next up previous contents index
Next: Removing an element from Up: Basic utility abstractions for Previous: Checking for an empty   Contents   Index


Determining the length of a list: `length'

This abstraction returns the length of a list. The list must be terminated by `nil'.

'length' checks each pair of the list until `nil' is found and then works its way back up to the beginning of the list incrementing the result of the previous step. The result of the last step will be the number of elements found in the list.

The metod used to iterate over all the elements of the list is called recursion. For more information on recursion readers are referred back to section patterns:recurse in the context of general programming patterns.


\begin{lstlisting}[language=Scm]{}
(define length (lambda (l)
(if (nullp l)
zero
(add one (length (cdr l))))))
\end{lstlisting}


\begin{lstlisting}[language=Scm]{}
(define l1 (cons one (cons two (cons three nil))))
;
(ndisp! (length l1))
--> 3
\end{lstlisting}


domain access counter Georg P. Loczewski 2004-03-05