15

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

Matthew Piziak
  • 3,430
  • 4
  • 35
  • 49

2 Answers2

21

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))
Pi Delport
  • 10,356
  • 3
  • 36
  • 50
4

I would avoid indexing into the list twice by using nthcdr to get the cdr of the cons cell containing the first element that you want to swap and then use elt to get the remaining element out of the sublist. This means that you only have to actually index starting from the head of the list once.

 (let ((list-tail (nthcdr i list)))
    (rotatef (car list-tail)
             (elt list-tail (- j i)))
    list)

At least from my perspective, this is sufficiently tedious to justify a function.

Gustav Bertram
  • 14,591
  • 3
  • 40
  • 65
aaronasterling
  • 68,820
  • 20
  • 127
  • 125