LET和LET中的范围问题*

时间:2015-10-25 18:28:43

标签: scope lisp common-lisp

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

(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)))

1 个答案:

答案 0 :(得分:2)

更新发生:

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