next up previous contents
Next: Iterating through all elements Up: Higher Order Functions Previous: Selecting elements from a   Contents


Searching for an element in a given list: `locate'

The abstraction `locate' returns the value `true' if the given list contains an element fulfilling the condition defined by the predicate function.

The abstraction `locatex' difers from `locate' only by returning the element found in the list instead of `true' if it was found.


(define locate (lambda(pred l)
                 (if (nullp l)
                      false
                      (if (pred (car l))
                           true
                           (locate pred (cdr l))))))
;
(define locatex (lambda(pred l)
                  (if (nullp l)
                       false
                       (if (pred (car l))
                            (car l)
                            (locatex pred (cdr l))))))


(define l1 (cons one 
                  (cons two 
                         (cons three 
                                (cons four 
                                       nil)))))
;
(bdisp! (locate (lambda(x) (equaln x two)) l1))
                                               --> true
(bdisp! (locate (lambda(x) (equaln x five)) l1))
                                               --> false



Georg P. Loczewski 2004-03-05


Impressum und Datenschutz