I have a problem with modifying entries of an association list. When I run this code
Example A
(set 'Dict '(("foo" "bar")))
(letn (key "foo"
entry (assoc key Dict))
(setf (assoc key Dict) (list key "new value")))
(println Dict)
the result is:
(("foo" "new value")) ; OK
which is expected. With this code
Example B
(set 'Dict '(("foo" "bar")))
(letn (key "foo"
entry (assoc key Dict))
(setf entry (list key "new value"))) ; the only change is here
(println Dict)
the result is:
(("foo" "bar")) ; huh?
Why the Dict
is not being updated in the second case?
Edit
What I want is to check if an entry is in the Dict
and if it is - update it, otherwise leave it alone. With letn
I want to avoid a duplicated code
(letn (key "foo"
entry (assoc key Dict))
(if entry ; update only if the entry is there
(setf entry (list key "new value")))
In the letn expression the variable entry contains a copy of the association not a reference. Set the association directly as shown in Cormullion's example:
(setf (assoc key Dict) (list key "new value"))
In the newLISP programming model everything can be referenced only once. Assignment always makes a copy.