Constants in OCaml

Constants in OCaml can be represented using the let keyword. Here’s how you can define and use constants in OCaml, similar to the given example.

OCaml does not have native support for arbitrary precision arithmetic in expressions, but constants can still be used effectively.

Our first program will show how constants work in OCaml. Here’s the full source code.

(* Define a string constant *)
let s = "constant"

(* Define a numeric constant *)
let n = 500000000

(* Perform arithmetic with constants *)
let d = 3e20 /. float_of_int n

(* Print the results *)
let () = 
  print_endline s;
  Printf.printf "%f\n" d;
  Printf.printf "%Ld\n" (Int64.of_float d);
  Printf.printf "%f\n" (sin (float_of_int n))

To run the program, put the code in constants.ml and use ocaml to execute it.

$ ocaml constants.ml
constant
600000000000.000000
600000000000
0.28470407323754404

Now that we can run and build basic OCaml programs, let’s learn more about the language.