1
votes

I need to swap the elements of a list given two positions (i, j) to implement 2-opt heuristics for the TSP and found this question recommending the use of rotatef.

However, when I try using it I can't understand its behavior.

This is the piece of code that's giving me a headache:

(setq loop '(A B C D E F))
> (A B C D E F)

;; Original copy saved in loop
(setq new_tour loop)

(format t "ORIGINAL LOOP: " loop)
> LOOP: (A B C D E F)

(format t "NEW_TOUR: " new_tour)
> NEW_TOUR: (A B C D E F)

(rotatef (nth 0 new_tour) (nth 1 new_tour))
(format t "NEW_TOUR IS NOW: ~a~%" new_tour)
> NEW_TOUR IS NOW: (B A C D E F)

(format t "ORIGINAL LOOP IS NOW: ~a~%" loop)
> ORIGINAL LOOP IS NOW: (B A C D E F)

Why does rotatef also modify the 'loop' list? Is there a way of swapping the elements of new_tour without losing the original list (loop)?

1
You didn't take a copy. There is only one list in your code. - melpomene
you have two variables pointing to the same literal list. - Rainer Joswig
since your question had nothing to do with AI or heuristics, I have removed these tags... - Rainer Joswig

1 Answers

6
votes

To copy loop use

(setq new_tour (copy-list loop))