Contents Previous Next Index
1 Introduction to Programming in Maple
Maple provides an interactive problem-solving 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
Maple statements
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
The computation engine
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 built-in commands.
The Maple kernel also consists of kernel extensions, which are collections of external compiled libraries that are included in Maple to provide low-level 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 high-level 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 1-D 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.
2 + 3;
5
2 + 3:
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";
Hello World
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.
(44*3+13)^2/116;
7254
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 := 103993/33102;
a≔10399333102
2 * a;
10399316551
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 floating-point (decimal) approximation to 103993/33102 divided by 2 by entering the following statement.
evalf(a/2);
1.570796326
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−1x2
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;
hello≔procreturnHello Worldend proc
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.
To run this procedure, enter its name followed by a set of parentheses and a semicolon:
hello();
Procedures can also accept arguments. Consider the following example.
half := proc(x) evalf(x/2); end proc;
half≔procxevalf⁡1/2*xend proc
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.
half(2/3);
0.3333333333
Recall, a was assigned the value 103993/33102.
half(a);
half(1) + half(2);
1.500000000
The basic syntax for a procedure is given below.
proc( P ) ... end proc
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);
θ≔arcsin⁡oppositehypotenuse
evalf(180/Pi*theta);
57.29577950⁢arcsin⁡oppositehypotenuse
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;
GetAngle≔procopposite,hypotenuselocalθ;θ ≔ arcsin⁡opposite/hypotenuse;evalf⁡180*θ/πend proc
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 case-sensitive, 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.
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 in 2-D input should only contain text. 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 GetAngle--that is, to cause the statements that form the procedure to be run in sequence--enter its name followed by parentheses enclosing the inputs, in this case, two numbers delimited (separated) by commas (,). End the statement with a semicolon.
GetAngle(4,5);
53.13010234
Only the result of the last calculation performed within the procedure GetAngle is returned--the result of evalf(180/Pi*theta). The assignment theta:=arcsin(opposite/hypotenuse); is performed, but the statement result is not displayed.
Maple Library Commands, Built-In Commands, and User-Defined 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 user-defined 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 built-in commands. These are widely used in computations, and are fundamental for implementing other Maple commands.
For more information about built-in 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 user-defined 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.
restart;
e := 3;
e≔3
e;
3
This is called full evaluation--each 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.
c := b;
c≔b
b := a;
b≔a
a := 1;
a≔1
c;
1
This group of statements creates the chain of assignments. c→b→a→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.
GetAngle;
GetAngle
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.
eval(GetAngle);
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):
print(lcm);
proca,boptionremember,Copyright (c) 1990 by the University of Waterloo. All rights reserved.;localt;ifnargs=0thenreturn1elifnargs=1thentryreturngcd⁡acatcharguments must be polynomials over the rationals:errorarguments must be polynomials over the rationalsend tryelif2<nargsthenreturnfoldl⁡procname,argseliftype⁡a,'integer'andtype⁡b,'integer'thenreturnilcm⁡a,bend if;gcd⁡a,b,'t';returnt*bend proc
Because the built-in 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 built-in procedure, you will see that the procedure has only an option builtin statement and no visible body.
print(add);
procoptionbuiltin=add;end proc
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 command-line versions).
Hold the Command key and press the period key (.) (in Macintosh command-line and worksheet versions).
To perform a hard interrupt, which stops the computation and exits the Maple session, in the Windows command-line 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.
p:=proc()
Warning, premature end of input, use <Shift> + <Enter> to avoid this message.
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≔procHello Worldend proc
Missing Operator
The most common error of this type is omitting the multiplication operator.
2 a + b;
Error, missing operator or `;`
You can avoid this error by entering an asterisk (*) to indicate multiplication.
2*a + b;
2⁢a+b
Implicit multiplication, which can be used in 2-D math input, is not valid syntax in 1-D 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.
evalf();
Error, invalid input: evalf expects 1 or 2 arguments, but received 0
solve(y=3*x+4, 5);
Warning, solving for expressions other than names or functions is not recommended.
Error, (in solve) a constant is invalid as a variable, 5
cos(x, y);
Error, (in cos) expecting 1 argument, got 2
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 user-defined 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.
{[1,0], [0,1};
Error, `}` unexpected
In a valid statement, each (, {, and [ requires a matching ), }, and ], respectively.
{[1,0], [0,1]};
0,1,1,0
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;
x=y2+3
solve(%,y);
x−3,−x−3
x;
x
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 right-hand side to the left-hand side. After an assignment is made, the left-hand side can be used in place of the value of the right-hand side. The left-hand side cannot be a number; it must be a name, indexed name, function call, or sequence of these values.
x := y^2+3;
x≔y2+3
solve(x,y);
I⁢3,−I⁢3
y2+3
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
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.
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?
Display your procedure definitions. Are they identical to the code you entered to write them?
Download Help Document