danielsto
danielsto

Reputation: 134

Swapping list elements in Common Lisp

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

Upvotes: 1

Views: 442

Answers (1)

Doug Currie
Doug Currie

Reputation: 41220

To copy loop use

(setq new_tour (copy-list loop))

Upvotes: 6

Related Questions