我在(普通)lisp 中看到了两种不同的“输出”函数模式:
(defun implicit ()
(format t "Life? Don't talk to me about life!"))
(defun explicit (stream)
(format stream "This will all end in tears."))
(defun test-im-vs-ex-plicit ()
(values
(with-output-to-string (stream)
(let ((*standard-output* stream))
(implicit)))
(with-output-to-string (stream)
(explicit stream))))
在
implicit
中使用动态范围是否被认为是不好的做法,或者这是动态范围的普遍接受的用法?请注意,我假设这是例如用于构建复杂输出的 DSL,如 HTML、SVG、Latex 或其他任何东西,除了生成打印表示外,预计不会做任何不同的事情。是否有 - 除了风格 - 任何重要的差异,例如关于性能、并发性或其他什么?
最佳答案
其实你可以直接绑定(bind)*standard-output*
:
(defun test-im-vs-ex-plicit ()
(values
(with-output-to-string (*standard-output*) ; here
(implicit))
(with-output-to-string (stream)
(explicit stream))))
没有真正简单的答案。我的建议:
使用流变量,这使得调试更容易。它们出现在参数列表中并且更容易在回溯中发现。否则,您需要在回溯中查看流变量的动态重新绑定(bind)。
a) 没有什么可以通过的?
(defun print-me (&optional (stream *standard-output*))
...)
b) 一个或多个固定参数:
(defun print-me-and-you (me you &optional (stream *standard-output*))
...)
c) 一个或多个固定参数和多个可选参数:
(defun print-me (me
&key
(style *standard-style*)
(font *standard-font*)
(stream *standard-output*))
...)
另请注意:
现在假设
(implicit)
有错误,我们得到一个中断循环,一个调试 repl。这个中断循环中标准输出的值是多少?CL-USER 4 > (defun test ()
(flet ((implicit ()
(write-line "foo")
(cerror "go on" "just a break")
(write-line "bar")))
(with-output-to-string (stream)
(let ((*standard-output* stream))
(implicit)))))
TEST
CL-USER 5 > (compile 'test)
TEST
NIL
NIL
CL-USER 6 > (test)
Error: just a break
1 (continue) go on
2 (abort) Return to level 0.
3 Return to top loop level 0.
Type :b for backtrace or :c <option number> to proceed.
Type :bug-form "<subject>" for a bug report template or :? for other options.
CL-USER 7 : 1 > *standard-output*
#<SYSTEM::STRING-OUTPUT-STREAM 40E06AD80B>
CL-USER 8 : 1 > (write-line "baz")
"baz"
CL-USER 9 : 1 > :c 1
"foo
baz
bar
"
以上是您在 LispWorks 或 SBCL 中看到的内容。在这里,您可以访问真实程序的绑定(bind),但在调试期间使用输出函数会对此流产生影响。
在其他实现中
*standard-output*
将被重新绑定(bind)到实际终端 io - 例如在 Clozure CL 和 CLISP 中。如果您的程序没有重新绑定(bind)
*standard-output*
,那么在这些情况下就会减少混淆。如果我编写代码,我经常会考虑在 REPL 环境中什么会更有用 - 这与语言不同,在 REPL 和中断循环上的交互式调试较少......关于design-patterns - 口齿不清,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30555526/