skip to Main Content

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?

6

Answers


  1. 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/

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
  4. setf is “set field”, it changes a place and can have user extensions.
    setq is set with quoting first argument.

    Login or Signup to reply.
  5. 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)
    
    Login or Signup to reply.
  6. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search