stringnumbersocamltype-conversion

Add two String numbers in Ocaml


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.

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.

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

Thanks in advance. ....


Solution

  • 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)