Marco Antoniotti's blog on Lisp and other interesting bits of programming.

20110225

:constructor tricks

Every once in a while I discover things in CL that somehow I had not thought about before. They have been there sometimes since CLtL1 but, somehow, I did not register them before. (I am slow, I know; and I am not claiming that this is anything new. But this is the Internet :) )

Fancy :constructor uses are one of these things.

Suppose you wanted to construct a immutable tree node structure which recorded the height of the sub-tree upon construction. Here is an iteration of what you may do.

(defstruct node
(height 0)
left
right)

Now you need to create the constructor for nodes. Not worrying about nil nodes, you may start by doing the obvious (assuming a max* function capable of dealing with nil values):