How to use Scanf.format_of_string

I am trying to understand Scanf.format_of_string s fmt but it seems my intuition is failing me. What is the second parameter and how do I use it? I tried a simple example below but it is failing.

utop> let f = Scanf.format_from_string "" "%s";;
"bad input: format type mismatch between \"\" and \"%s\"".

My understanding is the s parameter is of a string type. No?

1 Like

format_from_string s fmt converts a string argument to a format string, according to the given format string fmt .

Raises Scan_failure if s , considered as a format string, does not have the same type as fmt .

The key fact is that s must have the matching type when considered as a format string. In your case, s corresponds to a zero-argument format string and fmt to a one-argument format string, so the exception is raised.

The format string fmt acts as a kind of dummy placeholder to provide the right type for the result of interpreting s, as a kind of run-time equivalent of the Stdlib.format_of_string function.

# let dummy_fmt : (_, _, _) format = "{ foo : %d; bar : %s }\n"

  (* Use [dummy_fmt] to supply expected type information of new format *)
  let reified_fmt = Scanf.format_from_string ("{ new_foo : %d; new_bar : %s }\n" : string) dummy_fmt

  let () =
    Printf.printf dummy_fmt 1 "alpha" ;
    Printf.printf reified_fmt 2 "beta" ;;

{ foo : 1; bar : alpha }
{ new_foo : 2; new_bar : beta }

Thanks for the explanation.

1 Like