2015-11-26 39 views
0

我有一個像下面的代碼。它返回列表,(((1 . 2) (1 . 0)) ((1 . 2) (1 . 1)) ((1 . 2) (1 . 3)) ((1 . 2) (1 . 4)) ((1 . 2) (1 . 5)) ((1 . 2) (1 . 6)) ((1 . 2) (1 . 7)) ((1 . 2) (0 . 2)) ((1 . 2) (2 . 2)))LISP。創建對的列表

我不知道如果我能在路上改寫generHod功能,使其返回列表像((1.2 1.0) (3.4 4.2) (1.3 1.3)...)

(setf hod '()) 

(defun generHod (CurrX CurrY) 
    (dotimes (y 8) 
     (if (/= y CurrY) 
      (setf hod (append hod (list (append (list (cons CurrX CurrY))(list (cons CurrX y)))))) 
     ) 
    ) 

    (dotimes (x 8) 
     (if (/= x CurrX) 
      (setf hod (append hod (list (append (list (cons CurrX CurrY))(list (cons x CurrY)))))) 
     ) 
    ) 

) 
+0

所有這些附加業務:不良作風。 –

+0

你提供什麼解決方案?不幸的是,我並沒有意識到不同的lisp函數可以使它更容易。 –

+2

我可以爲您提供一個很好的免費下載介紹性的Lisp書籍,其中介紹了基本知識:https://www.cs.cmu.edu/~dst/LispBook/index.html –

回答

1

首先:

(setf hod '()) 

這是一個糟糕的方式來定義一個全局變量;嘗試

(defparameter hod()) 

但爲什麼要使用全局變量呢?該函數可以構造一個新列表並返回它。如果調用者想要將其粘貼到全局變量中,則由調用者決定;這與該功能的操作無關。

(defun generHod ...) 

語法generHod是不是從Common Lisp中GENERHODgenerhod區分,在默認readtable。所有這些令牌都會產生相同的符號。最好不要在Lisp標識符中播放混合大小寫的遊戲;如果你想要多個單詞,請輸入gen-hod。通常generate一律縮寫爲英語黑客的gen,而不是gener。例如,請參閱Common Lisp中的gensym函數。

在你的功能,有一個完全是多餘的append

(append 
    (list (cons CurrX CurrY)) 
    (list (cons CurrX y)))) 

模式(append (list X0) (list X1) ... (list XN))可以改寫(list X0 X1 ... XN)。你只是將多餘的事物列表添加到一起來製作一個列表,而不是僅僅列出事物。

要想從整數值到浮點,該float功能可以使用,而loop宏提供了一個成語迭代和收集物品:

(defun gen-hod (curr-x curr-y) 
    (let ((cxy (list (float curr-x) (float curr-y)))) ;; allocate just once! 
    (nconc ;; destructive append: use with care 
     (loop for y from 1 to 8 
      when (/= y curr-y) 
       append (list cxy (list (float curr-x) (float y)))) 
     (loop for x from 1 to 8 
      when (/= x curr-x) 
       append (list cxy (list (float x) (float curr-y)))))))