Defining Local Variables in Lisp

For our simple game, we’ve defined global variables and functions. However, in most cases you’ll want to limit your definitions to a single function or a block of code. These are called local variables and functions.

To define a local variable, use the command let. A let command has the following structure:

 (let (variable declarations)
   ...body...)

The first thing inside the let command is a list of variable declarations . This is where we can declare one or more local variables. Then, in the body of the command (and only within this body), we can use these variables . Here is an example of the let command:

 > (let ((a 5)
         (b 6))
     (+ a b))
  11

In this example, we’ve declared the values 5 and 6 for the variables a and b , respectively. These are our variable declarations. Then, in the body of the let command, we added them together , resulting in the displayed value of 11.

When using a let expression, you must surround the entire list of declared variables with parentheses. Also, you must surround each pair of variable names and initial variables with another set of parentheses.

Note

Although the indentation and line breaks are completely arbitrary, because the names of the variables and their values in a let expression form a kind of simple table, common practice is to align the declared variables vertically. This is why the b is placed directly underneath the a in the preceding example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.217.220