Scheme Programming/Using Variables

Using Variables edit

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 define and let. The difference between the two is simple once fully grasped.

For example, using define:

> (define x 2)
#<unspecified>
> (* x 3)
6
> x
2

This shows that even once used, the variable x 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 <variable name> <variable value>)

Now we will see the use of let

> (let ((x 2) (y 4)) (* x y))
8
> x
;ERROR: "/usr/lib/scm/Iedline.scm": unbound variable:  x
> y
;ERROR: "/usr/lib/scm/Iedline.scm": unbound variable:  y

Notice here, how once the block of code has finished executing, the variables x and y 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)) (<body>))

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:

(define f 
  (lambda(x)
    (cond
      ((= x 3) 5)
      (else "Error: Invalid input!"))))

(define y (f 5))

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.