Variables
7 min · OCaml
Give values names with let.
Enemy 1 of 5
Type inference in action
`let name = value` binds a value to a name — in OCaml this is usually called a "let binding" rather than a variable assignment, and the wording matters: once bound, a name in OCaml refers to a fixed value that doesn't change out from under you. If you write another `let name = ...` later, you're not mutating the original binding — you're introducing a brand-new one that happens to shadow (temporarily hide) the earlier name within its scope. The original value still exists; it's just no longer the thing `name` refers to going forward.
This differs from languages where a variable is a mutable slot you reassign freely. OCaml does have genuinely mutable storage (`ref` cells, arrays), but they're reached for deliberately, not by default — the everyday case is an immutable binding, which makes it much easier to reason about what a piece of code could possibly have done to a value by the time you're reading it later in the file.
`let name = "Ada"` doesn't mention a type anywhere, yet OCaml's compiler knows precisely that `name` has type `string`, purely by looking at the literal on the right-hand side. This is OCaml's Hindley-Milner type inference at work — one of the most complete type-inference systems of any mainstream language — and it's why idiomatic OCaml code so rarely bothers writing type annotations even though every single value is strictly typed underneath.
Bindings at the top level (outside any function) are typically defined one after another, each usable by the ones that follow: define `name` first, then reference it inside a later `let () = ...` action.
Loading editor...