Variables in LISP
Similar to other languages, in LISP variables are named places that store a particular value, but they are not declared the way you declare variables in C++ or Java i.e you don’t need to mention data-type of variables when declaring them as LISP is dynamically typed.
LISP supports two types of variables:
- Local variables
- Global variables
They are also called Lexical variables, these variables are defined inside a particular function and only the code within the binding form can refer to them as they can not be accessed outside of that function. Parameters of the functions are also local variables.
Defining a local variable:
New local variables can be created using the special operator LET. These variables then can be used within the body of the LET.
The syntax for creating a variable with LET is:
(let (variable) body-of-expressions)
A let expression has two parts
- The first part consists of instructions for creating a variable and assigning values to them
- The second part consists of a list of s-expressions
Now let’s create local variables using the above-mentioned syntax
Here we have assigned x and y with initial values and for z no value is provided, hence NIL will be set as z’s default value.
Local Variables : x = 10, y = 20 & z=NIL
These are the variables that have a global scope i.e. you can call access them from anywhere in the program. In LISP global variables are also called Dynamic variables.
Defining a global variable:
New global variables can be defined using DEFVAR and DEFPARAMETER construct. The difference between both of them is that DEFPARAMETER always assigns initial value and DEFVAR form can be used to create a global variable without giving it a value.
The syntax for creating global variables is:
(defvar *name* initial-value "Documentation string") (defparameter *name* initial-value "Documentation string")
Let’s create a global variable that holds the rate of the pencil as *pencil-rate*, and with help of one function calculate the total bill by multiplying the total number of pencils with our global variable *pencil-rate*.
It is a proper naming convention to define global variables to start and end with asterisks because as global variables can be accessed anywhere in the program, there can be local variables with the same name, hence for avoiding this possibility by accident this naming convention is used. Example. *global*
Please Login to comment...