Alex Rivera | Logout

Changing the nth element of a list

Asked 2011-05-19T13:20:58.780
13

I want to change the nth element of a list and return a new list.

I've thought of three rather inelegant solutions:

(defun set-nth1 (list n value)
  (let ((list2 (copy-seq list)))
    (setf (elt list2 n) value)
    list2))

(defun set-nth2 (list n value)
  (concatenate 'list (subseq list 0 n) (list value) (subseq list (1+ n))))

(defun set-nth3 (list n value)
  (substitute value nil list 
    :test #'(lambda (a b) (declare (ignore a b)) t)
    :start n    
    :count 1))

What is the best way of doing this?

Edit
Report

1 Answer

4

It depends on what you mean for "elegance", but what about...

(defun set-nth (list n val)
  (if (> n 0)
      (cons (car list)
            (set-nth (cdr list) (1- n) val))
      (cons val (cdr list))))

If you have problems with easily understanding recursive definitions then a slight variation of nth-2 (as suggested by Terje Norderhaug) should be more "self-evident" for you:

(defun set-nth-2bis (list n val)
  (nconc (subseq list 0 n)
         (cons val (nthcdr (1+ n) list))))

The only efficiency drawback I can see of this version is that traversal up to nth element is done three times instead of one in the recursive version (that's however not tail-recursive).

answered 2011-05-20T06:11:39.743

Your Answer