Contents Previous Next Index

1 Introduction to Programming in Maple


Maple provides an interactive problemsolving environment, complete with procedures for performing symbolic, numeric, and graphical computations. At the core of the Maple computer algebra system is a powerful programming language, on which the Maple libraries of mathematical commands are built.

1.1 In This Chapter


•

Components of the Maple software

•

Procedures and other essential elements of the Maple language



1.2 The Maple Software


The Maple software consists of two distinct parts.

The User Interface


You can use the Maple user interface to enter, manipulate, and analyze mathematical expressions and commands. The user interface communicates with the Maple computation engine to solve mathematical problems and display their solutions.
For more information about the Maple user interface, refer to the Maple User Manual.


The Computation Engine


The Maple computation engine is the command processor, which consists of two parts: the kernel and math library.
The kernel is the core of the Maple computation engine. It contains the essential facilities required to run and interpret Maple programs, and manage data structures. In this guide, the kernel commands are referred to as builtin commands.
The Maple kernel also consists of kernel extensions, which are collections of external compiled libraries that are included in Maple to provide lowlevel programming functionality. These libraries include Basic Linear Algebra Subprograms (BLAS), GNU Multiple Precision (GMP), the NAG® C Library, and the C Linear Algebra PACKage (CLAPACK).
The math library contains most of the Maple commands. It includes functionality for numerous mathematical domains, including calculus, linear algebra, number theory, and combinatorics. Also, it contains commands for numerous other tasks, including importing data into Maple, XML processing, graphics, and translating Maple code to other programming languages.
All library commands are implemented in the highlevel Maple programming language, so they can be viewed and modified by users. By learning the Maple programming language, you can create custom programs and packages, and extend the Maple library.



1.3 Maple Statements


There are many types of valid statements. Examples include statements that request help on a particular topic, display a text string, perform an arithmetic operation, use a Maple library command, or define a procedure.
Statements in 1D notation require a trailing semicolon (;) or colon (:). If you enter a statement with a trailing semicolon, for most statements, the result is displayed. If you enter a statement with a trailing colon, the result is computed but not displayed.
For more information about statements in Maple, see Maple Statements.

Getting Help


To view a help page for a particular topic, enter a question mark (?) followed by the corresponding topic name. For example, ?procedure displays a help page that describes how to write a Maple procedure.
For more information about getting help in Maple, refer to the help and HelpGuide help pages.
This type of Maple statement does not have a trailing colon or semicolon.


Displaying a Text String


The following statement returns a string. The text that forms the string is enclosed in double quotes, and the result (the string itself) is displayed because the statement has a trailing semicolon.
${''Hello\; World''}$
 (2) 
Normally, you would create a string as part of another statement, such as an assignment or an argument for a procedure.
For more information about strings in Maple, see Maple Language Elements.


Performing an Arithmetic Operation


The arithmetic operators in Maple are + (addition),  (subtraction), * (multiplication), / (division), and ^ (exponentiation). A statement can be an arithmetic operation that contains any combination of these operators. The standard rules of precedence apply.
Maple computes this result as an exact rational number.


Assigning to a Name


By naming a calculated result or complicated expression, you can reference it. To assign to a name, use the assignment statement, :=.
${a}{\u2254}\frac{{103993}}{{33102}}$
 (4) 
$\frac{{103993}}{{16551}}$
 (5) 
For more information about names and assignment, see Maple Language Elements.


Using Maple Library Commands


After a value is assigned to a name, for example, the value assigned previously to a, you can use the name as if it were the assigned object. For example, you can use the Maple library command evalf to compute a floatingpoint (decimal) approximation to 103993/33102 divided by 2 by entering the following statement.
You can use the Maple library of commands, introduced in The Computation Engine, for many purposes. For example, you can find the derivative of an expression by using the diff command.
>

diff(x^2 + x + 1/x, x);

${2}{}{x}{+}{1}{}\frac{{1}}{{{x}}^{{2}}}$
 (7) 
