2016-12-05 58 views
0

我有以下結構:列表操作中CLISP

(defstruct node 
    parent 
    state 
    cost) 

node型結構的列表。

我想實現兩個功能:

(defun findMinimum (list) 

returns the node with the smallest cost in the list 
) 


(defun replaceNode (list) 

Checks if a node with the same state as new-node already exists in the list. 
If so, replaces that node with new-node. 
) 

我目前的解決方案僅僅是一個通過檢查每一個節點的整個列表循環。我想知道在cLISP中是否有更有效的方法來做到這一點?

任何幫助將不勝感激。

回答

2

我從駝峯更名你的函數更Lispy風格:

(defun find-minimum (list) 
    (reduce #'min list :key #'node-cost)) 

對於更換節點我猜你需要用新的節點的另一個理由。我們假設這就是你想要的:

(defun replace-node (new-node list) 
    (let ((pos-old-node (position (node-state new-node) list :key #'node-state))) 
    (when pos-old-node 
     (setf (nth pos-old-node list) new-node)))) 
+0

你可以用'MEMBER'而不是'POSITION'來獲得cons單元,然後設置它的'CAR'。這樣你就不需要用'NTH'重新遍歷列表。 – jkiiski

+0

謝謝你的回答。我怎樣才能使'find-minimum'返回最小代價節點,而不是最小值本身? –

+1

@RuiLoureiro您可以使用比較成本而不是「MIN」的函數。例如,'(lambda(&optional a b)(when(and a b)(if(<=(node-cost a)(node-cost b))a b)))' – jkiiski