marcoo
marcoo

Reputation: 869

Scheme member function, unsure of my definition

I want

(member? 'a '((d d) (d d)))

to return false

what am I doing wrong

(define (member? x list)
 (cond
  ((null? list) #t )
   (else ( or (or (eq? (car (car list)) x) (eq? (cdr (car list)) x)) (member? x (cdr list) ))  
)))

If someone can tell me what is wrong with my member function I would greatly appreciate it.

Upvotes: 1

Views: 1535

Answers (2)

Óscar López
Óscar López

Reputation: 236004

Try this, it's a more general solution:

(define (member? ele lst)
  (cond ((null? lst) #f)
        ((not (list? lst))
         (equal? ele lst))
        (else (or (member? ele (car lst))
                  (member? ele (cdr lst))))))

Notice that if you want to search inside a list of (arbitrarily nested) lists, the recursion is a little bit more elaborate: you have to consider the cases when the list is empty, when the list is not a list but a single element, and you have to recur on both the car and cdr parts of the list.

For example, the above definition will work for lists such as this:

(member? 'x '((a b) (c (x))))
> #t

Upvotes: 2

sepp2k
sepp2k

Reputation: 370152

((null? list) #t )

You're returning true if the list is empty. That's wrong.

Upvotes: 3

Related Questions