2015-09-29 128 views
0
(defun queens (n &optional (m n)) 
    (if (zerop n) 
     (list nil) 
     (loop for solution in (queens (1- n) m) ;; <=== what does the (1- n) mean? 
      nconc (loop for new-col from 1 to m 
        when (loop for row from 1 to n 
           for col in solution 
           always (/= new-col col (+ col row) (- col row))) 
        collect (cons new-col solution))))) 

(defun print-solution (solution) 
    (loop for queen-col in solution 
     do (loop for col from 1 to (length solution) 
       do (write-char (if (= col queen-col) #\Q #\.))) 
     (terpri)) 
    (terpri)) 

(defun print-queens (n) 
    (mapC#'print-solution (queens n))) 

嗨,有誰能向我解釋這個N皇后算法爲什麼會有(1 - n)? 「1-」部分和&可選語法是什麼?N-Queen Lisp(1- n)是什麼意思?

謝謝你,

+1

[它只是從n中減去1](http://clhs.lisp.se/Body/f_1pl_1_.htm)。可選參數在'&optional'關鍵字之後。 –

+0

,但是在lisp語言中肩是寫成( - n 1)?你介意多解釋一下嗎?我有點新來聆聽語言,謝謝 – theStress

+0

顯然沒關係。我相信'1 +'和'1-'是特別的,儘管我不完全確定。 –

回答

4

1-是一個減去從它的參數的函數。

&optional表示可選參數將隨之而來。通常默認值爲nil,但如果您將其指定爲列表(即(m n)),那麼該參數默認爲列表中的第二個值(在此情況下,如果第二個參數未通過,則m默認爲n)。

+0

明白了..謝謝^^ – theStress

+0

對不起,能否對(m n)部分進行更多解釋?你的意思是(皇后(-1 n)m))是指將一個n-1值和一個列表傳遞給函數? 你能給我皇后的功能嗎?跟蹤代碼時,我感到很失落。 – theStress

+1

@theStress如果我有一個函數定義爲'(defun myfun(a&optional(b 5)))'並且我調用'(myfun 4)',它實際上會調用'(myfun 4 5)'。但是,我可以自由地只說'(myfun 4 7)',然後'b'不會是5. –