Let

Let expression

A let expression can be used to capture a value from an intermediate calculation in a variable.

let-expression:
      let variable-list in expression
variable-list:
      variable
      variable
, variable-list
variable:
      variable-name
= expression
variable-name:
      identifier

The following example shows intermediate results being calculated and stored in variables x, y, and z which are then used in a subsequent calculation x + y + z:

let     x = 1 + 1,
        y = 2 + 2,
        z = y + 1 
in
        x + y + z

The result of this expression is:

11  // (1 + 1) + (2 + 2) + (2 + 2 + 1)

The following holds when evaluating expressions within the let-expression:

  • The expressions in the variable list define a new scope containing the identifiers from the variable-list production and must be present when evaluating the expressions within the variable-list productions. Expressions within the variable-list may refer to one-another.

  • The expressions within the variable-list must be evaluated before the expression in the let-expression is evaluated.

  • Unless the expressions in the variable-list are accessed, they must not be evaluated.

  • Errors that are raised during the evaluation of the expressions in the let-expression are propagated.

A let expression can be seen as syntactic sugar over an implicit record expression. The following expression is equivalent to the example above:

[     x = 1 + 1,
      y = 2 + 2,
      z = y + 1,
      result = x + y + z 
][result]