TExcelTAD
Home › OCaml › OCaml let Bindings and Scope

OCaml let Bindings and Scope

let is how you name things in OCaml. There are two forms:

  • Top-level let name = expr defines a name visible for the rest of the file (and to other modules).
  • Local let name = expr in body defines a name visible only inside body.
ocaml · try it yourself
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:

ocaml · try it yourself
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 perimeter
area 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:

ocaml · try it yourself
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:

ocaml · try it yourself
let area =
  let side = 3 in
  side * side

let () = Printf.printf "%d %d\n" area side
File "<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):

ocaml · try it yourself
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 y
x=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:

ocaml · try it yourself
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 second
4..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:

ocaml · try it yourself
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?

  1. 1
  2. 2
  3. A compile error: x is immutable
  4. 3

Where is the name n visible in let n = 5 in e?

  1. Everywhere in the file
  2. Only inside e
  3. Only before the in
  4. In all functions defined later

What is _ used for in let _, b = pair?

  1. It names the first element _
  2. It is a wildcard that ignores the first element
  3. It is a syntax error
  4. It makes b mutable