How can I SETF an element in a tree by an accessor?
Posted
by Willi Ballenthin
on Stack Overflow
See other posts from Stack Overflow
or by Willi Ballenthin
Published on 2010-03-29T06:00:57Z
Indexed on
2010/03/29
6:03 UTC
Read the original article
Hit count: 317
lisp
|common-lisp
We've been using Lisp in my AI course. The assignments I've received have involved searching and generating tree-like structures. For each assignment, I've ended up writing something like:
(defun initial-state ()
(list
0 ; score
nil ; children
0 ; value
0)) ; something else
and building my functions around these "states", which are really just nested lists with some loosely defined structure.
To make the structure more rigid, I've tried to write accessors, such as:
(defun state-score ( state )
(nth 2 state))
This works for reading the value (which should be all I need to do in a nicely functional world. However, as time crunches, and I start to madly hack, sometimes I want a mutable structure). I don't seem to be able to SETF the returned ...thing (place? value? pointer?).
I get an error with something like:
(setf (state-score *state*) 10)
Sometimes I seem to have a little more luck writing the accessor/mutator as a macro:
(defmacro state-score ( state )
`(nth 2 ,state))
However I don't know why this should be a macro, so I certainly shouldn't write it as a macro (except that sometimes it works. Programming by coincidence is bad).
What is an appropriate strategy to build up such structures?
More importantly, where can I learn about whats going on here (what operations affect the memory in what way)?
© Stack Overflow or respective owner