next up previous
Next: Plotting Three Dimensional Up: PLOTTING OBJECTS IN Previous: PLOTTING OBJECTS IN

Defining Functions/Procedures

In the previous sections we have been defining expressions instead of functions/procedures. Below f is an expression and g is a procedure. Compare the definitions and their use.

f := x^3 + x + 5;                 defining an expression f
g := proc(x) x^3 + x + 5 end;     defining a procedure g  
subs( x=1, f ); g(1);         evaluating f and g at x=1.
diff(f, x); diff(g(x), x);    differentiation
Occasionally, one must deal with procedures instead of expressions. Consider the definition below.
h := proc(x)                                              Hit Line Feed 
     if ( type(x,numeric) )                               Line Feed
        then if (x<0) then 1 else -1 fi                   Line Feed
     else 'h'(x)                                          Line Feed
     fi                                                   Line Feed
     end:                                                 Return
It defines a procedure named h, of one variable x, for which

Note that every if statement is ended by fi and the proc definition is ended by an end. In the definition of the part about ``x is not a number'' is included to handle those situations - there is more to it but we skip the details for the moment. Now try the following and examine whether the results are what you expected.

h(3); h(-5); h(0);
plot( h(x), x=-5..5 );
plot( x^2, x=-5..5 ); 
plot( h(x)*x^2, x=-5..5 );
It is imperative to keep in mind that whenever an expression containing a procedure is evaluated the arguments of the procedure are evaluated before the procedure is invoked. This leads to the most frequently occurring errors in the use of procedures. Be sure you understand why the the Maple output of the following statements is what it is.
a := 2; b :=3;
f := proc(x,y) x+2*y end;
f(c,d);   f(a,x);
f(a,d^2); f(a^2,d);
f(a,b);   f('a','b'); f('a^2',b^2);
The last executed line is particularly important - if an argument of a function is an expression enclosed in right quotes then the result of evaluating that argument is the expression inside the quotes - we saw this in Subsection 1.9. For more about defining procedures, using ``if then else'' etc. see the book on Maple on reserve in the library.



Peter Monk
Tue Aug 29 14:41:29 EDT 1995