lisp - 打印带有中缀符号的列表

标签 lisp common-lisp

我想使用 format 将 s-expression 转换为带有中缀符号的字符串。如何使用 format 完成此操作?

例子;

(format t "<insert format controls here>" (1 2 3) '*)
=> "1 * 2 * 3"

最佳答案

此答案包含错误代码。

简单,只需使用 custom formatters :

(format t "~/acquire/~/disseminate/" '(1 2 3) '*)

它们的定义如下:

(let ((memory))
  (defun cl-user::acquire (stream list &optional colonp atsignp)
    (declare (ignore colonp atsignp stream))
    (setf memory list))
  (defun cl-user::disseminate (stream operator &optional colonp atsignp)
    (declare (ignore colonp atsignp))
    (format stream (concatenate 'string "~{~a~^ " (string operator) " ~}") memory)
    (setf memory nil)))

例如:

CL-USER> (format t "~/acquire/~/disseminate/" '(1 2 3) '*)
1 * 2 * 3

memory 变量在两个函数的词法范围内,这使它们能够进行数据通信。第一个存储列表,第二个使用它。如果您从不调用第二个函数(或第一个函数为 nil),memory永远绑定(bind)到最后一个列表,这可能是个问题。另请注意,您可能会遇到并发问题。 坦率地说,这不是做你想做的最好的方法,但它可以完成工作 w.r.t.您的要求。

关于lisp - 打印带有中缀符号的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56585956/

相关文章:

lisp - 在 (loop ...) 中使用反引号/逗号成语是否正确?

lisp - Common Lisp 对象系统 (CLOS) 是否支持 duck-typing?

lisp - 如何创建结构的深拷贝

compilation - 关于Common Lisp编译顺序的问题

overflow - Wumpus游戏的make-city-edges函数导致堆溢出

lisp - 如何将两个相似的函数合并为一个函数

lisp - Common Lisp 未绑定(bind)变量

debian - 在 Debian 上使用 SLIME 在 Common Lisp 中加载外部包

common-lisp - 普通 lisp 中的这些命名从何而来?

macos - 在 Mac OS X(任何方言)上安装 lisp 的建议?