Contents Previous Next Index
9 Basic Programming
You have used Maple interactively in the previous chapters, sequentially performing operations such as executing a single command. Because Maple has a complete programming language, you can also use sophisticated programming constructs.
In Maple, you can write programs called procedures, and save them in modules. These modules can be used and distributed in the same way as Maple packages.
Important: It is strongly recommended that you use the Worksheet mode and 1-D Math input when programming or using programming commands. Hence, all input in this chapter is entered as 1-D Math.
9.1 In This Chapter
Section
Topics
Flow Control - Basic programming constructs: if-then statements and loops
Conditional Execution (if Statement)
Repetition (for Statement)
Iterative Commands - Specialized, efficient iterative commands
Creating a sequence
Adding and Multiplying Expressions
Selecting Expression Operands
Mapping a Command over a Set or List
Mapping a Binary Command over Two Lists or Vectors
Procedures - Maple programs
Defining and Running Simple Procedures
Procedures with Inputs
Procedure Return Values
Displaying Procedure Definitions
Displaying Maple Library Procedure Definitions
Modules
Programming in Documents - Display methods for Maple code
Code Edit Region
Startup Code
Document Blocks
9.2 Flow Control
Two basic programming constructs in Maple are the if statement, which controls the conditional execution of statement sequences, and the for statement, which controls the repeated execution of a statement sequence (a loop).
You can specify that Maple perform an action only if a condition holds. You can also perform an action, from a set of many, depending on which conditions hold.
Using the if statement, you can execute one statement from a series of statements based on a boolean (true, false, or FAIL) condition. Maple tests each condition in order. When a condition is satisfied, Maple executes the corresponding statement, and then exits the if statement.
Syntax
The if statement has the following syntax.
The conditional expressions (conditional_expression1, conditional_expression2, ...) can be any boolean expression. You can construct boolean expressions using:
Relational operators - <, <=, =, >=, >, <>
Logical operators - and, or, xor, implies, not
Logical names - true, false, FAIL
The statement sequences (statement_sequence1, statement_sequence2, ..., statement_sequenceN) can be any sequence of Maple statements, including if statements.
The elif clauses are optional. You can specify any number of elif clauses.
The else clause is optional.
Simple if Statements
The simplest if statement has only one conditional expression.
If the conditional expression evaluates to true, the sequence of statements is executed. Otherwise, Maple immediately exits the if statement.
For example:
x := 1173:
if not isprime(x) then ifactor(x); end if;
⁡3⁢⁡17⁢⁡23
else Clause
In a simple if statement with an else clause, if the evaluation of the conditional expressions returns false or FAIL, Maple executes the statement sequence in the else clause.
if false then "if statement"; else "else statement"; end if;
else statement
elif Clauses
In an if statement with elif clauses, Maple evaluates the conditional expressions in order until one returns true. Maple executes the corresponding statement sequence, and then exits the if statement. If no evaluation returns true, Maple exits the if statement.
The keyword elif stands for else if.
x := 11:
if not type(x, integer) then printf("%a is not an integer.", x); elif x >= 10 then printf("%a is an integer with more than one digit.", x); elif x >= 0 then printf("%a is an integer with one digit.", x); end if;
11 is an integer with more than one digit.
Order of elif Clauses: An elif clause's statement sequence is executed only if the evaluation of all previous conditional expressions returns false or FAIL, and the evaluation of its conditional expression returns true. This means that changing the order of elif clauses may change the behavior of the if statement.
In the following if statement, the elif clauses are in the wrong order.
if not(type(x, integer)) then printf("%a is not an integer.", x); elif x >= 0 then printf("%a is an integer with one digit.", x); elif x >= 10 then printf("%a is an integer with more than one digit.", x); end if;
11 is an integer with one digit.
elif and else Clauses
In an if statement with elif and else clauses, Maple evaluates the conditional expressions in order until one returns true. Maple executes the corresponding statement sequence, and then exits the if statement. If no evaluation returns true, Maple executes the statement sequence in the else clause.
x := -12:
if not type(x, integer) then printf("%a is not an integer.", x); elif x >= 10 then printf("%a is an integer with more than one digit.", x); elif x >= 0 then printf("%a is an integer with one digit.", x); else printf("%a is a negative integer.", x); end if;
-12 is a negative integer.
For more information on the if statement, refer to the if help page.
Using repetition statements, you can repeatedly execute a statement sequence. You can repeat the statements in three ways.
Until a counter variable value exceeds a limit (for/from loop)
For each operand of an expression (for/in loop)
Until a boolean condition does not hold (while loop or until loop)
for/from Loop
The for/from loop statement repeats a statement sequence until a counter variable value exceeds a limit.
The for/from loop has the following syntax.
The behavior of the for/from loop is:
Assign the initial value to the name counter.
Compare the value of counter to the value of final. If the counter value exceeds the final value, exit the loop. (This is the loop bound test.)
Execute the statement_sequence.
Increment the counter value by the value of increment.
Repeat steps 2 to 4, until Maple exits the loop.
The from, by, and to clauses are optional and can be in any order between the for clause and the do keyword. Table 9.1 lists the default clause values.
Clause
Default Value
from initial
1
by increment
to final
infinity (∞)
Examples
The following loop returns the square root of the integers 1 to 5 (inclusive).
fornto5doevalf⁡sqrt⁡nenddo
1.
1.414213562
1.732050808
2.
2.236067977
When the value of the counter variable n is strictly greater than 5, Maple exits the loop.
n
6
The previous loop is equivalent to the following for/from statement.
The by value can be negative. The loop repeats until the value of the counter variable is strictly less than the final value.
fornfrom10by−1to3doifisprime⁡nthenprint⁡nendifenddo
7
5
3
2
for/in Loop
The for/in loop statement repeats a statement sequence for each component (operand) of an expression, for example, the elements of a list.
The for/in loop has the following syntax.
The for clause must appear first.
The behavior of the for/in loop is:
Assign the first operand of expression to the name variable.
Assign the next operand of expression to variable.
Repeat steps 2 and 3 for each operand in expression. If there are no more operands, exit the loop. (This is the loop bound test.)
Example
The following loop returns a floating-point approximation to the sin function at the angles (measured in degree) in the list L.
L := [23.4, 87.2, 43.0, 99.7]:
for i in L do evalf(sin(i*Pi/180)); end do;
0.3971478907
0.9988061374
0.6819983602
0.9857034690
while Loop and until Loop
The while loop repeats a statement sequence until a boolean expression does not hold.
The until loop also repeats a statement sequence until a boolean expression does not hold, but it tests the terminating condition at the end of each iteration of the loop, instead of the beginning.
The while loop has the following syntax.
A while loop repeats until its boolean expression conditional_expression evaluates to false or FAIL. For more information on boolean expressions, see Conditional Execution (if Statement).
The until loop has the following syntax.
Note the difference in syntax: the until clause appears in place of end do
Compare the following loops. In the first one, the terminating condition is met the first time it is tested, and the loop terminates immediately. In the second one, which uses the until clause, the body of the loop is performed before the condition is tested, and the loop is used.
a:=1;
a≔1
while a mod 7 <>1 do a:=a+1; end do:
a;
do a:=a+1; until a mod 7=1:
8
The following loop computes the digits of 872,349 in base 7 (in order of increasing significance).
x := 872349:
while x > 0 do irem(x, 7); x := iquo(x, 7); end do;
x:=124621
0
x:=17803
x:=2543
x:=363
x:=51
x:=7
x:=1
x:=0
To perform such conversions efficiently, use the convert/base command.
convert(872349, base, 7);
2,0,2,2,6,2,0,1
For information on non-base 10 numbers, see Non-Base 10 Numbers.
General Loop Statements
You can include a while statement in a for/from or for/in loop.
The general for/from loop has the following syntax.
The general for/in loop has the following syntax.
After testing the loop bound condition at the beginning of each iteration of the for loop, Maple evaluates conditional_expression.
If conditional_expression evaluates to false or FAIL, Maple exits the loop.
If conditional_expression evaluates to true, Maple executes statement_sequence.
The equivalent general until loops have the same form but with end do replaced with until conditional_expression.
Infinite Loops
You can construct a loop for which there is no exit condition, for example, a while loop in which the conditional_expression always evaluates to true. This is called an infinite loop. Maple indefinitely executes an infinite loop unless it executes a break, quit, or return statement or you interrupt the computation using the interrupt icon in the toolbar (in worksheet versions).
Additional Information
For more information on the for statement and looping, refer to the do help page and the Loops section of the Maple Statements chapter of the Maple Programming Guide.
9.3 Iterative Commands
Maple has commands that perform common selection and repetition operations. These commands are more efficient than similar algorithms implemented using library commands. Table 9.2 lists the iterative commands.
Command
Description
seq
Create sequence
add
Compute numeric sum
mul
Compute numeric product
select
Return operands that satisfy a condition
remove
Return operands that do not satisfy a condition
selectremove
Return operands that satisfy a condition and separately return operands that do not satisfy a condition
map
Apply command to the operands of an expression
zip
Apply binary command to the operands of two lists or vectors
Creating a Sequence
The seq command creates a sequence of values by evaluating a specified expression over a range of index values or the operands of an expression. See Table 9.3.
Calling Sequence Syntax
seq(expression, name = initial .. final);
seq(exp(x), x=-2..0);
ⅇ−2,ⅇ−1,1
seq(expression, name in expression);
seq(u, u in [Pi/4, Pi^2/2, 1/Pi]);
π4,π22,1π
The add and mul commands add and multiply sequences of expressions over a range of index values or the operands of an expression. See Table 9.4.
add(expression, name = initial .. final);
mul(expression, name = initial .. final);
add(exp(x), x = 2..4);
ⅇ2+ⅇ3+ⅇ4
mul(2*x, x = 1 .. 10);
3715891200
add(expression, name in expression);
mul(expression, name in expression);
add(u, u in [Pi/4, Pi/2, Pi]);
74⁢π
mul(u, u in [Pi/4, Pi/2, Pi]);
18⁢π3
The endpoints of the index range (initial and final) in the add and mul calling sequence must evaluate to numeric constants. For information on symbolic sums and products, refer to the sum and product help pages.
The select, remove, and selectremove commands apply a boolean-valued procedure or command to the operands of an expression. For information on operands, refer to the op help page.
The select command returns the operands for which the procedure or command returns true.
The remove command returns the operands for which the procedure or command returns false or FAIL.
The selectremove command returns two expressions of the same type as the input expression. - The first consists of the operands for which the procedure or command returns true. - The second consists of the operands for which the procedure or command returns false or FAIL.
The structure of the output is the same as the structure of the input. See Table 9.5.
For information on Maple procedures, see Procedures.
select(proc_cmd, expression);
select(issqr, {198331, 889249, 11751184, 9857934});
889249,11751184
remove(proc_cmd, expression);
remove(var -> degree(var) > 3, 2*x^3*y - y^3*x + z );
z
selectremove(proc_cmd, expression);
selectremove(x -> evalb(x > round(x)), [sin(0.), sin(1.), sin(3.)]);
0.1411200081,0.,0.8414709848
For information on optional arguments to the selection commands, refer to the select help page.
The map command applies a name, procedure, or command to each element in a set or list. See Table 9.6.
map(name_proc_cmd, expression);
map(f, {a, b, c});
f⁡a,f⁡b,f⁡c
map(u -> int(cos(x), x = 0 .. u), [Pi/4, Pi/7, Pi/3.0]);
22,cos⁡5⁢π14,0.8660254037
An alternative to the map command is to apply a function elementwise, using ~. For more information ~, see Applying an Operation or Function to All Elements in a List, Set, Table, Array, Matrix, or Vector. For information on mapping over the operands of other expressions, optional arguments to the map command, and other mapping commands, refer to the map help page.
The zip command applies a name or binary procedure or command component-wise to two lists or vectors.
By default, the length of the returned object is that of the shorter list or vector. If you specify a value as the (optional) fourth argument, it is used as the value of the missing elements of the shorter list or vector. In this case, the length of the return value is that of the longer list or vector. See Table 9.7.
zip(proc_cmd, a, b);
zip(proc_cmd, a, b, fill);
zip(f, [i, j], [k, l]);
f⁡i,k,f⁡j,l
zip(AiryAi, [1, 2], [0], 1);
−316⁢Γ⁡232⁢π,Ai″⁡1
This is equivalent to AiryAi1,0,AiryAi2,1.
For more information on the zip command, refer to the zip help page.
For more information on looping commands, refer to the corresponding command help page.
9.4 Procedures
A Maple procedure is a program consisting of Maple statements. Using procedures, you can quickly execute the contained sequence of statements.
To define a procedure, enclose a sequence of statements between proc(...) and end proc statements. In general, you assign a procedure definition to a name.
The following procedure returns the square root of 2.
p := proc() sqrt(2); end proc;
p:=procsqrt⁡2end proc
Note: Maple returns the procedure definition.
To improve readability of procedures, it is recommended that you define a procedure using multiple lines, and indent the lines using space characters. To begin a new line (without evaluating the incomplete procedure definition), press Shift+Enter. When you have finished entering the procedure, press Enter to create the procedure.
p := proc() sqrt(2); end proc:
To run the procedure p, enter its name followed by parentheses (( )).
p();
You can define a procedure that accepts user input. In the parentheses of the proc statement, specify the parameter names. For multiple parameters, separate the names with commas.
geometric_mean := proc(x, y) sqrt(x*y); end proc:
When the user runs the procedure, the parameter names are replaced by the argument values.
geometric_mean(13, 17);
221
geometric_mean(13.5, 17.1);
15.19374871
For more information on writing procedures, including options and local and global variables, refer to the procedure help page.
When you run a procedure, Maple returns only the last statement result value computed. Maple does not return the output for each statement in the procedure. It is irrelevant whether you use semicolons or colons as statement separators.
p := proc(a, b) a + b; a - b: end proc:
p(1, 2);
−1
Unlike simple Maple objects, you cannot display the value of a procedure by entering its name.
geometric_mean;
geometric_mean
You must evaluate the name of the procedure using the print (or eval) command.
print(geometric_mean);
procx,ysqrt⁡y*xend proc
Maple procedure definitions are a valuable learning tool. To learn how to program in Maple, it is recommended that you examine the procedures available in the Maple library.
By default, the print command returns only the proc and end proc statements and (if present) the description fields of a Maple procedure.
print(lcm);
proca,b...end proc
To display a Maple library procedure definition, first set the value of the interface verboseproc option to 2. Then re-execute the print calling sequence.
interface('verboseproc' = 2):
proca,boptionremember,Copyright (c) 1990 by the University of Waterloo. All rights reserved.;localq,t;ifnargs=0then1elifnargs=1thent ≔ expand⁡a;sign⁡t*telif2<nargsthenfoldl⁡procname,argseliftype⁡a,'integer'andtype⁡b,'integer'thenilcm⁡a,belsegcd⁡a,b,'q';q*bend ifend proc
Maple procedures associate a sequence of commands with a single command. The module, a more complex programming structure, allows you to associate related procedures and data.
A key feature of modules is that they export variables. This means that the variables are available outside the module in which they are created. Most Maple packages are implemented as modules. The package commands are exports of the module.
For more information on modules, refer to the module help page.
Objects
Objects take the idea of associating data and procedures beyond what modules provide. With objects, multiple instances of a class of objects can be created. Each individual object can have its own data, yet share other values and procedures with the entire class objects. A well implemented class of objects can be used in Maple as naturally as a built-in Maple type.
For more information on objects, refer to the object help page.
9.5 Programming in Documents
To write Maple code, you could simply open a Maple worksheet and start typing. However, if you want to create a readable document with the code interspersed or hidden, there are several options available: code edit regions and start up code. Both these features use a code editor which has features such as syntax highlighting and line numbers.
The code edit region allows you to program in one contained region, in a natural way. Features include the ability to press Enter for line breaking and indentation preservation. Figure 9.1 shows the expanded code edit region.
To insert a new code edit region into your worksheet:
From the Insert menu, select Code Edit Region.
Figure 9.1: Code Edit Region
To execute the code within this region, click anywhere in this region, then click the Execute Selection icon ( ) on the toolbar. (Alternatively, from the Evaluate menu, select Execute Code.)
You can hide the code in a code edit region by minimizing the region. To minimize, select View → Collapse Code Edit Region. When the region is minimized, an icon appears with the first line of the code written next to it. It is recommended that you make the first line a comment describing the program or programs contained in the region. See Figure 9.2.
Figure 9.2: Collapsed Code Edit Region
To re-execute the code in the region while it is collapsed, click this icon.
For more information, refer to the CodeEditRegion help page.
Startup code allows you to define commands and procedures that are executed each time the document is opened and after restart is called. This code is completely hidden to others reading the document. For example, use this region to define procedures that will be used throughout the document code but that would take up space and distract readers from the message of the document.
To enter startup code for a document:
From the Edit menu, select Startup Code. Alternatively, click the startup code icon in the toolbar, .
Enter commands to be run each time the worksheet is opened or restart is called.
To check the syntax of the entered code while entering your Maple commands or before closing the editor, from the Edit menu. select Check Syntax Now.
Note: You can also check the Check Syntax Automatically option to enable continuous syntax checking. It is recommended that you check the syntax before saving so that your startup code does not prevent Maple from opening successfully.
To save the contents, from the File menu, select Save Code. Alternatively, click the save icon, .
Close Startup Code.
Figure 9.3: Startup Code Editor
For more information, refer to the startupcode help page.
9.6 Additional Information
The Maple Programming Guide provides an in-depth reference for programming in Maple. Topics include statements, data structures, procedures, packages, and debugging your code.
Access via the help system. From the Table of Contents, select Manuals>Programming Guide.
The Programming Guide is also available as a PDF on the Maplesoft website.
http://www.maplesoft.com/documentation_center
Download Help Document