有时我喜欢用(format t ..)
输出一些文本。
为了防止源代码中长而不可读的格式字符串,并使输出容易对齐,我使用(format t (concatenate 'string ....)
。
的例子:
(format t (concatenate 'string
"some output~%"
" error-msg: ~a~%"
" uiop-cwd: ~a~%"
" uiop-file-exists: ~a~%")
"error foo"
(uiop:getcwd)
(uiop:file-exists-p "hello_world.bmp"))
在Common Lisp中是否有更习惯的和编译时的方法来做同样的事情?
下面是一个等效的格式字符串,它使用了Tilde换行符格式指令,忽略了下面的换行符和空格(直到下一个可见字符)。为了像你那样用空格缩进,我在空格前写了强制换行符~%
:
(format t
"some output~
~% error-msg: ~a~
~% uiop-cwd: ~a~
~% uiop-file-exists: ~a~%"
"error foo"
(uiop:getcwd)
(uiop:file-exists-p "hello_world.bmp"))
(NB。这是一个单独的字符串,所以在编译时不需要进行连接。)
你可以做得很好:
(defun fmt (to control/s &rest args-to-format)
(declare (dynamic-extent args-to-format)) ;?OK
(apply #'format to (if (listp control/s)
(apply #'concatenate 'string control/s)
control/s)
args-to-format))
(define-compiler-macro fmt (&whole form to control/s &rest args-to-format)
(cond
((stringp control/s)
`(format ,to ,control/s ,@args-to-format))
((and (listp control/s)
(eql (first control/s) 'quote))
;; literal
(destructuring-bind (_ thing) control/s
(declare (ignore _))
(print "here")
(if (and (listp thing) (every #'stringp thing))
`(format ,to ,(apply #'concatenate 'string thing) ,@args-to-format)
form)))
(t
form)))
编译器宏应该确保
的通用大小写(fmt t '("~&foo: ~S~%"
"bar~%") ...)
将完全没有运行时成本。