在 Ocaml 中添加两个字符串数字

Add two String numbers in Ocaml

我正在做 Ocaml 的第一步,我想编写一个函数,它将在字符串变量中接收两个数字,并将 return 字符串中两个接收到的数字的总和。

我知道我可以做到以下几点

let sum a b =
  match a,b with
  | "1", "1" -> "2"
  | "1", "1.0" -> "2.0"
;;

我知道这在现实生活中是不可行的,所以我想避免我必须添加的大量案例。我也知道我可以使用 float_of_string 和 int_of_string 来减少测试用例的数量。

你能给我一些关于我应该如何进行的提示吗?

提前致谢。 ....

基本上,更正确的方法是将字符串转换为数字,然后应用操作,然后将值注入回字符串中,例如

let sum x y = string_of_int (int_of_string x + int_of_string y)

如果您想在实数域中执行算术运算,您可以将 sum 定义为:

let sum x y = string_of_float (float_of_string x + float_of_string y)