The instruction let\(a:=b\) assigns the value of \(b\) to \(a\text{.}\) For example, after the instruction let\(a:=5\text{,}\) the variable \(a\) has the value \(5\text{.}\) Suppose that the variable \(a\) has the value \(5\text{.}\) Then, after let\(a:=a+1\text{,}\) the variable \(a\) has the value \(6\text{.}\) First, we evaluate \(a +1\) as \(6\) because \(a = 5\text{.}\) Then we assign \(6\) to the variable \(a\text{.}\)
The assignment instruction let can be used in two ways. We can give a value to a variable that does not yet have a value, or we can give a new value to a variable that already has a value.
We can also use let to assign the value of an expression to a variable. Assume that the value of the variable \(c\) is \(10\text{.}\) Consider the instruction:
First the expression on the right is evaluated. As \(c=10\) we get that \(c+35=10+35=45\text{.}\) Then the computed value 45 is assigned to \(d\text{,}\) so that the value of \(d\) after this instruction is \(45\text{.}\)
It is more confusing when the same variable shows up on both sides of the \(:=\) of a let instruction. Assume that the value of i is 5 and consider the instruction:
First the expression on the right is evaluated, we obtain \(i+1=5+1=6\text{.}\) Then the result of this computation, namely 6, is assigned to \(i\text{,}\) so that the new value of \(i\) is 6.
let\(d:=c\cdot c\text{:}\) We have \(c=-3\text{.}\) We compute \(c\cdot c=(-3)\cdot (-3)= 9\) and assign this value to the variable \(d\text{.}\) Now \(d=9\text{.}\)
let\(e:=c\cdot d\text{:}\) We have \(c=-3\) and \(d=9\text{.}\) We compute \(c\cdot d=(-3)\cdot 9=-27\) and assign this value to the variable \(e\text{.}\) Now \(e=-27\text{.}\)
return\(c\text{,}\)\(d\text{,}\)\(e\text{,}\)\(f\) : We return the values of \(c\text{,}\)\(d\text{,}\)\(e\text{,}\) and \(f\text{,}\) namely \(-3\text{,}\)\(9\text{,}\)\(-27\text{,}\) and \(81\)
The input and output of Algorithm 2.2.3 and Algorithm 2.4.3 are the same, but the results are obtained in different ways. In particular the computation effort differs.
Algorithm 2.2.3 needs one multiplication to compute \(c^2= c\cdot c\text{,}\) two multiplications to compute \(c^3= c\cdot c\cdot c\text{,}\) and three multiplications to compute \(c^4= c\cdot c\cdot c\cdot c\) (count the multiplication symbols ‘\(\cdot\)’). This is a total of 6 multiplications.
Algorithm 2.4.3 computes the same values as \(d=c\cdot c\text{,}\)\(e=c\cdot d\text{,}\) and \(f=c^2\cdot c^2\text{.}\) It only needs 3 multiplications to compute the four values \(d=c^2\text{,}\)\(e=c^3\text{,}\) and \(f=c^4\text{.}\)
Using the same strategy as in Algorithm 2.4.3, the algorithm in Example 2.4.5 computes the eighth power of its input. This is the first in a series of interactive algorithms. Click the instructions to see how they change the variable values.