gpt4 book ai didi

scope - LET 和 LET* 中的范围有问题

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:40 30 4
gpt4 key购买 nike

我正在尝试实现 local search algorithm进行优化。我是 Lisp 的新手,所以这是我想出的代码(注意 FORMATs):

(defun local-search (solution)
"Improve solutions by changing the order of the points"
(flet ((improve (route)
(alexandria:shuffle (copy-tree route))))
(let ((best-solution solution)
(best-cost (solution-cost solution)))
(format t "~a~%~%" best-cost)
(format t "Counter, Current, Best~%")
(loop with counter = 0
while (< counter *max_iterations*)
do (let* ((new-solution (improve solution))
(new-cost (solution-cost new-solution)))
(format t "~a, ~a, ~a~%" counter new-cost best-cost)
(if (< new-cost best-cost)
(setf best-cost new-cost
best-solution new-solution
counter 0)
(incf counter)))
finally (return best-solution)))))

现在,这可能不是最惯用的方法,我有兴趣找到更好的方法来实现它,但我的主要问题是:SETF 不似乎正在更新我的参数。当我运行我的函数时,这是我得到的输出(*max_iterations* 设置为 10):

796.4436

Counter, Current, Best
0, 796.4436, 796.4436
1, 796.4436, 796.4436
2, 796.4436, 796.4436
3, 796.4436, 796.4436
4, 796.4436, 796.4436
5, 796.4436, 796.4436
6, 796.4436, 796.4436
7, 796.44354, 796.4436
0, 796.4436, 796.44354
1, 796.4436, 796.44354
2, 796.4436, 796.44354
3, 796.4436, 796.44354
4, 796.4436, 796.44354
5, 796.4436, 796.44354
6, 796.4436, 796.44354
7, 796.44366, 796.44354
8, 796.4436, 796.44354
9, 796.4436, 796.44354

counter 中的重新启动,我可以看到代码找到了更好的解决方案,但它无法SETF 它们。我想这是因为一些我不知道的范围规则。我错过了什么?

编辑

对于上下文,这是 solution-cost 函数:

(defun solution-cost (solution)
"Calculate the total cost of a solution"
(reduce #'+ (mapcar #'cost solution)))

(defun cost (points &optional (acc 0))
"Calculate the total cost of a route"
(if (null points) acc
(cost (cdr points)
(+ acc (funcall *distance-fn* (first points) (second points))))))

完整代码是in this paste .我是这样调用它的:

(improve (initial-population *n_plants* (random-points)))

最佳答案

更新发生:

RRA-DARP 64 > (improve (initial-population *n_plants* (random-points)))
Was: 988.39277
Now is: 943.89106

Was: 943.89106
Now is: 895.5029

Was: 895.5029
Now is: 895.0123

900.5653

Counter, Current, Best
0, 900.56525, 900.5653 < old best

:SMALLER

0, 900.56525, 900.56525 < new best
1, 900.56525, 900.56525
2, 900.56525, 900.56525
3, 900.56525, 900.56525
4, 900.56525, 900.56525
5, 900.5653, 900.56525
6, 900.56525, 900.56525
7, 900.5653, 900.56525
8, 900.5653, 900.56525
9, 900.56525, 900.56525
Was: 895.0123
Now is: 900.56525

900.56525

关于scope - LET 和 LET* 中的范围有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33333368/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com