2

所以我正在使用 Lisp 制作一个相对简单的游戏。

我创建了一个具有所有 NIL 元素的指定大小的板:

(defun make-board(rows columns) 
  (cond ((= rows 1) (list (make-list columns)))
        (t ( append (list (make-list columns)) (make-board (1- rows) columns)))))

现在我正在研究 place 函数,它将在 2D 列表的列中的第一个 NIL 元素处放置一个值:

(defun place(player column matrix)
    ;need some help here

    ;I can get the specified column, is there a better way?!
    (let (col)(get-column column matrix))
)

我可以检索指定的列:

; return the given column
(defun get-column 
   (colnum matrix)
   (mapcar (lambda (row) (nth colnum row)) matrix))

我觉得这很简单,但不幸的是 Lisp 不能很好地与我合作。我也更喜欢这种没有迭代的实现,因为这是执行 Lisp 的“正确”方式。

编辑:

为澄清起见,make-board 将返回如下内容:

(make-board 5 5)
((NIL NIL NIL NIL NIL) 
 (NIL NIL NIL NIL NIL) 
 (NIL NIL NIL NIL NIL) 
 (NIL NIL NIL NIL NIL)
 (NIL NIL NIL NIL NIL))
4

2 回答 2

1

我不知道为什么递归应该是在 Lisp 中编程的“正确”方式。循环宏非常有用,使用它可以轻松实现您想要实现的功能。

(defun make-board(rows columns)
  (loop repeat rows collect
    (loop repeat columns collect nil)))
于 2013-04-14T15:21:53.353 回答
0

我相信为您的电路板使用二维数组会更方便:

(defun make-board (rows columns)
  (make-array (list rows columns)
              :initial-element nil))

为了找到一列的第一个空单元格,循环该列:

(defun find-null-cell-index (column board)
  "Returns the row index of the first cell in the given column of the board
that contains nil."
  (loop :for i :below (array-dimension board 0)
        :when (null (aref board i column))
        :do (return-from find-null-cell-index i)))
于 2013-04-14T17:48:19.327 回答