Macros 不循环的Lisp宏;展开;

Macros 不循环的Lisp宏;展开;,macros,lisp,Macros,Lisp,我使用Lisp宏的第一步 (defconstant width 7) (defconstant height 6) ... ; board is a 2D array of width x height ; and this is my first ever macro: (defmacro at (y x) `(aref board ,y ,x)) ; "board" must be available wherever the macro is used. (defun foo (bo

我使用Lisp宏的第一步

(defconstant width 7)
(defconstant height 6)
...
; board is a 2D array of width x height
; and this is my first ever macro:
(defmacro at (y x)
  `(aref board ,y ,x))
; "board" must be available wherever the macro is used.

(defun foo (board ...)
  ...
  (loop for y from 0 to (1- height) do
    ; thanks to the "at" macro, this is cleaner:
    (let ((score (+ (at y 0) (at y 1) (at y 2))))
      (loop for x from 3 to (1- width) do
        (incf score (at y x))
        ; ...do something with score
        (decf score (at y (- x 3)))))))
代码使用了我的第一个宏“at”one。它发出“访问指令”来读取board[y][x],因此它只能在存在“board”的地方使用,如上面的函数“foo”

这起作用了-然后我意识到。。。我可以走得更远

这两个嵌套循环是“静态”约束的:y从0到高度-1,x从3到(宽度-1)。。。所以从理论上讲,我可以创建一个宏,它可以发出(展开!)循环代码中的incf和decf指令

我试过这个:

(defmacro unroll ()
  (loop for y from 0 to (1- height) do
    `(setf score (+ (at ,y 0)  (at ,y 1) (at ,y 2)))
    (loop for x from 3 to (1- width) do
     `(incf score (at ,y ,x))
     `(decf score (at ,y (- ,x 3))))))
…但失败-“(宏扩展-1”(展开))“显示为零

我做错了什么

如果不清楚,我希望使用两个嵌套的循环,并在外循环的开始处以及内部循环的每次迭代中发出“代码”

非常感谢任何帮助(我是一个口齿不清的新手)


<强>更新<强>:在@拉斯曼的建议之后,我成功地将这个更改应用到我的代码中,并且我非常满意地看到,我的LISP版本成为了第二个最快的实现,仅次于C和C++(并且比OcAML更快!)

(defmacro unroll ()
  (loop for y from 0 to (1- height)
        collect
          `(begin (setf score (+ (at ,y 0)  (at ,y 1) (at ,y 2)))
                  ,@(loop for x from 3 to (1- width)
                          collect `(begin (incf score (at ,y ,x))
                                          (decf score (at ,y (- ,x 3))))))))