Skip to content

Instantly share code, notes, and snippets.

@deech
Created March 5, 2016 00:27
Show Gist options
  • Save deech/cc19bea22a18b68f1a45 to your computer and use it in GitHub Desktop.
Save deech/cc19bea22a18b68f1a45 to your computer and use it in GitHub Desktop.
Setting an element in a nested list structure
(defun nset-element-at (path ast new-element)
(if (= 0 (length path))
(setf ast new-element)
(let ((place-fn)
(path (reverse path)))
(progn
(dotimes (current-index (length path) nil)
(setq place-fn
(if (= current-index 0)
(list 'nth (nth current-index path) 'ast)
(list 'nth (nth current-index path) place-fn))))
(eval `(setf ,place-fn new-element))))))
> (setq *x* '(1 (2 3 4 (5 (6 7 (8 9))))))
(1
(2 3 4
(5
(6 7
(8 9)))))
> (nset-element-at '(1 2 1 3 1) *x* 'x)
x
> *x*
(1
(2 3 4
(5
(6 7
(8 x)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment