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

时间:2021-12-24 01:59:08

I’m doing my first steps on Ocaml and I want to write a function which will receive two numbers in String variables and will return the sum of the two received numbers in an string.

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

I know I could do the following

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

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

I am aware it is infeasible for real life, so I would like to avoid the huge amount of cases I'll have to add. I'm also aware that I could use float_of_string and int_of_string for reducing the number of test cases.

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

Could you please give me some hints about how I should proceed?

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

Thanks in advance. ....

提前致谢。 ....

1 个解决方案

#1


Basically, a more correct way would be to convert strings to numbers, and the apply operations, and afterwards inject the values back into the string, e.g,

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

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

If you want to perform your arithmetic operations in the field of real numbers you can define your sum as:

如果要在实数字段中执行算术运算,可以将总和定义为:

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

#1


Basically, a more correct way would be to convert strings to numbers, and the apply operations, and afterwards inject the values back into the string, e.g,

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

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

If you want to perform your arithmetic operations in the field of real numbers you can define your sum as:

如果要在实数字段中执行算术运算,可以将总和定义为:

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