我正在初学者语言模式下使用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)]))