prog::Precondition – Precondition testing
prog::Precondition allows for flexible precondition testing with consistent error messages.
Call:
prog::Precondition(<precondition1, precondition2, ...>)
Parameters:
precondition1: |
boolean expressions |
Details:
When testargs() is TRUE, prog::Precondition evaluates the expressions precondition1,precondition1,Symbol::hellip one after the other in the caller context, and raise an error if the result is FALSE.
When testargs() is FALSE, Precondition just does nothing; in particular the expressions are not evaluated at all. The overhead of a precondition is therefore just that of a trivial function call (and could possibly be optimized further).
Suppose that we want to implement a function which accepts to positive integer argument i and j such that i<j. Testing whether the arguments are indeed positive integers can be done using the standard MuPAD type checking mechanism:
f :=
proc(i: Type::PosInt, j: Type::PosInt)
begin
Symbol::hellip;
stupidResult;
end:
However the precondition i<j cannot as it involves to arguments simultaneously. The usual idiom was to test the precondition manually under a testargs() guard:
f :=
proc(i: Type::PosInt, j: Type::PosInt)
begin
if testargs() and i >= j then
error("i should be smaller than j");
end_if;
Symbol::hellip;
stupidResult;
end:
This is a bit cumbersome, but more importantly it does not enforce any sort of consistency in the way the error messages are output. For example, some developers may decide to include the actual values of i and j; or not.
For better readibility, we export prog::Precondition:
export(prog, Alias, Precondition):
Now, we can declare preconditions for the function in a natural way:
f :=
proc(i: Type::PosInt, j: Type::PosInt)
begin
Precondition(i < j);
Symbol::hellip;
stupidResult;
end:
Here is the current error message:
testargs(TRUE):
f(2,1);
Error: Precondition i < j failed [f]
Note: the values of the parameters involved are not yet printed, but this would be possible.
When testargs() is FALSE, the preconditions are just ignored, of course potentially leading to stupid results.
testargs(FALSE):
f(2,1);
Changes in MuPAD 4.0
New Function.