OCaml let Bindings and Scope
let is how you name things in OCaml. There are two forms:
- Top-level
let name = exprdefines a name visible for the rest of the file (and to other modules). - Local
let name = expr in bodydefines a name visible only insidebody.
let tax_rate = 0.2 (* top level: visible below *)
let price_with_tax net =
let tax = net *. tax_rate in (* local: only inside this function *)
net +. tax
let () = Printf.printf "%.2f\n" (price_with_tax 50.0)60.00
Chaining local bindings
Each let ... in opens a new scope that contains everything after the in. Several in a row read like a step-by-step calculation:
let () =
let width = 4.0 in
let height = 2.5 in
let area = width *. height in
let perimeter = 2.0 *. (width +. height) in
Printf.printf "area %.1f, perimeter %.1f\n" area perimeterarea 10.0, perimeter 13.0
Bindings are immutable
A binding never changes. Writing let x = ... again with the same name creates a new binding that shadows the old one. The old value still exists, and code that captured it keeps seeing it:
let () =
let x = 10 in
let show_x () = Printf.printf "show_x sees %d\n" x in
let x = x + 5 in (* a new x shadows the old one *)
Printf.printf "x is now %d\n" x;
show_x ()x is now 15
show_x sees 10
show_x was created when x was 10, and it keeps that value. This is called a closure: a function remembers the bindings that were in scope where it was defined.
Note: Shadowing is not assignment. If you need a value that really changes over time, OCaml has references (
ref), covered in the imperative section. Most code does not need them.
Scope ends at the expression
A local name exists only inside its body. Using it outside is a compile error:
let area =
let side = 3 in
side * side
let () = Printf.printf "%d %d\n" area sideFile "<source>", line 5, characters 38-42:
5 | let () = Printf.printf "%d %d\n" area side
^^^^
Error: Unbound value side
Simultaneous bindings with and
let a = ... and b = ... defines several names at once. None of them can see the others (unless you use let rec, used for mutually recursive functions):
let () =
let x = 1 and y = 2 in
let x = y and y = x in (* swap: both right-hand sides use the old values *)
Printf.printf "x=%d y=%d\n" x yx=2 y=1
Destructuring in a binding
The left side of let is actually a pattern, so you can take apart a tuple (or record) while binding:
let min_max a b = if a < b then (a, b) else (b, a)
let () =
let low, high = min_max 9 4 in
let _, second = ("ignored", "kept") in
Printf.printf "%d..%d %s\n" low high second4..9 kept
_ is the wildcard pattern: it matches anything and binds no name.
Local definitions inside functions
Helper functions that only make sense inside one function can be local too, which keeps the top level clean:
let format_duration seconds =
let pad n = if n < 10 then "0" ^ string_of_int n else string_of_int n in
let minutes = seconds / 60 and secs = seconds mod 60 in
pad minutes ^ ":" ^ pad secs
let () =
print_endline (format_duration 75);
print_endline (format_duration 3599)01:15
59:59
Test yourself
What does let x = 1 in let x = x + 1 in x evaluate to?
12- A compile error: x is immutable
3
Where is the name n visible in let n = 5 in e?
- Everywhere in the file
- Only inside
e - Only before the
in - In all functions defined later
What is _ used for in let _, b = pair?
- It names the first element
_ - It is a wildcard that ignores the first element
- It is a syntax error
- It makes b mutable