Previous | Next

The first step in raising Objective Caml above the lowly pocket calculator level is the ability to give names to objects.  The language construct for doing so is borrowed from mathematics, where mathematicians would say “let x be the smallest integer such that …” and refer to that integer as “x” from then on. The syntax for doing so is:

let (variable) = (expression) ;;

Use the semicolons for now—we will see later on that they are optional in some circumstances. Example of such a definition:

let x = (2 + 4) * 3 ;;
x - 2

This will evaluate the expression (which yields the value 18) then bind that value to the name x. Every expression below the definition of x will know that x equals 18, so the second expression would evaluate to 16. Here, x is called a variable—a confusing name, since it does not actually vary: once it’s defined, it stays forever. Any name can be used for a variable, as long as it starts with a lowercase letter and contains only letters, numbers and underscores.

It is of course possible to define more than one variable in a program:

let x = 3 + 4 ;;
let y = 2 * 5 ;;
x + y

This example evaluates to 17. A normal Objective Caml program defines hundreds and even thousands of variables in order to work.

Having a thousand variables creates a risk for collision. The good news is that collisions are handled smoothly: at any point in the program only the last definition found so far counts. So, if we were to consider an example:

let x = 3 ;;
let x = x + 1 ;;
x + x

Line 1 defines x as 3, line 2 defines x again, this time as 3 + 1 = 4, and line three evaluates to 4 + 4 = 8.

This doesn’t solve the problem entirely, though: what if I accidentally overwrite a previously defined value, and I need that value later on?

Previous | Next

0 Responses to “Variables”


  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)