我正在寻找一个将十进制数的字符串表示转换为Num.num
的函数。有一个Num.num_of_string
函数,但遗憾的是,它只适用于有效整数。
我在重新实现一个这样的功能之前要求。
答案 0 :(得分:1)
我想你必须自己做。我曾经做过一次,这就是我所做的:
let num_of_string =
let open Num in
let code_0 = Char.code '0' in
let num10 = Int 10 in
fun s ->
try num_of_string s
with Failure _ ->
let r = ref (Int 0) in
let pos_dot = ref (-1) in
String.iteri (fun i c ->
if c = '.' then pos_dot := String.length s - i
else
r := add_num (mult_num num10 !r) (num_of_int (Char.code c - code_0))
) s;
assert (!pos_dot <> -1);
div_num !r (power_num num10 (num_of_int !pos_dot))