1

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

Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
danielsto
  • 134
  • 5
  • 17

1 Answers1

6

To copy loop use

(setq new_tour (copy-list loop))
Doug Currie
  • 40,708
  • 1
  • 95
  • 119