2016-12-05 55 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