我需要从字符串转换为格式 . 我给了一系列格式,我想访问每种格式并在它们上使用sprintf .
例如
let errors = [| "format 1"; "format 2"; ... ; "format 512" |]
let code_to_string (error_code : int) :(string) = sprintf errors.(error_code)
我看到this question . 根据最佳答案,不同的字符串会产生不同类型的格式,这就是为什么:
let errors = [| format_of_string "format 1";
format_of_string "format 2";
...
format_of_string "format 512" |]
不起作用 .
有没有办法将所有格式存储为字符串,然后在需要时转换它们?或者我是否必须为每个字符串编写一个函数?例如
let error1 = sprintf "format 1" args
let error2 = sprintf "format 1" args
...
let error512 = sprintf "format 512" args
1 回答
您可以使用
Scanf.format_from_string
将类型为string
的任意静态未知值转换为format6
类型的值 . 但是,当然,你需要知道格式的类型(它们都应该统一) .这是一个激励的例子:
附:并且here是对此功能的更极端使用 .