previous | index | next

Testing for List Membership

          (element? 8 (integers-from-to 1 15)) ⇒ #t

          (element? 20 (integers-from-to 1 15))
          Error: car expects argument of type <pair>; given ()
Q: What's the problem?

A: Forgot to deal with the empty list (the base case of the recursion).

Q: Can an item be an element of the empty list?

A: No.

     (define element?   
       (lambda (item lst)
         (cond ((null? lst) #f)
               ((equal? item (car lst)) #t)
               (else (element? item (cdr lst))))))

previous | index | next