The let x = e1 in e2 construct in OCaml is an expression that allows you to create a new variable binding and use it within a specific scope. It works as follows:

  • The first step is to evaluate the expression e1 to a value v. For example, in the expression let x = 2 + 2 in x * x, the value of e1 is 2 + 2 which evaluates to 4.

  • The second step is to evaluate the expression e2 with x bound to the value v. In the same example, e2 is x * x and x is bound to the value 4. So x * x becomes 4 * 4 which evaluates to 16.

The overall result of the let-expression is whatever e2 evaluates to. In this example, e2 evaluates to 16, so the overall result of the let-expression is also 16.

It’s worth noting that let x = e1 in e2 is not a statement but an expression. That means that it can be used as a part of other expressions.

let n = 330 in "class has " ^ string_of_int n ^ " students"

The above expression has type string because the part after in has type string.