方案,检查两个列表中的内容是否相同

问题描述 投票:1回答:7

如果两个列表相同,是否可以相互检查两个列表?

((清单-'嘿饼干猴)'(苹果比萨饼)==> #t

我尝试过类似的东西

(define (check-list list element)
  (let ((x list))
  (cond ((null? x) #f)
        ((eq? (car x) (car element)) #t)
        (else (check-list (cdr x) element))))
  (check-list list (cdr element)))

我知道这写得不正确,但不知道如何解决此问题。

有人可以帮助我吗?

list scheme procedure
7个回答
0
投票

似乎有些混乱。这里的“大”问题是如何确定两个列表是否共享至少一个共同的元素,让我们为该过程编写一个名为element-in-common?的过程。解决此问题之前,我们需要确定single元素是否属于一个列表,这是check-list应该做的(请注意,在代码check-list中,您将element作为第二个参数,但您将其视为元素的[[list)。

您不必编写check-list过程,它已经存在并且称为member。有了这些知识,我们就能解决大问题-如何确定一个列表(称为member)中至少一个元素是否在另一列表(称为lst1)中?

简单:我们使用递归遍历lst2中的每个元素,询问每个元素是否属于lst1。如果lst2中只有一个元素是lst1的成员,则返回lst2。如果#t中的所有元素都不在lst1中,则返回lst2。像这样的东西:

#f

不要忘记测试您的代码:

(define (element-in-common? lst1 lst2) (cond (<???> ; is the first list empty? <???>) ; then there are no elements in common ((member <???> lst2) ; is the current element of `lst1` in `lst2`? <???>) ; then there IS an element in common (else ; otherwise (element-in-common? <???> lst2)))) ; advance recursion


1
投票
有时可以帮助您以自然语言来制定解决问题的过程。让我们简化一下问题。

您如何检查

one元素是否包含在列表中?一种实现方法是将一个元素与列表中的每个元素进行比较,直到找到它为止(沿着已经完成的代码中的某个位置),但并不完全。快速草稿为:

(element-in-common? '(hey cookie monkey) '(apple pizza cookie)) => #t (element-in-common? '(hey cookie monkey) '(apple pizza pie)) => #f
我们可以使用先前的知识来解决当前的实际问题。我们知道如何在列表中搜索元素,现在我们需要在另一个列表中搜索列表中的每个元素。 

(define (member? e lst) (cond ((null? lst) #f) ; empty list doesn't contain e (or (eq? e <??>) ; either the first element is e or (member? e <??>))) ; the rest of the list contains e

(define (check-list lst1 lst2) (if (or (null? lst1) (null? lst2)) #f ; empty list(s) share no elements (or (member? <??> <??>) ; first element of lst1 in lst2? (member? <??> <??>)))) ; rest of lst1 in lst2? 应该用适当的表达式表示,以选择列表的各个部分。

1
投票
<??>

1
投票
(define (intersect? list1 list2) (and (not (null? list1)) (or (member (car list1) list2) (intersect? (cdr list1) list2))))

0
投票
memq

0
投票
在麻省理工学院]

(define (check-list list1 list2) (cond ((null? list1) #f) ((memq (car list1) list2) #t) (else (check-list (cdr list1) list2))))


0
投票
© www.soinside.com 2019 - 2024. All rights reserved.