views:

941

answers:

6

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?

+7  A: 

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/

Harold L
+4  A: 

You can use setf wherever you could use setq. In fact, setf is actually a macro which builds on setq. So, this should be purely a readability and style issue.

Almost all the code I've seen avoids the use of setq and uses setf.

Ville Laurikari
A: 

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 use setf. But only if you're being consistent.

A: 

setf is "set field", it changes a place and can have user extensions. setq is set with quoting first argument.

Anton Kazennikov
+2  A: 

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:

CL-USER> (macroexpand '(setf foo 42))
(SETQ FOO 42)
jrockway
A: 

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.

Dev er dev
I object to the second sentence. SETF is a convenient abstraction over several assignment constructs, one of which is SETQ. You cannot implement SETF without having SETQ.
Svante
2Svante: but it's hard to imagine situations where you'd need to use setq instead of setf.
Anton Kazennikov
That's not the point -- no one uses TAGBODY and GO in high level code, either, but the implementations of many common constructs depend on them.
Svante