fslang-suggestions icon indicating copy to clipboard operation
fslang-suggestions copied to clipboard

Support strings marked as literals in print functions

Open eugbaranov opened this issue 7 years ago • 4 comments

Currently string literals are automatically converted to TextWriterFormat even if you mark it with {Literal} attribute:

[<Literal>]
let format = "Test %d"
// The type 'string' is not compatible with the type 'Printf.TextWriterFormat<('a -> 'b)>'
printfn format 1

This is in somewhat inconsistent with type providers since they allow using string literals:

[<Literal>]
let sample = """{"x":1}"""
type Test = JsonProvider<sample>

Pros and Cons

Advantages

More consistency in where literal strings can be used

Disadvantages

Additional complexity in the compiler

Extra information

Estimated cost (XS, S, M, L, XL, XXL): S

Affidavit (please submit!)

Please tick this by placing a cross in the box:

  • [x] This is not a question (e.g. like one you might ask on stackoverflow) and I have searched stackoverflow for discussions of this issue
  • [x] I have searched both open and closed suggestions on this site and believe this is not a duplicate
  • [x] This is not something which has obviously "already been decided" in previous versions of F#. If you're questioning a fundamental design decision that has obviously already been taken (e.g. "Make F# untyped") then please don't submit it.

Please tick all that apply:

  • [x] This is not a breaking change to the F# language design
  • [x] I or my company would be willing to help implement and/or test this

eugbaranov avatar Jan 24 '18 13:01 eugbaranov

Just as a note, it is possible to use format strings at runtime, in all its unsafe glory:

let fmt = "Test %d"

let fmt_of_string s = new PrintfFormat<_, _, _, _>(s)

do
  let fmt' = fmt_of_string fmt
  printf fmt' 1

...but a malformed format string or mismatched printf arguments to a well-formed format string will raise an exception.

drvink avatar Nov 28 '18 22:11 drvink

I'd definitely support this. Seems like a straightforward addition.

cartermp avatar Nov 28 '18 22:11 cartermp

Yes we should really support this.

BTW there is also a fairly simple type provider extension we could make to support a generalisation of the type-directed string - - > Print Formatconversion, for any user-defined type-analysed DSL without needing RegExp<"...">

dsyme avatar Nov 28 '18 23:11 dsyme

I think the type provider approach would be awesome, as we could use that with resources. I've always struggled with a good approach F# style with resources, and using them with a type provider seems very idiomatic, and would allow for type safety in parameterized resource strings.

abelbraaksma avatar Nov 28 '18 23:11 abelbraaksma