Reputation: 329
I need to convert from a string to a format. I'm given an array of formats, and I would like access each format and use sprintf on them.
e.g.
let errors = [| "format 1"; "format 2"; ... ; "format 512" |]
let code_to_string (error_code : int) :(string) = sprintf errors.(error_code)
I saw this question. According to the best answer, different strings produce formats of different types, which is why this:
let errors = [| format_of_string "format 1";
format_of_string "format 2";
...
format_of_string "format 512" |]
doesn't work.
Is there a way to store all formats as strings, and then convert them when needed? Or would I have to write a function for each of the strings? e.g.
let error1 = sprintf "format 1" args
let error2 = sprintf "format 1" args
...
let error512 = sprintf "format 512" args
Upvotes: 4
Views: 1247
Reputation: 35210
You can convert arbitrary statically unknown values of type string
into values of type format6
using Scanf.format_from_string
. But, of course, you need to know the type of the format (and they all should unify).
Here is the motivating example:
# let fmt = Scanf.format_from_string "Hello: %d" "%d";;
val fmt : (int -> '_a, '_b, '_c, '_d, '_d, '_a) format6 = <abstr>
# Printf.printf fmt 12;;
Hello: 12- : unit = ()
P.S. And here is a more extreme use of this feature.
Upvotes: 3