Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 40 ยท Language Basics

Values and let Bindings

Understand OCaml's let: naming values, local bindings with let ... in, scope, shadowing, immutability, and why OCaml has no assignment operator for ordinary names.

In most languages you create "variables" and change them. In OCaml you create bindings: a name attached to a value. The word is let, and a binding never changes after it is made. This one idea explains a lot about how OCaml code looks, and this lesson shows how bindings, scope and shadowing work.

Top-level bindings

OCAML
let age = 30
let pi = 3.14159
let language = "OCaml"
let is_ready = true

Each line says "from now on, this name means this value". You do not write types; the compiler infers int, float, string and bool. Names start with a lowercase letter or underscore and use snake_case by convention: max_size, user_name. Capitalized names are reserved for modules and constructors.

In the toplevel, each of these answers with its type:

OCAML
# let age = 30;;
val age : int = 30

Bindings are immutable

There is no way to "assign" to age later. This is not an error in the sense of a typo; it simply is not what let does. If you write a second binding with the same name, you create a new binding that hides the first (this is called shadowing):

OCAML
let x = 1
let x = x + 1   (* a new x, whose value is 2 *)

The old x is not modified; any function defined earlier that used it keeps seeing the old value:

OCAML
let x = 10
let show () = x
let x = 99
let a = show ()   (* a is 10, because show captured the first x *)

This is lexical scoping: a name refers to the nearest binding that was visible where the code was written.

Local bindings with let ... in

To give a name to something temporarily, use let name = value in expression. The name exists only inside the expression after in:

OCAML
let circle_area r =
  let pi = 3.14159 in
  pi *. r *. r

Outside circle_area, pi is not defined. A let ... in is itself an expression, so it can appear anywhere an expression can:

OCAML
let total =
  let price = 20 in
  let tax = price / 10 in
  price + tax
(* total is 22 *)

Bindings stack: the second let can see the first. They are visible until the expression after the last in ends.

Local bindings and layout

OCaml code usually puts each let ... in on its own line and does not indent the chain further. The formatter ocamlformat does this for you.

Multiple bindings at once: and

OCAML
let width = 8 and height = 5
let area = width * height

With and, the bindings are created at the same time, so the right-hand sides cannot see each other. This is handy for swapping values:

OCAML
let a = 1 and b = 2
let a = b and b = a   (* now a = 2 and b = 1 *)

Most code just writes separate lets; and matters mainly for mutually recursive functions, which come in Recursion.

Patterns on the left of =

The left side of let can be a pattern, not only a name. The most common use is taking apart a tuple:

OCAML
let (x, y) = (3, 4)
let (first, _) = ("keep", "ignore")

_ is a wildcard that matches anything and binds nothing. You will see much more of patterns in the pattern-matching chapter.

Unit bindings and the underscore

When you evaluate something only for its effect, bind it to () or _:

OCAML
let () = print_endline "starting"
let _ = List.length [1; 2; 3]   (* compute, ignore the result *)

A top-level let () = ... is how a program says "run this". The compiler checks that the expression has type unit; if it does not, you get an error, which catches bugs where you forgot to use a result.

Names and conventions

  • Identifiers may contain letters, digits, _ and ' (a prime): x', list2, parse_int. Primes are traditionally used for "the next version of x".
  • A name that starts with _, such as _unused, tells the compiler "I know this is unused", silencing the warning.
  • Keywords such as let, in, match, type, fun, if, val cannot be used as names.

A stand-in: let as a scope chain

JavaScript's const inside nested blocks behaves much like let ... in. The stand-in below shows shadowing without mutation: the outer x stays 10.

JS Stand-in: shadowing without mutation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does let x = 5 create?

    let binds a name to a value. The binding is immutable, but a later let x creates a new binding that shadows it.
  2. 2. Where is pi visible in let f r = let pi = 3.14 in pi *. r?

    A let ... in binding is local to the expression after in.
  3. 3. What is the value of a after let x = 10 let show () = x let x = 99 let a = show ()?

    show captured the first x. The later binding shadows the name but does not change the earlier one.
  4. 4. What does let _ = f 1 do?

    _ is a wildcard pattern that matches without binding a name.

Summary

  • let name = value binds a name; bindings are immutable.
  • A new let with the same name shadows the old one without changing it.
  • let ... in makes local bindings whose scope is the following expression.
  • and creates simultaneous bindings; patterns and _ can stand on the left.
  • let () = ... runs an expression for its effect.

Next: Basic types