Swapping elements in a Common Lisp list

Matthew Piziak picture Matthew Piziak · Oct 16, 2010 · Viewed 7.7k times · Source

Is there a Common Lisp function that will swap two elements in a list given their indices and return the modified list?

Answer

Pi Delport picture Pi Delport · Oct 16, 2010

You can use rotatef:

(rotatef (nth i lst) (nth j lst))

Of course, list indexing can be expensive (costing O(size of list)), so if you do this with any regularity, you'd rather want to use an array:

(rotatef (aref arr i) (aref arr j))