RosettaCodeData/Task/Short-circuit-evaluation/00-TASK.txt

30 lines
1.9 KiB
Plaintext

{{Control Structures}}
Assume functions &nbsp; <code>a</code> &nbsp; and &nbsp; <code>b</code> &nbsp; return boolean values, &nbsp; and further, the execution of function &nbsp; <code>b</code> &nbsp; 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 &nbsp; (<code>and</code>):
:::: <code> x = a() and b() </code>
Then it would be best to not compute the value of &nbsp; <code>b()</code> &nbsp; if the value of &nbsp; <code>a()</code> &nbsp; is computed as &nbsp; <code>false</code>, &nbsp; as the value of &nbsp; <code>x</code> &nbsp; can then only ever be &nbsp; <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 &nbsp; <code>b()</code> &nbsp; if the value of &nbsp; <code>a()</code> &nbsp; is computed as &nbsp; <code>true</code>, &nbsp; as the value of &nbsp; <code>y</code> &nbsp; can then only ever be &nbsp; <code>true</code>.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called &nbsp; [[wp:Short-circuit evaluation|short-circuit evaluation]] &nbsp; of boolean expressions
;Task:
Create two functions named &nbsp; <code>a</code> &nbsp; and &nbsp; <code>b</code>, &nbsp; 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 &nbsp; <code>b</code> &nbsp; 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 &nbsp; &nbsp; '''if''' &nbsp; &nbsp; statements.
<br><br>