OCaml let … in
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
e1to a valuev. For example, in the expressionlet x = 2 + 2 in x * x, the value ofe1is2 + 2which evaluates to4. -
The second step is to evaluate the expression
e2withxbound to the valuev. In the same example,e2isx * xandxis bound to the value4. Sox * xbecomes4 * 4which evaluates to16.
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.