2010-12-05 230 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) 
相關問題