Generic Setter Guild Supply Ship

Lisp Dialect

Common Lisp

Synopsis

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.

image with no caption

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.

How It Kills Bugs

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.

Example A-4. Example

 (defparameter foo (list 1 (make-hash-table) 3))
 (setf (gethash 'my-key (nth foo 1)) 77)

Explanation

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 .

Weakness

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.

image with no caption
image with no caption
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.195.225