交换Common Lisp列表中的元素

Mat*_*iak 13 lisp swap list common-lisp

是否有一个Common Lisp函数,它将在给定索引的列表中交换两个元素并返回修改后的列表?

Pi *_*ort 18

你可以使用rotatef:

(rotatef (nth i lst) (nth j lst))
Run Code Online (Sandbox Code Playgroud)

当然,列表索引可能很昂贵(花费O(列表大小)),所以如果你这样做有规律性,你宁愿使用数组:

(rotatef (aref arr i) (aref arr j))
Run Code Online (Sandbox Code Playgroud)