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.
To run the program, save it as variables.ml
and use the OCaml compiler:
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.