I'm currently working on some Lisp code and came up with an `insert-at-nth-` function that I'm pretty proud of. It took a while to figure out how to implement it without making copies of the original list, recursion, or looping/iteration. I know some built-in functions may use these concepts under the hood, but I wanted to keep my codebase clean. I'm using `nthcdr` and `cons` for this. Here's my code:
```
(defun insert-at-nth (list-prev index element)
"Inserts an element into a list at nth index. WARNING: alters original list, use with caution."
(setf (nthcdr index list-prev) (cons element (nthcdr index list-prev))))
```
My question is: Am I doing anything I should avoid? Can this be optimized further? Am I following best practices here? I think the function works fine, but since I'm not very experienced in Lisp, I'd appreciate others' opinions on its quality. Thanks!
3 Answers
LISP is very pragmatic, you don't have to be a purist! If you need to perform this operation, it's perfectly fine to create a function that mutates your data rather than duplicating code. Just keep an eye on performance—if the index is high and you're calling this function often, consider optimizing how you handle those cases.
Hey, it would be great if you could format your code properly so it's easier to read!
Just a heads up 🛑— there's no (setf nthcdr) function in Common Lisp, so make sure to double-check your references if you’re using Emacs Lisp.
Thanks for the clarification! I should've mentioned that I’m using Emacs Lisp, but I looked at Common Lisp docs for some insights!

I hear you! I've tried a few times to reformat my code here, but it just won't cooperate for some reason. I’m not sure if it's a mobile issue or what, but I've used three backticks with a line before and after, and it still messes up.