Drracket-在字符列表中查找元音总数 [英] DrRacket – Finding total number of vowels in list of characters
本文介绍了Drracket-在字符列表中查找元音总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在初学者语言模式下使用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)]))
这篇关于Drracket-在字符列表中查找元音总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文