I am trying to modify a tree made of cons cells. Recursively I descend to
the cons where I want to append a subtree like (cons 'header (cons 'name nil)).
How do I do it so that the addition is seen when I later check the cons
cell that is at the root of the tree?
I do not want to change every tree element that matches certain criteria. I want to descent to the point where I append my subtree following a path similar to descending down the file system tree.
(defvar tree1)TREE1
(setq tree1 (list 1 (list 2 3 (list 4 5))))(1 (2 3 (4 5)))
tree1(1 (2 3 (4 5)))
(defvar tree2 (list 'a (list 'b 'c)))TREE2
(setf (first (caddr (car (cdr tree1)))) tree2)(A (B C))
tree1(1 (2 3 ((A (B C)) 5)))
(setq tree1 (list 1 (list 2 3 (list 4 5))))(1 (2 3 (4 5)))
(setf (second (caddr (car (cdr tree1)))) tree2)(A (B C))
tree1(1 (2 3 (4 (A (B C)))))
Instead I think you want
something like
(defun bintrav2 (arg &aux (tr arg))
(format t "trying ~S~%" tr)
(when (equalp tr '(2))
(setf (car tr) (cons 2222 nil))
(format t "trying changed ~S~%" tr))
(if (atom tr)
nil
(progn
(format t "trying with ~S~%" tr)
(bintrav2 (car tr))
(bintrav2 (cdr tr)))))
This is my lame attempt. Only if I knew how to replace your cars and
cdrs following the setf I would have my solution.
(defparameter *bintree* '(((1) . (2)) (3 . 4)))
(defun bintrav (tr)
(format t "trying ~S~%" tr)
(when (equal tr '(2))
(progn
(setf tr (cons 2222 nil))
(format t "trying changed ~S~%" tr)))
(if (atom tr)
nil
(progn
(format t "trying with ~S~%" tr)
(bintrav (car tr))
(bintrav (cdr tr)))))
It appears that (setf (car tr) 'whatever) was the answer I was looking
for. I could not figure out why (setf tr 'whatever) was the wrong
approach.
is it still a problem? For SETF to mutate its first argument the first argument of SETF has to be a SETF'able "place". If it is not a place but
a variable will merely modify the binding of the variable
like (setq var val)
On Thursday, 17 March 2022 at 12:15:17 UTC, Madhu wrote:
is it still a problem? For SETF to mutate its first argument the first
argument of SETF has to be a SETF'able "place". If it is not a place but
a variable will merely modify the binding of the variable
like (setq var val)
It is not a problem. But I must admit I did not understand the
distinction. I thought the binding of the variable was a SETF'able
place.
This is why you have to stop "one level up" from where you want to
modify a tree (if you are doing it this way) and why you can't modify an empty tree this way (there is no one-level up!).
That explains why I have cddr in accessing children and cdr in SETFing the tree.
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 299 |
Nodes: | 16 (2 / 14) |
Uptime: | 28:33:09 |
Calls: | 6,681 |
Calls today: | 4 |
Files: | 12,222 |
Messages: | 5,342,514 |
Posted today: | 2 |