Drracket-在字符列表中查找元音总数元音、字符、总数、列表中

2023-09-03 08:48:55 作者:在思念里做流浪狗

我正在初学者语言模式下使用Drracket。

代码如下:

(define vowels '(#a #e #i #o #u))

(define total 0)

(define (any-in-list lst check)
  (cond
    [(empty? lst) (+ 0 total)]
    [(member? (first lst) check) (add1 total)]
    [else (any-in-list (rest lst) check)]))

(define (count-vowels string)
  (any-in-list (string->list string) vowels))

(count-vowels "how do i do this?")
干货 搜索设计这个点被你忽视了吗

total值停留在1。调试后,我意识到第二个cond语句的计算结果为#TRUE,然后停止。如何在更新total值后使其继续用于列表的其余部分?

推荐答案

找到匹配项时忘记递归。 另外,由于total为0,(+ 0 total)始终为0,(add1 total)始终为1。

不要尝试使用全局变量和突变-递归并使用递归值。

(cond
    ; The empty list contains nothing, so the result is 0.
    [(empty? lst) 0]
    ; If the first element is a member, the result is
    ; one more than the count in the tail.
    [(member? (first lst) check) (add1 (any-in-list (rest lst) check))]
    ; Otherwise, the count is the same as in the tail.
    [else (any-in-list (rest lst) check)]))