2010-12-05 10 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) 
関連する問題