全部
我想将一个元素更改为格式化字符串,然后我使用 format 函数。 (我使用的语言是scheme)
如http://www.gnu.org/software/mit-scheme/documentation/mit-scheme-ref/Format.html中的文档说,如果我想在右侧插入空格,我可以使用 ~mincolA。
所以我用
(format "~4A " x)
但我收到这样的错误:
format: ill-formed pattern string
explanation: tag `~4' not allowed
pattern string: "~4A "
我想要得到如下结果:
if x is 0, then the result is space space space 0;
if x is 12, then the result is space space 12.
我知道我可以使用
(string-append (make-string (- 4 (string-length x)) #\ ) x)
得到我想要的结果,但我真的想使用“格式”功能。
谢谢。
最佳答案
请注意,引用的文档适用于 MIT/GNU 方案,format
功能在 Racket 中的工作方式有所不同。开箱即用,您可以使用 ~a
具有相同效果的函数:
(~a x #:min-width 4 #:align 'right #:left-pad-string " ") ; x can be a number or a string
例如:
(~a 0 #:min-width 4 #:align 'right #:left-pad-string " ")
=> " 0"
(~a "12" #:min-width 4 #:align 'right #:left-pad-string " ")
=> " 12"
如果您不介意导入额外的外部库,@uselpa 的答案是正确的。
关于使用格式的方案完整填充示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25449761/