Common Lisp:为什么这个函数会导致无限递归?
我正在尝试编写一个类似于 list 的函数(lnn; list-not-nil),它仅附加非 nil 的值。
(list nil 3) --> (NIL 3)
(lnn nil 3) --> (3)
这是我到目前为止的代码。由于某种原因,它会导致我尝试的任何输入无限递归。
(defun lnn (&rest items)
(lnn-helper nil items))
(defun lnn-helper (so-far items)
(cond ((null items)
so-far)
((null (car items))
(lnn-helper so-far (cdr items)))
(t (lnn-helper (append so-far (list (car items))) (cdr items)))))
有什么想法吗?非常感谢。
I am trying to write a function (lnn; list-not-nil) similar to list that only appends values that are not nil.
(list nil 3) --> (NIL 3)
(lnn nil 3) --> (3)
Here is the code I have so far. For some reason it causes infinite recursion on any input that I try.
(defun lnn (&rest items)
(lnn-helper nil items))
(defun lnn-helper (so-far items)
(cond ((null items)
so-far)
((null (car items))
(lnn-helper so-far (cdr items)))
(t (lnn-helper (append so-far (list (car items))) (cdr items)))))
Any ideas? Thanks very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用此参数列表,如果您始终使用两个参数调用
lnn-helper
,则items
将永远不会nil
。删除&rest
说明符,它就会起作用。With this argument list,
items
will never benil
if you always calllnn-helper
with two arguments. Remove the&rest
specifier, and it'll work.马蒂亚斯的回答应该有帮助。另请注意,这只是一个简单的减少:
或者甚至(效率较低):
然后:
:)
PS:我知道这可能只是递归的练习,但是 SCNR。
Matthias' answer should have helped. Also note, that this is just a simple reduction:
Or even (less efficient):
Then:
:)
P.S.: I know this was probably just an exercise in recursion, but SCNR.