创建正确列表的方案缺点问题
我在附加到该方案函数中的列表时遇到问题。
该函数旨在接受 2 个参数,并返回一个由第二个元素组成的列表,其次数与第一个元素中指定的次数相同。例如,如果您调用 (make-list? 5 4)
,您的输出应为 (4 4 4 4 4)
。
问题是当我使用 cons
时,我得到 ((((4 . 4) . 4) . 4) . 4)
。据我了解,我每次都会将其作为对象附加到整个列表的末尾,而不是我想要的最后一个元素。我不确定如何解决它。
这是我的函数,关于如何将最后一个元素而不是列表作为对象的建议会很棒。 (或者其他建议,如果这不是唯一/真正的问题。)
;make-list
(define make-list?
(lambda (N A)
(if (= N 1)
A
(cons (make-list?(- N 1) A ) A)
)
)
)
I'm having trouble appending to a list in this scheme function.
The function is meant to take in 2 arguments, and return a list consisting of the 2nd elements the number of times specified in the 1st element. For example, if you call (make-list? 5 4)
your output should be (4 4 4 4 4)
.
The problem is when I use cons
, I get ((((4 . 4) . 4) . 4) . 4)
instead. As I understand it, I am appending to the end of the entire list as an object each time, not the last element of it as I want to. I am unsure of how to fix it.
Here is my function, suggestions on how to cons to the last element instead of the list as an object would be great. (or other suggestions if that is not the only/real problem.)
;make-list
(define make-list?
(lambda (N A)
(if (= N 1)
A
(cons (make-list?(- N 1) A ) A)
)
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个好的经验法则是每个列表都以
'()
终止。在这种情况下,将基本情况设置为 0 并让它返回空列表可能更具说明性:因此,在本例中,如果我们命中 0,则返回空列表以“限制”我们的列表重新建设。
A good rule of thumb is that every list is terminated by
'()
. In this case, it might be more illustrative to make your base case 0 and have it return the empty list:So in this example, if we've hit 0, then we return the empty list to "cap off" the list we're building.
你的问题很烦人,是由细胞的工作方式引起的。如果 b 不是列表,则 (cons ab) 创建一个 cons 单元格。通过重新排序,您可以将原子添加到列表中,而不是相反,并使最里面的项目成为一个列表(顺便说一句,您可以使用 (cons A '()) 而不是 (list A)在下面的定义中)你可以解决这个问题。
Your problem is an annoying one, and is caused by how cons cells work. (cons a b) creates a cons cell if b is not a list. By reordering so you're adding the atom to the list, not the other way around, and making it so the innermost item is a list (by the way, you could use (cons A '()) instead of (list A) in the following definition) you get around this.