我正在以 Common Lisp 语言的风格编写漂亮的打印代码。虽然我有直觉认为可以使用格式指令编写更紧凑的代码,但我仍然没有成功这样做,所以我正在分享我的例子,我问是否有人能够编写具有相同语义的格式指令。
CL-USER> (let ((properties
'(:a "the letter a" :b "the letter b"
:a-property-with-a-long-key "and a very long value")))
(pprint-logical-block (nil properties :prefix "(" :suffix ")")
(loop (write-char #\()
(pprint-indent :block 1)
(write (pprint-pop))
(write-char #\Space)
(pprint-newline :linear)
(write (pprint-pop))
(write-char #\))
(pprint-exit-if-list-exhausted)
(pprint-indent :block 0)
(write-char #\Space)
(pprint-newline :linear))))
;; Ouput
((:A
"the letter a")
(:B
"the letter b")
(:A-PROPERTY-WITH-A-LONG-KEY
"and a very long value"))
;; Return value
NIL
(上面的代码肯定比尚未找到的格式指令替换它更容易理解。但是,在临时生成代码时,格式指令会非常有用。)
尝试这样的事情:
(let ((properties '(:a "the letter a"
:b "the letter b"
:a-property-with-a-long-key "and a very long value")))
(format t "(~{(~s~& ~s)~^~&~@{ (~s~& ~s)~^~&~}~})" properties))
输出:
((:A
"the letter a")
(:B
"the letter b")
(:A-PROPERTY-WITH-A-LONG-KEY
"and a very long value"))
使用的指令:
~{...~}
迭代列表的元素~@{...~}
迭代列表中的剩余元素~s
打印元素 (= (write (pprint-pop))
)~&
打印条件换行 (= pprint-newline
)(用 ~%
替换为无条件换行)~^
则停止 (= pprint-exit-if-list-exhausted
)