为什么我的 Common Lisp 循环只适用于简单的代码?

发布于 2024-12-13 17:00:38 字数 430 浏览 1 评论 0原文

我有一些代码:

(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

终止放荡 2024-12-20 17:00:38

一个问题是您使用 (not (mod xi)) 来确定 mod 评估是否为 0,这是错误的。

另一个问题是您正在将原子附加到列表中,但我认为这并不正是您想要做的。

这是一个似乎有效的修订版本:

(defun divisor (x)
  (loop for i from 2 to x do
       (if (= x i) (return (list x))
           (if (= (mod x i) 0)
               (return (append (list i) (divisor (/ x i))))))))

One problem is that you are using (not (mod x i)) to determine if the mod 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:

(defun divisor (x)
  (loop for i from 2 to x do
       (if (= x i) (return (list x))
           (if (= (mod x i) 0)
               (return (append (list i) (divisor (/ x i))))))))
小镇女孩 2024-12-20 17:00:38

在你的循环中, 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.

夏日落 2024-12-20 17:00:38
    (defun divisor (x) 
      (loop for i from 2 to x when (eql 0 (mod x i)) collect i))
    (defun divisor (x) 
      (loop for i from 2 to x when (eql 0 (mod x i)) collect i))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文