Created
March 5, 2016 00:27
-
-
Save deech/cc19bea22a18b68f1a45 to your computer and use it in GitHub Desktop.
Setting an element in a nested list structure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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