Paul Nathan
Paul Nathan

Reputation: 40319

Expanding a &rest parameter in Common Lisp

Suppose I get tired of writing "format t ..." all the time, and want something a little fewer keystrokes.

So I write this:

(defun puts (fstring &rest vars)
  (format t fstring vars))

(puts "~a ~a" 1 2)

;; error message results, because vars became (1 2)

Now, vars has been transformed into a list of whatever params I passed in. It needs to be "expanded" out into a list of values.

What is the typical solution to do this problem?

Upvotes: 7

Views: 1215

Answers (2)

Rörd
Rörd

Reputation: 6681

Besides apply, there also the possibility to do this with a macro in which you can use ,@ to splice lists inside backquotes:

(defmacro puts (fstring &rest vars)
  `(format t ,fstring ,@vars))

Upvotes: 2

Jeremiah Willcock
Jeremiah Willcock

Reputation: 30999

You can use apply for that: (apply #'format t fstring vars) expands vars into separate arguments to format.

Upvotes: 11

Related Questions