使用命名参数的Lisp字符串格式 [英] Lisp string formatting with named parameters

查看:102
本文介绍了使用命名参数的Lisp字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Lisp中是否可以使用命名参数格式化字符串?

Is there a way in Lisp to format a string using named parameters?

也许带有关联列表的东西

Perhaps something with association lists like

(format t "All for ~(who)a and ~(who)a for all!~%" ((who . "one")))

以打印"All for one and one for all".

类似于此python问题,或 c ++ ,但使用Lisp.

Similar to this python question, or this scala one, or even c++, but in Lisp.

如果该功能不是该语言所提供的,那么是否有人拥有可以完成相同任务的出色功能或宏?

If this functionality isn't in the language, does anyone have any cool functions or macros that could accomplish the same thing?

推荐答案

使用 CL-INTERPOL

(cl-interpol:enable-interpol-syntax)

字符串插值

对于简单的情况,您不需要 FORMAT :

String interpolation

For simple cases, you don't need FORMAT:

(lambda (who) #?"All for $(who) and $(who) for all!")

然后:

(funcall * "one")
=> "All for one and one for all!"

解释格式指令

如果需要格式化,可以执行以下操作:

Interpret format directives

If you need to format, you can do:

(setf cl-interpol:*interpolate-format-directives* t)

例如,该表达式:

(let ((who "one"))
  (princ #?"All for ~A(who) and ~S(who) for all!~%"))

...打印:

All for one and "one" for all!

如果您感到好奇,则上面的读为为:

If you are curious, the above reads as:

(LET ((WHO "one"))
  (PRINC
    (WITH-OUTPUT-TO-STRING (#:G1177)
      (WRITE-STRING "All for " #:G1177)
      (FORMAT #:G1177 "~A" (PROGN WHO))
      (WRITE-STRING " and " #:G1177)
      (FORMAT #:G1177 "~S" (PROGN WHO))
      (WRITE-STRING " for all!" #:G1177))))

备用阅读器功能

以前,我全局设置了*interpolate-format-directives*,它解释所有内插字符串中的格式指令. 如果您想精确地控制何时插入格式指令,则不能仅将变量临时绑定到代码中,因为魔术是在读取时发生的.相反,您必须使用自定义阅读器功能.

Alternate reader function

Previously, I globally set *interpolate-format-directives*, which interprets format directive in all interpolated strings. If you want to control precisely when format directives are interpolated, you can't just bind the variable temporarily in your code, because the magic happens at read-time. Instead, you have to use a custom reader function.

(set-dispatch-macro-character
 #\#
 #\F
 (lambda (&rest args)
   (let ((cl-interpol:*interpolate-format-directives* t))
     (apply #'cl-interpol:interpol-reader args))))

如果我将特殊变量重置为其默认值NIL,则格式化指令的字符串以#F为前缀,而普通内插的字符串则使用#?语法.如果要更改可读取的表,请查看已命名的可读取表.

If I reset the special variable to its default value NIL, then strings where directives are formatted are prefixed with #F, whereas normal interpolated ones use the #? syntax. If you want to change readtables, have a look at named readtables.

这篇关于使用命名参数的Lisp字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