30 lines
1.9 KiB
Plaintext
30 lines
1.9 KiB
Plaintext
{{Control Structures}}
|
|
|
|
Assume functions <code>a</code> and <code>b</code> return boolean values, and further, the execution of function <code>b</code> takes considerable resources without side effects, <!--treating the printing as being for illustrative purposes only--> and is to be minimized.
|
|
|
|
If we needed to compute the conjunction (<code>and</code>):
|
|
:::: <code> x = a() and b() </code>
|
|
|
|
Then it would be best to not compute the value of <code>b()</code> if the value of <code>a()</code> is computed as <code>false</code>, as the value of <code>x</code> can then only ever be <code> false</code>.
|
|
|
|
Similarly, if we needed to compute the disjunction (<code>or</code>):
|
|
:::: <code> y = a() or b() </code>
|
|
|
|
Then it would be best to not compute the value of <code>b()</code> if the value of <code>a()</code> is computed as <code>true</code>, as the value of <code>y</code> can then only ever be <code>true</code>.
|
|
|
|
Some languages will stop further computation of boolean equations as soon as the result is known, so-called [[wp:Short-circuit evaluation|short-circuit evaluation]] of boolean expressions
|
|
|
|
|
|
;Task:
|
|
Create two functions named <code>a</code> and <code>b</code>, that take and return the same boolean value.
|
|
|
|
The functions should also print their name whenever they are called.
|
|
|
|
Calculate and assign the values of the following equations to a variable in such a way that function <code>b</code> is only called when necessary:
|
|
:::: <code> x = a(i) and b(j) </code>
|
|
:::: <code> y = a(i) or b(j) </code>
|
|
|
|
<br>If the language does not have short-circuit evaluation, this might be achieved with nested '''if''' statements.
|
|
<br><br>
|
|
|