Note the difference between the names used in these two examples. In the first example, a is a variable with an assigned value. In the second example, x is a symbol with no assigned value. Maple can represent and compute with symbolic expressions.
For more information about the Maple library commands, refer to the Maple User Manual or the help system.



1.4 Procedures


This section introduces the concept of procedures in Maple. For more information about procedures, see Procedures.

Defining a Simple Procedure


A Maple procedure (a type of program) is a group of statements that are processed together. The easiest way to create a Maple procedure is to enclose a sequence of commands, which can be used to perform a computation interactively, between the proc(...) and end proc statements.


Entering a Procedure Definition


The following procedure generates the string "Hello World". Enter this procedure in a Maple session by entering its definition on one line.
>

hello := proc() return "Hello World"; end proc;

${\mathrm{hello}}{\u2254}{\mathbf{proc}}\left({}\right)\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{return}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{''Hello\; World''}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{end\; proc}}$
 (8) 
You can also enter a procedure or any Maple statement on multiple lines. To move the cursor to the next line as you are entering a multiline statement, hold the Shift key and press Enter at the end of each line.
Note: This is necessary in the interactive worksheet environment only. If you enter code in a code edit region, you can simply type the text and press Enter to move the cursor to next line. For more information on code edit regions, refer to the CodeEditRegion help page. For more information about using Shift+Enter, see Unexpected End of Statement.
You can indent lines in a procedure by using the spacebar. After you enter the last line, end proc;, press Enter.
>

hello := proc()
return "Hello World";
end proc;

${\mathrm{hello}}{\u2254}{\mathbf{proc}}\left({}\right)\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{return}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{''Hello\; World''}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{end\; proc}}$
 (9) 
To run this procedure, enter its name followed by a set of parentheses and a semicolon:
${''Hello\; World''}$
 (10) 
Procedures can also accept arguments. Consider the following example.
>

half := proc(x)
evalf(x/2);
end proc;

${\mathrm{half}}{\u2254}{\mathbf{proc}}\left({x}\right)\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathrm{evalf}}{}\left({1}{\/}{2}{\*}{x}\right)\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{end\; proc}}$
 (11) 
This procedure requires one input, x. The procedure computes the approximation of the value of x divided by 2. When a return statement is not specified, a Maple procedure returns the result of the last statement that was run. Since evalf(x/2) is the last calculation performed in the procedure half (in fact, it is the only calculation), the result of that calculation is returned.
The procedure is named half by using the := notation in the same way that you would assign any other object to a name. After you have named a procedure, you can use it as a command in the current Maple session. The syntax to run your procedure is the same syntax used to run a Maple library command: enter the procedure name followed by the input to the procedure enclosed in parentheses.
Recall, a was assigned the value 103993/33102.
The basic syntax for a procedure is given below.
The letter P indicates the parameters. The body of the procedure is between the proc and end proc keywords.
Consider the following two statements, which calculate the angle in a right triangle given the lengths of two sides.
>

theta := arcsin(opposite/hypotenuse);

${\mathrm{\theta}}{\u2254}{\mathrm{arcsin}}{}\left(\frac{{\mathrm{opposite}}}{{\mathrm{hypotenuse}}}\right)$
 (15) 
${57.29577950}{}{\mathrm{arcsin}}{}\left(\frac{{\mathrm{opposite}}}{{\mathrm{hypotenuse}}}\right)$
 (16) 
The following example shows a procedure that corresponds to these statements. The procedure definition contains two input parameters for the length of two sides of a right triangle.
>

GetAngle := proc( opposite, hypotenuse )
local theta;
theta := arcsin(opposite/hypotenuse);
evalf(180/Pi*theta);
end proc;

${\mathrm{GetAngle}}{\u2254}{\mathbf{proc}}\left({\mathrm{opposite}}{\,}{\mathrm{hypotenuse}}\right)\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{local}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathrm{\θ}}{\;}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathrm{\θ}}{\u2254}{\mathrm{arcsin}}{}\left({\mathrm{opposite}}{\/}{\mathrm{hypotenuse}}\right){\;}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathrm{evalf}}{}\left({180}{\*}{\mathrm{\θ}}{\/}{\mathrm{\π}}\right)\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{end\; proc}}$
 (17) 
