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{.}\) Assume that the variable \(a\) has the value \(5\) ; then after let\(a:=a+1\text{,}\) the variable \(a\) has the value \(6\text{.}\) This occurs because we first evaluate that \(a +1\) is \(6\) (since \(a = 5\)) and then assign \(6\) to the variable \(a\text{.}\)
The assignment instruction let_:= can be used in two ways. We can assign a value to a variable that did not have a value so far or we can assign new value to an existing variable, that we change the value of an existing variable.
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)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.7 and Algorithm 2.25 are the same, but the results are obtained in different ways. In particular the computation effort differs.
Algorithm 2.7 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.25 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.25 the algorithm in Example 2.27 computes the eighth power of the input. This is the first in a series of interactive algorithms in which you can observe how the instructions change the values of variables by clicking on the instructions.