为什么我的 Common Lisp 循环只适用于简单的代码?
我有一些代码:
(defun divisor (x)
(loop for i from 2 to x do
(if (= x i) (return x)
(if (not (mod x i))
(return (append i (divisor (/ x i))))))))
应该返回 x 的素因数列表。然而,代码只返回 x。
defun 评估没有错误。我尝试跟踪 defun 中的每个函数,但没有一个函数被评估。 Loop 是一个宏,所以我无法跟踪它,但如果我清除循环内部并替换为
(format t "~d " i)
从 2 到 x 的计数,就像我所期望的那样。
我想我做错了什么,但我无法弄清楚。
I have a bit of code:
(defun divisor (x)
(loop for i from 2 to x do
(if (= x i) (return x)
(if (not (mod x i))
(return (append i (divisor (/ x i))))))))
that should return a list of the prime factors of x. However, the code just returns x.
The defun evaluates with no errors. I've attempted to trace every function in the defun, and none is ever evaluated. Loop is a macro, so I can't trace it, but if I clear out the inside of the loop and replace with
(format t "~d " i)
it counts from 2 to x, like I would expect.
I assume I've done something wrong, but I can't figure it out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个问题是您使用
(not (mod xi))
来确定mod
评估是否为 0,这是错误的。另一个问题是您正在将原子附加到列表中,但我认为这并不正是您想要做的。
这是一个似乎有效的修订版本:
One problem is that you are using
(not (mod x i))
to determine if themod
evaluation is 0, which is wrong.Another problem is that you are appending atoms to lists and I don't think it is exactly what you want to do.
Here is a revised version that seems to work:
在你的循环中, i 最终到达 x 。然后返回 x,丢弃可能从子递归返回的任何其他返回值。
我认为您不正确地将循环与递归结合起来。您只需执行其中一项即可。
In your loop, i eventually reaches x. So then you return x, discarding any other return value you might have returned from the sub-recursions.
I think you've improperly combined a loop with recursion. You only need to do one of them.