Lisp – Print out () instead of nil for empty list

Two possible solutions:

I. You can use the format directives ~:A or ~:S

(format t "~:a" '()) => ()

However, this directive works only on the top level elements of a list, i.e.

(format t "~:a" '(a b () c))

will not print (A B () C)

but (A B NIL C)

So you need to loop through the list applying the ~:A to each element recursively if it is a cons.

(defun print-parentheses (l)
  (cond ((consp l) (format t "(")
              (do ((x l (cdr x)))
                  ((null x) (format t ")" ))
                (print-parentheses (car x))
                (when (cdr x) (format t " "))))
        (t (format t "~:a" l)) ))


(print-parentheses '(a b (c () d))) => (A B (C () D))

II. Create a print-dispatch function for empty lists and add it to the pretty print dispatch table:

(defun print-null (stream obj)
  (format stream "()") )

(set-pprint-dispatch 'null #'print-null)

(print '(a () b)) => (A () B) 

The latter is simpler, but it affects all the environment, which might not be what you want.

Leave a Comment