方案列表操作(递归)
这里的基本问题是,当给定一个列表时,返回该列表中除最后一个元素之外的所有元素。例如,给定 (abcd) -->返回(abc)。我本质上有这个功能,只是我遇到了麻烦,而且谷歌不太友好。我不确定我是否正确使用了 cons。
(define all-but-last
(lambda (x)
(if (null? (cdr x))
('()))
(cons ((car x) (all-but-last(cdr x)))
)))
熟悉 r5rs 方案语法的人会很有帮助。谢谢!
The basic problem here is, when given a list, to return all elements of that list other than the last element. For example, given (a b c d) --> return (a b c). I essentially have the function, it's just the Scheme syntax that I'm having trouble with and Google isn't being very friendly. I'm not sure if I'm using cons correctly.
(define all-but-last
(lambda (x)
(if (null? (cdr x))
('()))
(cons ((car x) (all-but-last(cdr x)))
)))
Someone who's knowledgeable with r5rs scheme syntax would be helpful. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果删除
'()
周围的额外括号和cons
的参数,则代码将正常工作(对于非空输入列表)。If you remove the extra parentheses around the
'()
and arguments tocons
, the code will work (for non-empty input lists).将 DrRacket 与语言 R5RS 结合使用,可以实现以下效果:
Using DrRacket with Language R5RS, this works:
另一种解决方案:
An alternative solution:
请参阅此问题的答案:
删除列表的最后一个元素(方案)
另外,我将把这个标记为“作业”。如果不是,请告诉我,我会将其删除。
See the answers to this question:
removing last element of a list(scheme)
Also, I'm going to tag this one as "homework". If it's not, let me know and I'll remove it.
如果你将 '() 传递给你的函数,我认为你应该给出错误消息而不是 return '()
if you pass '() to your function, I think you should give error message other than return '()