gpt4 book ai didi

loops - 从循环内的格式返回

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

我是一个 Lisp 新手,在理解 loopformat 组合时如何工作时有些困难。

这如我所料:

(loop for i upto 2 do (format t "~a""Badger")) ==>
獾獾獾

这不是:

(循环我最多 2 次(格式为 nil "~a""Badger"))==>

为什么第二个循环不返回 BadgerBadgerBadger ?我必须写什么代码才能给出这个返回值?

最佳答案

返回值和打印值之间有一个重要的区别。有时这在 REPL 中会造成混淆,因为默认情况下会打印返回值:

CL-USER> (+ 1 1)    ; form *returns* 2
2 ; and return value (2) is printed
CL-USER> (let ()
(+ 1 1) ; (+ 1 1) still returns 2, but
nil) ; the return value of the (let ...) is NIL
NIL ; so NIL is printed

现在,格式可以做一些不同的事情,这取决于它的第一个参数。如果它的第一个参数是 t 或一个流,那么它会将输出写入流并返回 nil:

CL-USER> (format t "hello")
hello ; printed output
NIL ; return value from format

CL-USER> (let ()
(format t "hello") ; will print "hello"
42) ; but the whole form returns 42
hello ; printed output
42 ; printed return value

当使用 nil 作为第一个参数调用 format 时,它会返回它生成的字符串形式的输出:

CL-USER> (format nil "hello")
"hello" ; return value, not printed output

CL-USER> (let ()
(format nil "hello") ; returns "hello"
42) ; but the whole form returns 42
42 ; printed return value

现在,您可以从循环中收集结果,听起来您想使用格式生成一个字符串,然后收集这些字符串:

CL-USER> (loop for i upto 2 collect i)
(0 1 2)

CL-USER> (loop for i upto 2 collect (* 8 i))
(0 8 16)

CL-USER> (loop for i upto 2 collect (format nil "string number ~a" i))
("string number 0" "string number 1" "string number 2")

关于loops - 从循环内的格式返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31190177/

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