COM1340 - Winter 2003
New lists from old
January 22, 2003

Given a list, we may want to create a new list based on the information contained in it. The new list might exclude certain elements in the original list, substitute for some elements, or insert new elements. For now, we'll only consider exclusions or insertions at the top level of the list.

All the code here is functional. That is, each procedure returns a new list, without mutating the input list.

Removing elements that satisfy a predicate

; rem-by-pred
; takes a list, returns a list with elements that satisfy a predicate
;  removed
(define (rem-by-pred lst)
  (cond
    [(null? lst) null]
    [(pred? (car lst))
     (rem-by-pred (cdr lst))]
    [else
      (cons (car lst)
            (rem-by-pred (cdr lst)))]))

Example (where pred? is number?):

(rem-by-pred '(cat dog 42 hamster 57 raven)) => 
  (cat dog hamster raven)

Last modified: Tues, Jan 21, 2003, 4:16 pm US/Eastern
HTML conversion by TeX2page 4p4k3