惊喜打印到字符串(常见的lisp)

时间:2016-03-12 22:36:01

标签: common-lisp

遵循WITH-OUTPUT-TO-STRING和。{的文档 GET-OUTPUT-STREAM-STRING,我希望以下内容能够正常运行,并且确实如此:

(print
 (with-output-to-string (sb nil)
   (format sb "~A " "hello, ")
   (format sb "~A~&" "world")
   sb))

(print
 (let ((sb (make-string-output-stream)))
   (format sb "~A " "hello, ")
   (format sb "~A~&" "world")
   (get-output-stream-string sb)))

但是,以下是接近其中一个例子的 WITH-OUTPUT-TO-STRING,不会:

(print
 (with-output-to-string (sb (make-array
                             '(0)
                             :element-type 'base-char
                             :fill-pointer 0
                             :adjustable t))
   (format sb "~A " "hello, ")
   (format sb "~A~&" "world")
   sb))

生成输出流本身,而不是生成的字符串:

#<SB-IMPL::FILL-POINTER-OUTPUT-STREAM {1005FBE523}>

我无法找到在输出中提取字符串的方法 流。我怀疑它与动态范围有关,但是我的 在这里理解踌躇不前

显然,我有更好的方法来达到预期的效果,所以我只是 好奇地发现我对语言的误解。

因为文档说明结果未定义 由MAKE-STRING-OUTPUT-STREAM创建的流上的GET-OUTPUT-STREAM-STRING 以下不起作用我并不感到惊讶:

(print
 (with-output-to-string (sb (make-array
                             '(0)
                             :element-type 'base-char
                             :fill-pointer 0
                             :adjustable t))
   (format sb "~A " "hello, ")
   (format sb "~A~&" "world")
   (get-output-stream-string sb)))

但我仍然很感激找到一种方法来提取我的第三个字符串 示例

1 个答案:

答案 0 :(得分:7)

请注意WITH-OUTPUT-TO-STRING以两种不同的方式返回值:

  1. 如果你没有提供字符串或NIL,那么它会创建一个字符串并将其返回。
  2. 如果你给它一个字符串,那么它会返回最后一个正文表格的结果值。
  3. 您的代码:

    (print
     (with-output-to-string (sb (make-array   ; creates a string
                                 '(0)
                                 :element-type 'base-char
                                 :fill-pointer 0
                                 :adjustable t))
       (format sb "~A " "hello, ")
       (format sb "~A~&" "world")
       sb)   ; you return the stream (which makes not much sense), but not the string
       )
    

    您已通过调用MAKE-ARRAY创建了一个字符串。它就是。用它。为此,您通常需要将其绑定到某个变量。

    示例如何返回字符串:

    (let ((s (make-array '(0)
                         :element-type 'base-char
                         :fill-pointer 0
                         :adjustable t)))
      (with-output-to-string (sb s)
        (format sb "~A " "hello, ")
        (format sb "~A~&" "world"))
      s)
    

    (let ((s (make-array '(0)
                         :element-type 'base-char
                         :fill-pointer 0
                         :adjustable t)))
      (with-output-to-string (sb s)
        (format sb "~A " "hello, ")
        (format sb "~A~&" "world")
        s))
    

    在最后一种情况下,with-output-to-string返回值,因为它有一个字符串,用作输出的目标。