Question

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

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:

let foo x = my_print "{integer}" x
Was it helpful?

Solution

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

  • 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

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top