Objective Caml solves this by providing local definitions: instead of making a variable available to all lines that appear below it, the variable is only available within an expression. The syntax is:
let (variable) = (expression) in (expression)
The variable exists only within the second expression, and uses the value of the first expression. For instance:
let x = 1 ;; let y = let x = 2 in x + x ;; x + y
This example defines x as 1. Then, within the definition of y, it defines x again as 2, which makes the value of y equal to 2 + 2 = 4. However, the second definition of x is only available within the “x + x” expression, so the “x + y” expression uses the original value, and the result is “1 + 4 = 5″.
Local definitions are expressions. This means that they can be used as part of other expressions, such as on either side of a mathematical operator, or within other definitions. It’s perfectly legal to write code like:
1 + (let x = 1 + 2 in x * 2)
This evaluates to 1 + (3 * 2) = 7.
In practice, most variables are defined locally, and only the most important variables are defined globally.
Hi. I'm Victor Nicollet,
0 Responses to “Local Definitions”