next up previous contents
Next: Searching for an element Up: Higher Order Functions Previous: Converting the `map' function:   Contents

Selecting elements from a given list: `filter'

This abstraction takes a predicate function and a list as its two arguments. The result returned by `filter' is a new list containing all elements of the original list, for which the predicate function returns the value `true'.

(define filter (lambda(p l)
                 (if (nullp l)
                   (if (p (car l))
                     (cons (car l) (filter p (cdr l)))
                     (filter p (cdr l))))))

(define l1 (cons one 
                  (cons two 
                         (cons three 
                                (cons four 
(ldisp! (filter (lambda(x) (gtp x two)) l1))
                             --> 3

Georg P. Loczewski 2004-03-05

Impressum und Datenschutz