common-lispsbcl

Circumflex in format of lists


This works:

(format nil "~{~a~^,~}" '(1 2 3))  ; => "1,2,3"
(format nil "~{~a=~a~^,~}" '(a 1 b 2 c 3)) ; => "A=1,B=2,C=3"

But in this example the circumflex suppresses everything:

(format nil "~:{~a=~a~^,~}" '((a 1) (b 2) (c 3))) ; => "A=1B=2C=3"

Why and how to fix it?


Solution

  • You need to nest iterations so that the inner iteration works over the parameters and the outer iteration works over the lists of parameters. Then the outer iteration can be escaped to suppress printing the final comma:

    * (format nil "~{~{~A=~A~}~^, ~}" '((a 1) (b 2) (c 3)))
    "A=1, B=2, C=3"