Number Parsing in OCaml

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in OCaml.

(* The built-in module `Float` provides float parsing *)
(* The built-in module `Int` provides integer parsing *)

let main () =
  (* With `Float.of_string`, we parse a float *)
  let f = Float.of_string "1.234" in
  Printf.printf "%f\n" f;

  (* For `Int.of_string`, we parse an integer *)
  let i = Int.of_string "123" in
  Printf.printf "%d\n" i;

  (* Int.of_string will recognize hex-formatted numbers *)
  let d = Int.of_string "0x1c8" in
  Printf.printf "%d\n" d;

  (* We can also parse unsigned integers *)
  let u = Int64.of_string "789" in
  Printf.printf "%Ld\n" u;

  (* There's no direct equivalent to Atoi in OCaml, 
     but we can use Int.of_string for basic base-10 int parsing *)
  let k = Int.of_string "135" in
  Printf.printf "%d\n" k;

  (* Parsing functions raise exceptions on bad input *)
  try
    let _ = Int.of_string "wat" in ()
  with Failure msg ->
    Printf.printf "%s\n" msg

let () = main ()

To run the program, save it as number_parsing.ml and use ocamlc to compile and run:

$ ocamlc -o number_parsing number_parsing.ml
$ ./number_parsing
1.234000
123
456
789
135
int_of_string

In OCaml, number parsing is handled by built-in modules like Float and Int. Unlike Go, OCaml doesn’t have a separate unsigned integer type in its standard library, so we use Int64 for larger numbers.

OCaml’s parsing functions raise exceptions on invalid input, which we can catch with a try-with block. This is different from Go’s approach of returning an error value.

The Printf module is used for formatted output, similar to Go’s fmt package.

Next, we’ll look at another common parsing task: URLs.