Search code examples
lispelispcommon-lisp

Modify list and return it inside a function in lisp


(defun testthis (node index newvalue)
  (set-nth node index newvalue)
   node
)

I would like to modify the nth element of a list in a function and then returns this list to save the modification performed.

How can I do a such function in lisp?


Solution

  • You can use setf and the nth accessor:

    (defun replace-index (node index new-value)
       (setf (nth index node) new-value)
       node)
    
    (defparameter *orig* (list 1 2 3 4))
    (defparameter *mod* (replace-index *orig* 2 99))
    (list *orig* *mod*) ; ==> ((1 2 99 4) (1 2 99 4))