Question

Is there a widely-accepted Common Lisp naming convention for functions modifying one or more of their arguments?

In CL, we have incf and setf imperative functions. Scheme uses an exclamation point (e.g. set!, vector-set! etc.) But what, if any, convention do CL programmers use?

 3  117  3
1 Jan 1970

Solution

 5

There isn't a common convention. The Google Common Lisp Style Guide (one useful CL style resource) doesn't have anything to say about it.

Common Lisp does have a convention of prefixing some variations of library functions that modify their arguments with an n, e.g., nconc, nbutlast, nreverse, nsubstitute, etc. These functions are understood to be "non-consing" as they modify their list arguments instead of consing up new nodes. It might make sense to adopt this as a convention and it would be generally understood.

You could use an exclamation point and that would probably be generally clear, but some would frown on this practice. The ! character is reserved to the programmer by the Common Lisp standard. Yet this could bite you, e.g., if you are using a library that has used ! to define a reader macro (which was the original intention behind reserving this and several other characters).

setf Functions

With functions like set! or vector-set! the goal appears to be to mutate some data type. What is pretty common practice is to write some sort of setf function to allow you to work with the data type using setf easily, and making it clear that you are mutating the data.

For example, you can do something like this:

CL-USER> (defvar xs (list 1 2 3))
XS

CL-USER> (defun (setf mid) (x thing)
           (setf (cadr thing) x)
           thing)
(SETF MID)

CL-USER> xs
(1 2 3)

CL-USER> (setf (mid xs) 42)
(1 42 3)

CL-USER> xs
(1 42 3)

Here a function named (setf mid) has been defined which can be used in a place form as described here. You can write setf functions this way, or using defsetf, or you can use define-setf-expander to control how setf works.

2024-06-29
ad absurdum