Search code examples
lispcommon-lispclisp

Does a setfable nthcdr implementation exist?


I am using clisp and I wonder if there is any library with a setfable version of nthcdr that I can use.


Solution

  • You can hack around it with:

    (let ((lst (list 1 2 3 4))
          (n 2))
      (setf (cdr (nthcdr (1- n) lst)) '(5 6 7))
      l)
    > (1 2 5 6 7)
    

    Or define your own setf for it:

    ;; !!warning!!  only an example, lots of nasty edge cases
    (defsetf nthcdr (n lst) (new-val) 
       `(setf (cdr (nthcdr (1- ,n) ,lst)) ,new-val))
    

    I do not know why nthcdr does not have a setf defined. Even Alexandria seems to define setf for last, but not nthcdr.

    PS. I would treat wanting to setf an nthcdr as a bad smell in your code.