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开发者_如何学JAVA. It needs to be "expanded" out into a list of values.
What is the typical solution to do this problem?
You can use apply
for that: (apply #'format t fstring vars)
expands vars
into separate arguments to format
.
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))
精彩评论