LOOP:FOR 子句应该出现在循环主体之前

问题描述

我有这个代码,但是我在运行它时遇到了这个错误,有谁知道如何修复它或者我为什么会得到这个?

(defun pell (n)
  (setq n (+ n 1))
  (loop repeat n
        for current = 0 then next
        and next = 1 then (+ (* 2 next) current)
        collect current))

(print (pell 6))

解决方法

FOR 子句应该出现在循环主体之前

在 FOR 之前有一个 REPEAT 子句。 Lisp 抱怨 FOR 应该在主体之前发生。

因此代替

REPEAT ...
FOR ...
...

FOR ...
REPEAT ...
...
,

您需要将 and 更改为 for,并将 repeat 子句移到变量子句之后。每个迭代变量必须由其自己的 for 关键字引入。这是正确的版本:

(defun pell (n)
  (loop for current = 0 then next
        for next = 1 then (+ (* 2 next) current)
        repeat (1+ n)
        collect current))

(pell 6)  ; => (0 1 3 9 27 81 243)

注意:我之前在 repeat 之前带有 for 的版本被 SBCL 毫无问题地接受了,但是官方语法要求 repeat 之后的 for 1}} 子句。

this page,您可以找到 loop 原语的正确语法。

可以在 here 中找到对 loop 构造的介绍。