subset

The function (subset pred lst ) produces a list of elements of a given list that satisfy the predicate pred.


(subset number? '(a 1 b 2 3 c 4))
   =   (1 2 3 4)

(subset symbol? '(a 1 b 2 3 c 4)) = (a b c)


(define (subset pred lst)
  (if (pair? lst)
      (if (pred (car lst))
          (cons (car lst)
                (subset pred (cdr lst)))
          (subset pred (cdr lst)))
      '() ) )

Note that in subset the predicate is passed in as the argument pred, and pred is used as a function. This works because the name pred is bound to the function definition that is specified.

Contents    Page-10    Prev    Next    Page+10    Index