有没有更好的方法来编写这个功能?

时间:2010-12-05 19:39:20

标签: list common-lisp

我有以下Common Lisp函数:

(defun get-positions (marker)
  (let ((result nil))
    (dotimes (i (length board))
      (if (eq (nth i board) marker)
          (push i result)))
    (nreverse result)))

这是board的内容,这是函数的输出:

CL-USER> board
(X X O NIL NIL NIL NIL NIL NIL)
CL-USER> (get-positions 'x)
(0 1)

似乎我写的函数可能有点冗长。是否有更简洁的方式来编写它?

1 个答案:

答案 0 :(得分:7)

我会这样写,传入要搜索的列表而不是使用全局变量board。我还添加了一个文档字符串,由于使用eq进行比较似乎相当随意,我会将其设为关键字参数,以便您可以提供=进行数字比较,或equal提供字符串:

(defun get-positions (x list &key (test #'eq))
  "Return list of indexes of positions where X appears in LIST.
Keyword :test specifies the comparison function (default: EQ)."
  (loop for y in list
        for i upfrom 0
        if (funcall test x y) collect i))

(get-positions 'x '(x x nil nil x nil x))
  ==> (0 1 4 6)