我试图在另一个列表中计算列表的出现但我被卡住了。我不知道是否有任何功能,但这是我的代码。它实际上发现了第一次出现并返回1.我怎样才能继续计算?
(define *test* '(a b c a b a b a b c b c b c a b c))
(define match
(lambda (pattern text) (cond ((null? pattern) 1)
((null? text) 0)
((eq? (car text) (car pattern))
(match (cdr pattern) (cdr text)))
(else (match pattern (cdr text))))
))
您的代码检查列表中的位置,直到找到匹配项为止,如果匹配,则返回它找到匹配项。您想要检查列表中的每个位置并添加包含该模式的位置,但由于您的代码预先查找模式,因此很难控制其运行的列表的哪个部分。我无法“解决”代码中的问题,所以我决定从头开始编写代码。希望它有意义:
(define begins-with (lambda (starter-list full-list)
(cond ((null? starter-list) #t)
((eq? (car starter-list) (car full-list)) (begins-with (cdr starter-list) (cdr full-list)))
(else #f)
)))
(define count-matches
(lambda (pattern lst)
(cond ((null? lst) 0)
((begins-with pattern lst) (+ 1 (count-matches pattern (cdr lst))))
(else (count-matches pattern (cdr lst)))
第一个函数begins-with
不检查模式的整个字符串,它只是检查它是否“以”模式开头。这允许我们使用另一个函数count-matches
来计算以模式开头的后缀数,换句话说,模式出现在字符串中的次数。
请注意,我上面编写的代码将计算重叠序列,例如'(a b a)
在'(a b a b a)
中出现两次。