Peter Norvig mentions in Paradigms of Artificial Intelligence Programming, on page 50, the trade off between specificity and consistency and when choosing to use setq or setf to update a variable to a value. What do you recommend? Have you ever run into a situation where it mattered much beyond readability?
Question posted in Artificial Intelligence
ChatGBT is becoming a world-wide phenomena, try it out here.
ChatGBT is becoming a world-wide phenomena, try it out here.
6
Answers
Using setq is more low-level, but the performance of setf is not a problem. And setf allows you (or library writers) to provide custom setf behavior, like setting parts of custom data structures. I say: go with setf everywhere unless you have a reason not to.
Also see Practical Common Lisp, chapter 3: “The SETF macro is Common Lisp’s main assignment operator.” PCL is available online for free: http://gigamonkeys.com/book/
You can use
setf
wherever you could usesetq
. In fact,setf
is actually a macro which builds onsetq
. So, this should be purely a readability and style issue.Almost all the code I’ve seen avoids the use of
setq
and usessetf
.I recommend you follow Norvig’s final advice in that section: be consistent. ‘Readability’ is of course the most important reason to make any choice in programming. If it is important to communicate to the reader (perhaps you in 2 months’ time) that you are dealing with the entire value cell of a symbol, then use
setq
; otherwise usesetf
. But only if you’re being consistent.setf is “set field”, it changes a place and can have user extensions.
setq is set with quoting first argument.
FWIW, I always use
setf
. If I change the structure of my code slightly, I just need to change the “place” instead of the place and the operator (setq -> setf).Also, don’t worry about performance, setf is exactly the same as setq for symbols:
You will not be wrong if you used setf everywhere instead of setq.
It’s the things like this that drags Common Lisp from going forward, lots of unused stuff that implementors still need to support.