When you run the procedure definition, the output shown is the Maple interpretation of this procedure definition. Examine it carefully and note the following characteristics.
•

The name of this procedure (program) is GetAngle. Note that Maple is casesensitive, so GetAngle is distinct from getangle.

•

The procedure definition starts with proc( opposite, hypotenuse ). The two names in parentheses indicate the parameters, or inputs, of the procedure.

•

Semicolons or colons separate the individual commands of the procedure.

•

The local theta; statement declares theta as a local variable. A local variable has meaning in the procedure definition only. Therefore, if you were to declare another variable called theta outside of the procedure, that variable would be different from the local variable theta declared in the procedure and you could use theta as a variable name outside of the procedure GetAngle without conflict.

For more information about local variables, see Variables in Procedures.
•

Pi is a predefined variable in Maple. Two predefined functions, evalf and arcsin, are used in the calculation.

•

The end proc keywords and a colon or semicolon indicate the end of the procedure.

•

As you enter the procedure, the commands of the procedure do not display output. The procedure definition is displayed as output only after you complete it with end proc and a semicolon.

•

There is no explicit return statement, so the result of calling the procedure is the result of the last calculation.

•

The procedure definition that displays in the output is equivalent to, but not identical to, the procedure definition you enter. When Maple parses the statement, the commands of the procedure may be simplified.

The procedure definition syntax is flexible. You can do the following:
•

Enter each statement on one or more lines

•

Enter multiple statements on one line, provided they are separated by colons or semicolons

•

Place extra semicolons between statements

•

Omit the semicolon (or colon) from the statement preceding end proc

To hide the output resulting from a complicated procedure definition, use a colon instead of a semicolon at the end of the definition.


Adding Comments to a Procedure


