What's the canonical way to join strings in a list?

Use FORMAT.

~{ and ~} denote iteration, ~A denotes aesthetic printing, and ~^ (aka Tilde Circumflex in the docs) denotes printing the , only when something follows it.

* (format nil "~{~A~^, ~}" '( 1 2 3 4 ))

"1, 2, 3, 4"
* 

This solution allows us to use FORMAT to produce a string and to have a variable delimiter. The aim is not to cons a new format string for each call of this function. A good Common Lisp compiler also may want to compile a given fixed format string - which is defeated when the format string is constructed at runtime. See the macro formatter.

(defun %d (stream &rest args)
  "internal function, writing the dynamic value of the variable
DELIM to the output STREAM. To be called from inside JOIN."
  (declare (ignore args)
           (special delim))
  (princ delim stream))

(defun join (list delim)
  "creates a string, with the elements of list printed and each
element separated by DELIM"
  (declare (special delim))
  (format nil "~{~a~^~/%d/~:*~}" list))

Explanation:

"~{      iteration start
 ~a      print element
 ~^      exit iteration if no more elements
 ~/%d/   call function %d with one element
 ~:*     move one element backwards
 ~}"     end of iteration command

%d is just an 'internal' function, which should not be called outside join. As a marker for that, it has the % prefix.

~/foo/ is a way to call a function foo from a format string.

The variables delim are declared special, so that there can be a value for the delimiter transferred into the %d function. Since we can't make Lisp call the %d function from FORMAT with a delimiter argument, we need to get it from somewhere else - here from a dynamic binding introduced by the join function.

The only purpose of the function %d is to write a delimiter - it ignores the arguments passed by format - it only uses the stream argument.


Melpa hosts the package s ("The long lost Emacs string manipulation library"), which provides many simple string utilities, including a string joiner:

(require 's)                                                                                                                                                                                          
(s-join ", " (list "a" "b" "c"))                                                                                                                                                                      
"a, b, c"

For what it's worth, very thinly under the hood, it's using a couple lisp functions from fns.c, namely mapconcat and identity:

(mapconcat 'identity (list "a" "b" "c") ", ")                                                                                                                                                         
"a, b, c"

Tags:

Common Lisp