Searching within sublists in Racket

62 views Asked by At

Note: I am using R5RS

(define (found? value L)

  (cond

    ((null? L) #f)

    ((equal? (car L) value) #t)

    (else (found? value (cdr L)))))

This is the function I wrote for iterating over a list like (7 "a" (b (c a) () (d d))).

If I call (found? "a" '(7 "a" (b (c a)) () (d d))), it returns #t.

But if I call (found? 'a '(7 "a" (b (c a)) () (d d))), it returns #f.

I know that if I look for the entire sublist like (b (c a)), the function returns true. But it doesn't work for nested sublist, e.g. (c a).

How can I find the a within the sublist (c a)?

1

There are 1 answers

0
Martin Půda On BEST ANSWER

You have to add an additional cond branch for nested lists:

(define (found? value lst)
  (cond
    ((null? lst) #f)
    ((equal? (car lst) value) #t)
    ((list? (car lst))
     (or (found? value (car lst))
         (found? value (cdr lst))))
    (else (found? value (cdr lst)))))

Tests:

> (found? "a" '(7 "a" (b (c a)) () (d d)))
#t
> (found? 'a '(7 "a" (b (c a)) () (d d)))
#t