Consider the following example.
(* this procedure computes an interior angle of a right
You can include single line comments anywhere in the procedure. They begin with a pound character (#). You can also enter multiline comments between (* and *) symbols as shown in the example above.
Note: Multiline comments cannot be entered in 2D math notation. As an alternative, in a Maple document, you can enter comments as text by adding a paragraph above or below the Maple statement.


Calling a Procedure


Running a procedure is referred to as an invocation or a procedure call. When you invoke a procedure, Maple runs the statements that form the procedure body one at a time. The result of the last computed statement within the procedure is returned as the value of the procedure call.
For example, to run the procedure GetAnglethat is, to cause the statements that form the procedure to be run in sequenceenter its name followed by parentheses enclosing the inputs, in this case, two numbers delimited (separated) by commas (,). End the statement with a semicolon.
Only the result of the last calculation performed within the procedure GetAngle is returnedthe result of evalf(180/Pi*theta). The assignment theta:=arcsin(opposite/hypotenuse); is performed, but the statement result is not displayed.


Maple Library Commands, BuiltIn Commands, and UserDefined Procedures


Maple comes with a large collection of commands and packages. Before writing custom procedures, refer to the Maple help system to find out which commands are available. You can easily include complex tasks in your userdefined procedures by using existing Maple commands instead of writing new code.
Maple commands are implemented in one of two formats: those written and compiled in an external language such as C and those written in the Maple programming language.
The commands that are compiled as part of the Maple kernel are referred to as builtin commands. These are widely used in computations, and are fundamental for implementing other Maple commands.
For more information about builtin kernel commands, see The Computation Engine and The builtin Option.
The commands in the Maple library are written in the Maple programming language. These commands exist as individual commands or as packages of commands. They are accessed and interpreted by the Maple system as required. The code for the library commands and the definitions of userdefined procedures can be viewed and modified. However, before exploring library commands, it is important that you learn about evaluation rules to understand the code.


Full Evaluation and Last Name Evaluation


For most expressions assigned to a name, such as e defined with the following statement, you can obtain its value by entering its name.
This is called full evaluationeach name in the expression is fully evaluated to the last assigned expression in any chain of assignments. The following statements further illustrate how full evaluation works.
This group of statements creates the chain of assignments. $c\to b\to a\to 1$, and c fully evaluates to 1.
If you try this approach with a procedure, Maple displays only the name of the procedure instead of its value (the procedure definition). For example, in the previous section, GetAngle is defined as a procedure. If you try to view the body of procedure GetAngle by referring to it by name, the procedure definition is not displayed.
${\mathrm{GetAngle}}$
 (25) 
This model of evaluation is called last name evaluation and it hides the procedure details. There are several reasons for this approach relating to advanced evaluation topics. The most important concept to understand is that you will only see the name of a procedure when you reference it by itself or when it is returned unevaluated; you will not see the full procedure definition. To obtain the value of the name GetAngle, use the eval command, which forces full evaluation.
Last name evaluation applies to procedures, tables, and modules in Maple. For more information, refer to the last_name_eval help page.
${\mathrm{GetAngle}}$
 (26) 


Viewing Procedure Definitions and Maple Library Code


You can learn about programming in Maple by studying the procedure definitions of Maple library commands. To print the body of Maple library commands, set the Maple interface variable verboseproc to 2, and then use the print command.
For example, to view the procedure definition for the Maple least common multiple command, lcm, enter the following statements.
For more information about interface variables, refer to the interface help page.
>

interface(verboseproc = 2):

${\mathbf{proc}}\left({a}{\,}{b}\right)\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{option}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathrm{remember}}{\,}{\mathrm{Copyright\; (c)\; 1990\; by\; the\; University\; of\; Waterloo.\; All\; rights\; reserved.}}{\;}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{local}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{t}{\;}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{if}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathrm{nargs}}{\=}{0}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{then}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{1}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{elif}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathrm{nargs}}{\=}{1}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{then}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{t}{\u2254}{\mathrm{expand}}{}\left({a}\right){\;}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathrm{sign}}{}\left({t}\right){\*}{t}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{elif}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{2}{<}{\mathrm{nargs}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{then}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathrm{foldl}}{}\left({\mathrm{procname}}{\,}{\mathrm{args}}\right)\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{elif}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathrm{type}}{}\left({a}{\,}{\'}{\mathrm{integer}}{\'}\right)\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{and}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathrm{type}}{}\left({b}{\,}{\'}{\mathrm{integer}}{\'}\right)\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{then}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathrm{ilcm}}{}\left({a}{\,}{b}\right)\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{else}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathrm{gcd}}{}\left({a}{\,}{b}{\,}{\'}{t}{\'}\right){\;}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{t}{\*}{b}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{end\; if}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{end\; proc}}$
 (27) 
Because the builtin kernel commands are compiled in machine code, and not written in the Maple language, you cannot view their definitions. If you print the definition of a builtin procedure, you will see that the procedure has only an option builtin statement and no visible body.
${\mathbf{proc}}\left({}\right)\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{option}}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathrm{builtin}}{\=}{\mathrm{add}}{\;}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{end\; proc}}$
 (28) 



1.5 Interrupting Computations and Clearing the Internal Memory



Interrupting a Maple Computation


To stop a computation, for example, a lengthy calculation or infinite loop, use one of the following methods.
Note: Maple may not always respond immediately to an interrupt request if it is performing a complex computation. You may need to wait a few seconds before the computation stops.
•

Click the interrupt icon
in the toolbar (in worksheet versions). See Figure 1.1.


Figure 1.1: Maple Toolbar



Note: For more information on the toolbar icons, refer to the worksheet/reference/WorksheetToolbar help page.
•

Hold the Ctrl key and press the C key (in UNIX and Windows commandline versions).

•

Hold the Command key and press the period key (.) (in Macintosh commandline and worksheet versions).

To perform a hard interrupt, which stops the computation and exits the Maple session, in the Windows commandline interface, hold the Ctrl key and press the Break key.


Clearing the Maple Internal Memory


