previous | index | next

Testing for List Membership (Ex. 7.8a)

Desired behavior of procedure element?:
          (element? 8 (integers-from-to 1 15)) ⇒ #t

          (element? 20 (integers-from-to 1 15)) ⇒ #f
Q: When is an item an element of a list?
(Hint: Answer in terms of the head and the tail.)

A: If it is equal to the head of the list, otherwise if it is an element of the tail of the list

     (define element?   ; Q: Will this work?
       (lambda (item lst)
         (cond ((equal? item (car lst)) #t)
               (else (element? item (cdr lst))))))

previous | index | next