方案:将递归改为尾递归
我不确定如何将向前计数变成尾递归程序。它接受一个非负数 n
,并返回从 0
到 n
的整数列表(包括 n
>)。
编辑:好的,我终于让这个工作了。问题不在于我当前的程序是递归的,而我需要使其成为尾递归的——这完全是错误的。实际的答案非常简短明了。因此,如果其他人被困在这个问题上并且也是一个十足的编程菜鸟,这里有一些可能会有所帮助的提示:
1)你的帮助程序旨在跟踪到目前为止的列表。
2)它的基本情况是..如果x = 0..你会做什么?添加 0 到..某物上。
3) 在 x - 1 上重复,然后将 x 添加到到目前为止的列表中。
4) 当你开始实际的程序时,向前倒数,你所需要的只是助手。但请记住,它需要两个参数!
I'm unsure of how to turn count-forwards into a tail-recursive program. It takes a non-negative number, n
, and returns the list of integers from 0
to n
(including n
).
Edit: Okay, I finally got this one to work. The problem wasn't that my current program was recursive and I needed to make it tail-recursive- It was just plain wrong. The actual answer is really short and clean. So if anyone else is stuck on this and is also a total programming noob, here's a few hints that might help:
1) Your helper program is designed to keep track of the list so far.
2) Its base case is.. If x = 0.. what do you do? add 0 onto.. something.
3) Recur on x - 1, and then add x onto your list so far.
4) When you get to your actual program, count-forwards, all you need is the helper. But remember that it takes two arguments!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里唯一的递归函数是 list-reverse。它是尾递归的,因为对自身的调用是函数体中的最后一个操作。
用于生成从 0 到
m
的非递减序列的函数(其中包含将1
添加到前一个元素的连续结果)将类似于:Test:
seq -do
是生成从m
到n
非递减序列的通用函数;它是尾递归的,因为最后一个操作是对其自身的调用。我还从头开始实现了
reverse
,以便您可以在作业问题中使用它。The only recursive function here is list-reverse. It is tail-recursive, because the call to itself is the last operation in the function body.
Your function for generating a nondecreasing sequence from zero to
m
, which contains the successive results of adding1
to the previous element, would look something like:Test:
seq-do
is a general function for generating nondecreasing sequences fromm
ton
; it is tail-recursive, because the last operation is the call to itself.I've also implemented
reverse
from scratch, so that you can use it in your homework problems.