Clear the internal memory during a Maple session by entering the restart command or clicking the restart icon
in the worksheet toolbar. When you enter this command, the Maple session returns to its startup state, that is, all identifiers (including variables and procedures) are reset to their initial values.
For more information on clearing the Maple internal memory and the restart command, refer to the restart help page. For more information on the toolbar icons, refer to the worksheet/reference/WorksheetToolbar help page.
Maple tracks the use of permanent and temporary objects. Its internal garbage collection facility places memory that is no longer in use on free lists so it can be used again efficiently as needed. For more information on garbage collection and the gc command, see Garbage Collection.



1.6 Avoiding Common Problems


This section provides a list of common mistakes, examples, and hints that will help you understand and avoid common errors. Use this section to study the errors that you may encounter when entering the examples from this chapter in a Maple session.

Unexpected End of Statement


Valid statements in Maple can end with a semicolon or nothing to execute a command, or with a colon to suppress the output of a command. However, semicolons are required for procedure statements. An error message is displayed if you press Enter in an input region that is incomplete.
Tip: You can use the parse command to find errors in statements, and the Maple debugger to find errors in programs. For more information on the debugger, see The Maple Debugger: A Tutorial Example or refer to the parse and debugger help pages.
If you press Enter to move the cursor to a new line when you are entering a procedure definition on multiple lines, the following error is displayed.
To prevent this error message from displaying as you enter a procedure definition, hold the Shift key and press Enter at the end of each line, instead of pressing only Enter.
>

p := proc()
"Hello World";
end proc;

${p}{\u2254}{\mathbf{proc}}\left({}\right)\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{''Hello\; World''}\phantom{\rule[0.0ex]{0.5em}{0.0ex}}{\mathbf{end\; proc}}$
 (29) 


Missing Operator


The most common error of this type is omitting the multiplication operator.
You can avoid this error by entering an asterisk (*) to indicate multiplication.
Implicit multiplication, which can be used in 2D math input, is not valid syntax in 1D math input.


Invalid, Wrong Number or Type of Arguments


An error is displayed if the argument(s) to a Maple library command are incorrect or missing.
If such an error occurs, check the appropriate help page for the correct syntax. Enter ?topic_name at the Maple prompt.
The same type of error message is displayed if you call a userdefined procedure, such as GetAngle, with the wrong number of the arguments.


Unbalanced Parentheses


In complicated expressions or nested commands, it is easy to omit a closing parenthesis.
In a valid statement, each (, {, and [ requires a matching ), }, and ], respectively.
$\left\{\left[{0}{\,}{1}\right]{\,}\left[{1}{\,}{0}\right]\right\}$
 (31) 


Assignment Versus Equality


When you enter statements in a Maple session, it is important to understand the difference between equality (using =) and assignment (using :=).
The equal sign, =, is used in equality tests or to create equations. Creating an equation is a valid Maple statement.
${x}{=}{{y}}^{{2}}{+}{3}$
 (32) 
$\sqrt{{x}{}{3}}{,}{}\sqrt{{x}{}{3}}$
 (33) 
In the example above, % is a special name that stores the value of the last statement. The solve command is used to isolate y in the equation defined in the first statement. The first statement is not an assignment; x remains a symbol with no assigned value.
You can use the assignment statement, :=, to assign x the value y^2+3. The assignment statement assigns the value of the righthand side to the lefthand side. After an assignment is made, the lefthand side can be used in place of the value of the righthand side. The lefthand side cannot be a number; it must be a name, indexed name, function call, or sequence of these values.
${x}{\u2254}{{y}}^{{2}}{+}{3}$
 (35) 
${\mathrm{I}}{}\sqrt{{3}}{,}{\mathrm{I}}{}\sqrt{{3}}$
 (36) 
For more information about equations and Boolean testing, see Boolean and Relational Expressions or refer to the evalb help page. For more information about names and assignment, see Names and Assignments.



1.7 Exercises


1.

Assign the integers 12321, 23432, and 34543 to the names a, b, and c. Use these names to find the sum and difference of each pair of numbers.

2.

Write two procedures. The first requires two inputs and finds their sum. The second requires two inputs and finds their product. Use these procedures to add and multiply pairs of numbers. How could you use these procedures to add and multiply three numbers?

3.

Display your procedure definitions. Are they identical to the code you entered to write them?



Contents Previous Next Index
