Scheme 方案,子列表
这个函数叫做sublist?有两个参数(两个列表)。它检查l2是否是l1的子列表并返回#t或#f 到目前为止,我已经知道了这一点,但exists函数似乎工作不正常Scheme 方案,子列表,scheme,Scheme,这个函数叫做sublist?有两个参数(两个列表)。它检查l2是否是l1的子列表并返回#t或#f 到目前为止,我已经知道了这一点,但exists函数似乎工作不正常 (define (sublist? l1 l2) (cond ((null? l2) #t) ((exists l1 (car l2)) #t) (else (sublist? l1 (cdr l2))))) (define (exists l p) (if (null? l) #f
(define (sublist? l1 l2)
(cond ((null? l2) #t)
((exists l1 (car l2)) #t)
(else (sublist? l1 (cdr l2)))))
(define (exists l p)
(if (null? l) #f
(or (equal? p (car l)) (exists (cdr l) p))))
更新首先,我认为在你的
存在
函数中,你缺少了一个等于?
看起来第一个参数应该是一个原子,但是在子列表函数中,首先发送列表,然后发送原子,需要切换参数
(define (exists l p)
(if (null? l) #f
(or (equal? p (car l)) (exists (cdr l) p))))
这应该行得通
此外,它的惯例是将谓词函数作为问题调用,您应该将其命名为exists?
[编辑]
仔细检查后,它看起来像您的子列表?函数不正确。即使列表中只存在子列表的一个元素,它也将返回#t。您需要将其稍微修改为:
(define (sublist? l1 l2)
(cond ((null? l2) #t)
((not (exists l1 (car l2))) #f)
(else (sublist? l1 (cdr l2)))))
现在你说:
1) 是空的吗?然后是一个子列表
2) 此元素不在列表中吗?那就不是了
3) 如果是,则检查其余元素。我相信前面的答案只检查子集,而不是子列表。子列表的顺序很重要,因此不能简单地检查列表中是否存在元素。您需要执行以下操作
(define (sublist? l1 l2)
(cond ((null? l2) #t)
((null? l1) #f)
((headlist? l1 l2) #t)
(else (sublist? (cdr l1) l2)))
(define (headlist? l1 l2)
(cond ((null? l2) #t)
((null? l1) #f)
((not (equal? (car l1) (car l2))) #f)
(else headlist? (cdr l1) (cdr l2))))
您的意思是
(equal?p(car l))
?equals?:模块中未绑定的标识符in:equals?这个错误是什么意思?谢谢。现在可以了,但是子列表呢?函数总是返回真值。这是我考试的练习作业。我担心我给你答案对你的伤害可能比帮助你更大,你需要自己在其他方面弄清楚这一点才能在考试中取得成功。