Search code examples
f#printfunit-type

ksprintf type error when using dynamic string


The sample code:

Printf.ksprintf ignore "static string"

let dynamicString = Printf.StringFormat<unit>("dynamic string")
Printf.ksprintf ignore dynamicString // <- error

When I pass a static string to ksprintf everything works fine. But if I form a string dynamically, a compilation error shows up:

The type 'unit' does not match the type 'string'

P.S. Found in the sources of FSharp.Core:

/// <summary>Represents a statically-analyzed format when formatting 
/// arguments of the format operation and the last the overall return type.</summary>
type StringFormat<'T,'Result> = Format<'T, unit, string, 'Result>

/// <summary>Represents a statically-analyzed format when formatting builds a string. 
/// The type parameter indicates the arguments and return type of the 
/// format operation.</summary>
type StringFormat<'T> = StringFormat<'T,string>

Solution

  • The correct type for the format string is not unit. It should be

    let dynamicString = Printf.StringFormat<unit,unit>("dynamic string")  
    

    To find this out, create a function like this:

    let test arg = Printf.ksprintf ignore arg
    

    and look at the generated type for arg