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?
What is the difference between setf and setq? Explanation: Setq is used only for setting the values of symbols but setf can be used for anything. Setf can be used for setting value of any data-type and not only symbols.
(setq var1 form1 var2 form2 ...) is the simple variable assignment statement of Lisp. First form1 is evaluated and the result is stored in the variable var1, then form2 is evaluated and the result stored in var2, and so forth. setq may be used for assignment of both lexical and dynamic variables.
setf is actually a macro that examines an access form and produces a call to the corresponding update function. Given the existence of setf in Common Lisp, it is not necessary to have setq, rplaca, and set; they are redundant. They are retained in Common Lisp because of their historical importance in Lisp.
DEFPARAMETER defines global variable with dynamic scoping. Usual conventions dictate to make such variables easy to distinguish so their name is surrounded by stars. Value for variable is reevaluated for each occurence (unlike with DEFVAR).
If SET and SETQ are to be booted from a Common Lisp successor, they will have to get some replacement. Their use in high-level code is limited, but low-level code (for example, the code SETF is implemented in) needs them. – Svante
6 Answers 6 ActiveOldestVotes 186 Originally, in Lisp, there were no lexical variables -- only dynamic ones. And there was no SETQ or SETF, just the SET function. What is now written as: (setf (symbol-value '*foo*) 42) was written as: (set (quote *foo*) 42)
Then lexical variables happened, and SETQ came to be used for assignment to them too -- so it was no longer a simple wrapper around SET. Later, someone invented SETF (SET Field) as a generic way of assigning values to data structures, to mirror the l-values of other languages: x.car := 42; would be written as (setf (car x) 42)
Originally, in Lisp, there were no lexical variables -- only dynamic ones. And there was no SETQ or SETF, just the SET function. What is now written as: (setf (symbol-value '*foo*) 42)
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With