gpt4 book ai didi

java - 以 Clojure 格式(java.util.Formatter)、cl 格式(Common Lisp 格式)以编程方式控制填充?

转载 作者:行者123 更新时间:2023-11-30 08:28:27 27 4
gpt4 key购买 nike

有没有办法使用 Clojure format(基于 java.util.Formatter)或 cl-format(基于 Common Lisp 的format) 以编程方式设置空格填充?如果您事先知道所需的宽度,它们都会返回 "foo":

(format "%6s" "foo")
(clojure.pprint/cl-format nil "~6d" "foo")

但是如果我想让程序决定返回的字符串应该有多宽呢?显然我可以手动构造格式字符串,例如:

(def width 6)
(format (str "%" width "s") "foo")

但我想我记得有一个 Common Lisp format 指令可以简单地将格式参数的值插入到格式指令中,然后使用生成的构造指令来处理下一个参数.但是,我还没有在 CL Hyperspec 中找到这样的指令。或 CLTL2 (这并不意味着信息不存在)。到目前为止,我也没有在 java.util.Formatter 文档中发现这样的指令。有没有办法通过任何这些格式化函数/类中的指令来控制指令?

(我不确定我的 cl-format 示例是否应该工作,因为 d 是一个数字格式指令。它在 Clojure 1.5 中工作。 1. 同样的技巧在 CLISP 中使用 format 有效,但在 SBCL、ABCL、CCL 或 ECL 中无效。)

编辑:(我发现左填充字符串的正确方法是将 @ 添加到 a 指令,而不是使用 d :

(clojure.pprint/cl-format nil "~6@a" "foo")

此方法在 Common Lisp 中应始终有效,并且通过在 Clojure 中使用 @a 而不是 d,可以避免将来实现 cl 的风险-format 将使用字符串更改 d 的行为,这是一种无意的使用。)

最佳答案

在Common Lisp中,可以使用v作为前缀参数,例如:

(format nil "~vd" 10 42)

记录在此处:http://clhs.lisp.se/Body/22_c.htm

In place of a prefix parameter to a directive, V (or v) can be used. In this case, format takes an argument from args as a parameter to the directive.

关于java - 以 Clojure 格式(java.util.Formatter)、cl 格式(Common Lisp 格式)以编程方式控制填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20185594/

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