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


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.


(define length 
   (lambda (l)
      (if (nullp l)
         zero
         (add one (length (cdr l))))))


(define l1 (cons one (cons two (cons three nil))))
;
(ndisp! (length l1))
                             --> 3



Georg P. Loczewski 2004-03-05


Impressum und Datenschutz