列表中每三个单词后面的换行符,格式为cl:format
如何在列表中每三个参数后添加回车符(使用列表中每三个单词后面的换行符,格式为cl:format,format,lisp,common-lisp,Format,Lisp,Common Lisp,如何在列表中每三个参数后添加回车符(使用~%) 例如,我现在有: (format nil "~{~a ~}" (list '"one" '"two" '"three" '"four" '"five" '"six" '"seven" '"eight" '"nine" '"ten")) ;=> "one two three four five six seven eight nine ten " 但我想: ;=> "one two three ; four five six
~%
)
例如,我现在有:
(format nil "~{~a ~}" (list '"one" '"two" '"three" '"four" '"five" '"six" '"seven" '"eight" '"nine" '"ten"))
;=> "one two three four five six seven eight nine ten "
但我想:
;=> "one two three
; four five six
; seven eight nine
; ten "
~{str~}
中的格式字符串str
可以在每次迭代中使用列表中的多个参数。这意味着,如果有一个参数列表保证可以被3整除,那么可以使用类似~{~a~a~a~%}
的格式字符串。下面是一个例子:
CL-USER> (format nil "~{~a ~a ~a~%~}" '(1 2 3 4 5 6))
"1 2 3
4 5 6
"
不过,您可能有许多不能被三整除的参数,在这种情况下,您需要提前终止迭代。如果没有更多参数,可以使用format指令~^
中断。由于在第一个或第二个参数之后可能会出现这种情况,因此应该在这些位置之后添加一个参数。以下是具有零、一和两个尾随参数的情况的示例:
CL-USER> (format nil "~{~a~^ ~a~^ ~a~%~}" '(1 2 3 4))
"1 2 3
4"
CL-USER> (format nil "~{~a~^ ~a~^ ~a~%~}" '(1 2 3 4 5))
"1 2 3
4 5"
CL-USER> (format nil "~{~a~^ ~a~^ ~a~%~}" '(1 2 3 4 5 6))
"1 2 3
4 5 6
"
当元素数可以被3整除时,您可能不希望看到最后的换行符,在这种情况下,您也可以在换行符之前添加一个~^
:
CL-USER> (format nil "~{~a~^ ~a~^ ~a~^~%~}" '(1 2 3 4 5 6))
"1 2 3
4 5 6"
这种构造特别适合于编写分隔列表:
CL-USER> (format nil "write(~{~a~^,~})" '("fd" "buf" "count"))
"write(fd,buf,count)"
这些格式指令(及其变体)在HyperSpec中有更详细的描述(链接页面中的内容比此处引用的内容更多):
{str}
这是一个迭代构造。参数应该是一个列表,其中
用作一组参数,就像对的递归调用一样。
字符串str被反复用作控制字符串。每个
迭代可以吸收尽可能多的列表元素
论据;如果str本身使用了两个参数,那么两个元素
在循环中,每次都会用完列表中的一部分。如果有的话
迭代步骤列表为空,则迭代终止。
此外,如果给定前缀参数n,则最多有n个
重复str的处理。最后,~^
指令可以
用于提前终止迭代
您可能还对以下问题感兴趣:
(格式t“hello there~cj”#\return)
后,我在屏幕上看到jello there
,但在(格式t“hello there~cj”#\newline)
后,我看到两行,第一行是hello there
,第二行是j
。感谢您的详细回复。