gpt4 book ai didi

format - cl :format 列表中每三个单词后换行

转载 作者:太空宇宙 更新时间:2023-11-03 18:37:15 26 4
gpt4 key购买 nike

如何在列表中的每三个参数后添加一个回车符(使用 ~%)?
例如,我现在:

(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 可以在每次迭代中用完列表中的多个参数。这意味着如果您有一个保证可以被三整除的参数列表,您可以使用像 ~{~a ~a ~a~%~} 这样的格式字符串。这是一个例子:

CL-USER> (format nil "~{~a ~a ~a~%~}" '(1 2 3 4 5 6))
"1 2 3
4 5 6
"

不过,您可能有许多不能被三整除的参数,在这种情况下,您需要提前终止迭代。如果没有更多参数,您可以使用格式指令 ~^ 来中断。由于在第一个或第二个参数之后您可能会遇到这种情况,因此您应该在这些地方之后添加其中一个。以下是带有零个、一个和两个尾随参数的示例:

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
"

当元素的数量可以被三整除时,您可能不想要最后的换行符,在这种情况下,您也可以在换行符之前添加一个~^:

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 中有更详细的描述(链接页面中的内容比此处引用的内容更多):

22.3.7.4 Tilde Left-Brace: Iteration

~{str~}

This is an iteration construct. The argument should be a list, which is used as a set of arguments as if for a recursive call to format. The string str is used repeatedly as the control string. Each iteration can absorb as many elements of the list as it likes as arguments; if str uses up two arguments by itself, then two elements of the list will get used up each time around the loop. If before any iteration step the list is empty, then the iteration is terminated. Also, if a prefix parameter n is given, then there will be at most n repetitions of processing of str. Finally, the ~^ directive can be used to terminate the iteration prematurely.

您可能还对这些问题感兴趣:

关于format - cl :format 列表中每三个单词后换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19522348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com