Previous | Next

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.

Previous | Next

0 Responses to “Local Definitions”


  1. No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



1208 feed subscribers
(readers who polled a feed this week)