To modify the value of a variable in Common Lisp, you use setf
. However, this command also has an amazing special power: Instead of a variable name, you can pass it a complex Lisp expression that retrieves a value. It can then turn that expression “inside out” and use it to modify that value, rather than simply retrieve it. These types of expressions are called generic setters.
Many commands besides setf
also support generic setters. Using this feature, most types of data structures can get by without any specific “setting” functions of their own.
When you have a complicated, nested data structure, it’s often easier to understand code that retrieves data from a specific location than it is to understand code that sets a value at the same location. If you want to set a value at a specific location in a complicated structure, you usually need to work backward through the structure to figure out how to change it. But with generic setters, you can let Lisp handle the hard code for you. Having simpler code is a great way to fight bugs.
The example creates a variable named foo
, which holds a list of three items . The second item in the list is an empty hash table. Then it adds a key named my-key
with a value of 77
to the table inside foo
all at once, by putting a complex expression into setf
that “gets at” this location .
By mutating an existing data structure, generic setters cause a side effect, which violates one of the tenets of functional programming. This means they can’t be used when programming in a purely functional style.
Generic setters are discussed in Chapter 9.
3.140.195.225