如何计算Scheme中另一个列表中列表的出现次数

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

我试图在另一个列表中计算列表的出现但我被卡住了。我不知道是否有任何功能,但这是我的代码。它实际上发现了第一次出现并返回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))))
    ))
scheme find-occurrences
1个回答
0
投票

您的代码检查列表中的位置,直到找到匹配项为止,如果匹配,则返回它找到匹配项。您想要检查列表中的每个位置并添加包含该模式的位置,但由于您的代码预先查找模式,因此很难控制其运行的列表的哪个部分。我无法“解决”代码中的问题,所以我决定从头开始编写代码。希望它有意义:

(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)中出现两次。

© www.soinside.com 2019 - 2024. All rights reserved.