prog::Precondition – Precondition testing

prog::Precondition allows for flexible precondition testing with consistent error messages.

→ Examples

Call:

prog::Precondition(<precondition1, precondition2, ...>)

Parameters:

precondition1

boolean expressions

Details:

Example 1:

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);

math

Changes in MuPAD 4.0

New Function.