Scheme Programming/Using Variables

Using Variables
In order to make your program a little more dynamic, it is often necessary to declare a variable. There are 2 main ways of doing this, using  and. The difference between the two is simple once fully grasped.

For example, using define:

This shows that even once used, the variable  continues to exist, it is defined for all to see, use and (as we shall see later on) modify at will.

In general, the form of a define statement for a variable is as follows:

(define )

Now we will see the use of

Notice here, how once the block of code has finished executing, the variables  and   are no longer accessible. This is a very bulky and slow way to do this at this point, but it allows for more elegant programs later.

In general, the form of a let statement is as follows:

(let ((var1 val1) ... (varn valn)) )

Variables in Scheme are dynamically typed, so there is no need to declare the type of the variable when you define it. Moreover, if you want to change the value of a variable, you can change it to any value you like - the same variable can hold any type of data. This can be beneficial when a function returns two different types of values and you wish to store the result in a variable regardless of what the result is:

If we were using a language such as Java, which uses static typing, this would not be allowed. As evidenced by the example, a common use of dynamic typing is to have a function return one type of value (e.g. a number) if the function call was successful, and another (here a string) if the function failed. Of course, despite dynamic typing, illogical actions such as attempting to multiply two symbols together will still fail, so when a function returns two possible types, be sure to determine the type of the value that was actually returned before attempting to use it.