Find an element of list in lists in list

前端 未结 3 1162
野趣味
野趣味 2021-01-28 05:58

I need a procedure which takes a list and checks if an element is part of that list even when the list contains lists. So far, I\'ve written this:

(define (elem         


        
3条回答
  •  清酒与你
    2021-01-28 06:14

    You're not recurring down the car of your set argument.

    If you evaluate

    (element-of-set? 3 '(a (a b b (c b) 3) 5 5 (e s) (s e s)))
    

    with your current definition of element-of-set?, it'll do something like

    • check if (eq? 3 'a), nope.
    • check if (eq? 3 '(a b b (c b) 3)), nope.
    • check if (eq? 3 5), nope
    • check if (eq? 3 5), nope
    • check if (eq? 3 '(e s)), nope
    • check if (eq? 3 '(s e s)), nope.
    • I'm out of list; 3 is not a member of '(a (a b b (c b) 3) 5 5 (e s) (s e s))

    If you want to check for deep set membership, you need to redefine your procedure so that it recurs into the car of set if that element is itself a list. Something like

    ...
    ((list? (car set)) (or (element-of-set? element (car set)) 
                           (element-of-set? element (cdr set))))
    ...
    

    should do it, assuming list? is actually defined (I don't have a scheme interpreter on this machine, so I'm not sure. You may need to use (not (atom? (car set))) instead).

提交回复
热议问题