2010-12-05 125 views
0

我有以下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) 

好像我写的可能是一个有点冗长的功能。有没有更简洁的方式来编写它?

回答

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) 
相关问题