How is it possible for F# to examine format strings at compile time to determine that x has type int in the following definition?
如何在编译时检查格式字符串以确定x在以下定义中是否具有int类型?
let foo x = sprintf "%d" x`?
Is this hard-coded into the language or could somebody write their own "my_print" function that uses format strings with a different syntax? For example:
这是硬编码到语言中还是有人可以编写自己的“my_print”函数,它使用不同语法的格式字符串?例如:
let foo x = my_print "{integer}" x
2 个解决方案
#1
You can read a bit about it in 6.4.17 ('printf' formats) here, but briefly
您可以在这里阅读6.4.17('printf'格式)中的一些内容,但简要介绍一下
- it's built into the language
- string literals can effectively be 'coerced' into the weird 'Format' type
- printf and friends expect a first argument of the Format type, making the coercion happen
它内置于语言中
字符串文字可以有效地“强制”为奇怪的“格式”类型
printf和朋友期待格式类型的第一个参数,使强制发生
The net result is that you can build your own printf-style functions, but must use the same %s formats, since that stuff is built-in.
最终结果是您可以构建自己的printf样式函数,但必须使用相同的%s格式,因为这些内容是内置的。
#2
Here is an example of how you can build your own printf-style functions in F#. You can't change the format specifiers (e.g. "%d"), but you can leverage the existing specifiers to build additional string formatting functions that the compiler will type check.
以下是如何在F#中构建自己的printf样式函数的示例。您无法更改格式说明符(例如“%d”),但您可以利用现有的说明符来构建编译器将键入的其他字符串格式化函数。
#1
You can read a bit about it in 6.4.17 ('printf' formats) here, but briefly
您可以在这里阅读6.4.17('printf'格式)中的一些内容,但简要介绍一下
- it's built into the language
- string literals can effectively be 'coerced' into the weird 'Format' type
- printf and friends expect a first argument of the Format type, making the coercion happen
它内置于语言中
字符串文字可以有效地“强制”为奇怪的“格式”类型
printf和朋友期待格式类型的第一个参数,使强制发生
The net result is that you can build your own printf-style functions, but must use the same %s formats, since that stuff is built-in.
最终结果是您可以构建自己的printf样式函数,但必须使用相同的%s格式,因为这些内容是内置的。
#2
Here is an example of how you can build your own printf-style functions in F#. You can't change the format specifiers (e.g. "%d"), but you can leverage the existing specifiers to build additional string formatting functions that the compiler will type check.
以下是如何在F#中构建自己的printf样式函数的示例。您无法更改格式说明符(例如“%d”),但您可以利用现有的说明符来构建编译器将键入的其他字符串格式化函数。