我需要创建一个布尔函数来评估两个列表,例如:
(define list1 '((1 2) (4 5) (8 6) (2 8)))
(define list2 '((1 2) (8 6)))
list2
是list1
的子列表,必须返回#t
,但我不知道怎么做,我尝试使用此函数比较两个列表
(define (sublist? lst1 lst2)
(if (null? lst2)
#f
(if(list? (car lst2))
(sublist? lst1 (car lst2))
(if (and(equal? car(lst1) (car lst2)) (equal? cdr(lst1) (car lst2)))
#t (sublist? lst1 (cdr lst2))))))
帮助:(
答案 0 :(得分:1)
此sublist?
表现为“子集?”。
; sublist? : list list -> "boolean"
; return non-false if all elements of xs are in ys
(define (sublist? xs ys)
(or (null? xs) ; the empty list is a sublist of ys
(and ; for a non-empty list
(member (car xs) ys) ; the first element must be in ys
(sublist? (cdr xs) ys)))) ; and the rest of the elements as well.
这个sublist?
表现为“子串?”
; prefix? : list list -> boolean
; is xs a prefix of ys?
(define (prefix? xs ys)
(or (null? xs)
(and (equal? (car xs) (car ys))
(prefix? (cdr xs) (cdr ys)))))
; sublist? : list list -> boolean
; is xs a consecutive sublist of ys?
(define (sublist? xs ys)
(or (null? xs)
(prefix? xs ys)
(and (not (null? ys))
(prefix? xs (cdr ys)))))
答案 1 :(得分:0)
建议的解决方案:
(define list1 '((1 2) (4 5) (8 6) (2 8)))
(define list2 '((4 5) (8 6)))
(define (sublist? lst1 lst2)
(if (null? lst2)
#t
(if (and (null? lst1)
(not (null? lst2)))
#f
(if (list? (car lst2))
(or (and (sublist? (car lst1) (car lst2))
(sublist? (cdr lst1) (cdr lst2)))
(sublist? (cdr lst1) lst2))
(if (eq? (car lst1) (car lst2))
(sublist? (cdr lst1) (cdr lst2))
(sublist? (cdr lst1) lst2))))))
(sublist? list1 list2)
<强>解释强>:
这是(不)简单地处理所有边缘情况:
- 如果list2
为空 - 它始终是list1
的子列表
- 如果我们到达list1
并且list2
尚未找到 - 则返回false
- 如果(car list2)
是一个列表 - 我们需要递归检查两种情况:(car list1)
等于(car list2)
或(car list2)
是(cdr list1)
中的其他地方
- 如果(car list1)
和(car list2)
相同,我们会以两个列表的其余部分递归检查:(cdr lst1)
和(cdr lst2)
此答案已经过测试here