Next: Returning Results Through Up: Maple Procedures Previous: Simplifications and Transformation

Optional Arguments and Default Values

Many Maple routines accept optional arguments. This is often used to allow the user to use default values instead of having to specify all parameters. Examples are the functions plot, factor, collect, and series. Let us consider the degree function. The degree function computes the degree of a univariate polynomial in one variable, and for multivariate polynomials, the total degree. For example


> p := x^3+2*x+1;

                                     3
                               p := x  + 2 x + 1

> degree(p);

                                       3

> q := 3*x^2*y+2*y^2-x*z+7;

                                  2        2
                          q := 3 x  y + 2 y  - x z + 7

> degree(q);

                                       3

Sometimes you will want to compute the degree in a specific variable, say . This can be done by specifying an optional second argument to the degree function, namely, the variable. For example


> degree(p,x);

                                       3

> degree(q,x);

                                       2

How would we code the degree function? Let us assume that the input is a formula and if an optional second argument is given, it is a name or set of names for the variables. We would write


DEGREE := proc(a,x) local s,t;
    if nargs = 1 then # determine the variable(s) for the user
        s := indets(a); # the set of all the variables of a
        if not type(s,set(name)) then ERROR(`input not a polynomial`) fi;
        DEGREE(a,s)
    elif type(a,constant) then 0
    elif type(a,name) then
        if type(x,name) then if a = x then 1 else 0 fi
        elif type(x,set(name)) then if member(a,x) then 1 else 0 fi
        else ERROR(`2nd argument must be a name or set of names`)
        fi
    elif type(a,`+`) then max( seq( DEGREE(t,x), t=a ) )
    elif type(a,`*`) then
        s := 0;
        for t in a do s := s + DEGREE(t,x) od;
        s
    elif type(a,algebraic^integer) then DEGREE(op(1,a),x) * op(2,a)
    else ERROR(`cannot compute degree`)
    fi
end;

The indets function used here returns a set of all the indeterminates (or variables) that appear in the input. We leave it to the reader to study each rule that is being used here, and the order in which the cases are done.


bondaren@thsun1.jinr.ru