Type F # output in format strings

How is it possible for F # to check format strings at compile time to determine that x is of type int in the following definition?

let foo x = sprintf "%d" x`? 

Is it hardcoded in the language, or can someone write their own function "my_print" that uses format strings with different syntax? For instance:

 let foo x = my_print "{integer}" x 
+4
source share
2 answers

You can read a little about it in 6.4.17 formats ('printf') here , but briefly

  • it is built into the language
  • string literals can effectively "force" into the weird type "Format"
  • printf and friends expect the first argument of type Format, which leads to coercion

As a result, you can create your own printf-style functions, but you must use the same% s formats as this material is embedded.

+3
source

Here is an example of how you can create your own printf style functions in F #. You cannot change format specifiers (for example, "% d"), but you can use existing specifiers to create additional string formatting functions that the compiler will print to the screen.

+3
source

All Articles