0

A function which will take an item and a list and return a boolean of whether or not the item was found on the list or any sublists.

(define is-present?
  (lambda (item lis)
    (if (null? lis) #f
       (if (eqv? item (car lis))
       #t
       (is-present? (item (cdr lis)))))))

I am able to search the element in a plain list but when there is a sublist in the list it fails.

4

4 回答 4

0

如果遇到子列表,则需要在此子列表上进行递归。

(define search
  (lambda (item lst)
    (cond ((null? lst)
           #f)
          ((pair? (car lst))
           (or (search item (car lst))
               (search item (cdr lst))))
          (else
            (or (eqv? item (car lst))
                (search item (cdr lst)))))))
于 2013-10-18T00:51:55.540 回答
0

请尝试以下操作:

(define (present? item list)
    (cond ((or (not (list? list)) (null? list)) #f)
          ((let ((x (car list))) (or (eqv? item x) (present? item x))) #t)
          (else (present? item (cdr list)))))

这就是我们正在做的事情:

  1. 我们首先检查是否list实际上是一个列表。如果它不是一个列表,那么我们返回#f
  2. 然后我们检查是否list为空。如果它是空的,那么我们返回#f
  3. 接下来我们检查carof是否listitem。如果是,那么我们返回#t
  4. 然后我们检查是否car包含。如果是,那么我们返回。listitem#t
  5. 最后,如果没有其他检查,那么我们返回是否cdr包含。listitem

present?函数检查是否item是 的成员list或子列表list

(present? 0 '(1 2 3 4))     => #f
(present? 3 '(1 2 3 4))     => #t
(present? 0 '((1 2) (3 4))) => #f
(present? 3 '((1 2) (3 4))) => #t

希望这可以帮助。

于 2013-10-18T00:52:34.433 回答
0

是的!这是我的作业问题。

这是我的回答:

(define present 
(lambda (x list)
(cond ((or (not (list? list)) (null? list)) #f)
      ((or (eqv? x (car list)) (present x (car list))) #t)
      (else (present x (cdr list))))))
于 2013-10-20T16:19:08.647 回答
0

如果caroflis本身就是一个列表,则需要采取特殊措施。您的代码缺少对该条件的检查。尝试这个:

(define (isPresent? item lis)
  (and (not (null? lis))
       (let ((head (car lis)))
         (or (eqv? item head)
             (and (pair? head) (isPresent? item head))  ;; <= your code missed this
             (isPresent? item (cdr lis))))))
于 2013-10-18T13:14:05.497 回答