我知道如何计算一个数字的数字之和:
(define (sum-of-digits x)
(if (= x 0) 0
(+ (modulo x 10)
(sum-of-digits (/ (- x (modulo x 10))
10)))))`但我只是不知道如何计算数字。也不知道如何通过线性迭代过程来实现。
谢谢!!
发布于 2012-10-04 21:13:46
你离答案很近。
为了弄清楚如何将数字之和转换为数字计数,请尝试编写一些测试用例。测试用例必须包括调用函数的示例以及预期的结果。
顺便提一句,这是一个生成递归的例子,你不应该处理它,直到你做了一系列的问题,比如“在列表中添加数字”,“在列表中计算元素”等等。
发布于 2012-10-04 22:40:01
关于你的每一个问题的提示:
1- Add an extra parameter to the function to hold the result accumulated so far
- Pass the initial value for the accumulator the first time you call the procedure, typically this is the same value that you'd have returned at the base case in a "normal" (non-tail-recursive) recursion.
- Return the accumulator at the base case of the recursion
- At the recursive step, update the accumulated result with a new value and pass it to the recursive call
- And the most important: when the time comes to call the recursion, make sure to call it as the last expression with no "additional work" to be performed.
https://stackoverflow.com/questions/12735885
复制相似问题