Variables in OCaml

In OCaml, variables are declared and used implicitly. The type system uses type inference to determine the types of variables in most cases.

(* In OCaml, we don't need to declare a main function explicitly *)

(* Let bindings are used to declare variables *)
let a = "initial"
let () = Printf.printf "%s\n" a

(* You can declare multiple variables at once using tuple destructuring *)
let b, c = 1, 2
let () = Printf.printf "%d %d\n" b c

(* OCaml will infer the type of initialized variables *)
let d = true
let () = Printf.printf "%b\n" d

(* Variables declared without initialization are not allowed in OCaml *)
(* Instead, we can use option types for potentially uninitialized values *)
let e : int option = None
let () = match e with
  | Some value -> Printf.printf "%d\n" value
  | None -> Printf.printf "None\n"

(* In OCaml, all bindings are immutable by default *)
(* To create a mutable binding, use the 'ref' keyword *)
let f = ref "apple"
let () = Printf.printf "%s\n" !f

To run the program, save it as variables.ml and use the OCaml compiler:

$ ocamlc -o variables variables.ml
$ ./variables
initial
1 2
true
None
apple

In OCaml:

  • Variables are declared using let bindings.
  • Multiple variables can be declared using tuple destructuring.
  • Type inference is used extensively, but you can also explicitly specify types.
  • There’s no concept of uninitialized variables; instead, OCaml uses option types for potentially absent values.
  • All bindings are immutable by default. To create mutable bindings, use the ref keyword.
  • The Printf.printf function is used for formatted output, similar to fmt.Println in the original example.

OCaml’s type system and immutability by default provide strong guarantees about program correctness at compile-time.