在列表中的列表中查找列表的元素
问题描述:
我需要一个过程,它接受一个列表并检查一个元素是否是该列表的一部分,即使该列表包含列表也是如此.到目前为止,我已经写了这个:
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 (element-of-set? element set)
(cond ((null? set) #f)
((eq? element (car set)) #t)
(else (element-of-set? element (cdr set))))))
但是,如果您有一个如下所示的列表:
But, if you have a list that looks like this:
(a (a b b (c b) 3) 5 5 (e s) (s e s))
那么我写的 element-of-set?
不承认 3 是这个列表的一部分.我做错了什么?
then my written element-of-set?
does not recognize that 3 is a part of this list. What am I doing wrong?
答
你只需要另一个子句来检查 car
是否是一个列表.将此添加到您的 cond
(在 eq?
子句之后):
You just need another clause to check if the car
is a list. Add this to your cond
(after the eq?
clause):
((list? (car set))
(or (element-of-set? element (car set))
(element-of-set? element (cdr set))))
这会在任何子列表上递归.
This recurses on any sublists.