Introductory Programming Guide
Introductory Programming Guide
Introductory
Programming Guide
c Maplesoft, a division of Waterloo Maple Inc. 2005.
ii •
Maplesoft,
c a division of Waterloo Maple Inc. 2005. All rights re-
served.
Printed in Canada
ISBN 1-894511-76-X
Contents
Preface 1
Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Worksheet Graphical Interface . . . . . . . . . . . . . . . . . . 1
Manual Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
The Maple Programming Language . . . . . . . . . . . . . 3
Using This Book . . . . . . . . . . . . . . . . . . . . . . . 3
Customer Feedback . . . . . . . . . . . . . . . . . . . . . . . . . 4
iii
iv • Contents
Missing Operator . . . . . . . . . . . . . . . . . . . . . . . 18
Invalid, Wrong Number or Type of Arguments . . . . . . 19
Unbalanced Parentheses . . . . . . . . . . . . . . . . . . . 19
Assignment Versus Equality . . . . . . . . . . . . . . . . . 20
1.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Data Structures . . . . . . . . . . . . . . . . . . . . . . . . 89
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
3.3 Using Expressions . . . . . . . . . . . . . . . . . . . . . . 96
Investigating the Parts of an Expression . . . . . . . . . . 96
Evaluating and Simplifying Expressions . . . . . . . . . . 100
Unevaluated Expressions . . . . . . . . . . . . . . . . . . . 100
Substituting Subexpressions . . . . . . . . . . . . . . . . . 103
Displaying Large Expressions: Labels . . . . . . . . . . . . 105
Structured Types . . . . . . . . . . . . . . . . . . . . . . . 106
3.4 Statements . . . . . . . . . . . . . . . . . . . . . . . . . . 110
The Assignment Statement . . . . . . . . . . . . . . . . . 111
Selection Statements . . . . . . . . . . . . . . . . . . . . . 114
Repetition Statements . . . . . . . . . . . . . . . . . . . . 115
The read and save Statements . . . . . . . . . . . . . . . 117
The break and next Statements . . . . . . . . . . . . . . 118
The error and return Statements . . . . . . . . . . . . . 118
The use Statement . . . . . . . . . . . . . . . . . . . . . . 119
The quit Statement . . . . . . . . . . . . . . . . . . . . . 119
3.5 Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . 119
Syntax Errors . . . . . . . . . . . . . . . . . . . . . . . . . 120
Reserved Word Unexpected . . . . . . . . . . . . . . . . . 120
Break or Next Not in Loop . . . . . . . . . . . . . . . . . 121
3.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
3.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . 314
8.3 Detecting Errors . . . . . . . . . . . . . . . . . . . . . . . 315
Tracing a Procedure . . . . . . . . . . . . . . . . . . . . . 315
Using Assertions . . . . . . . . . . . . . . . . . . . . . . . 320
Handling Exceptions . . . . . . . . . . . . . . . . . . . . . 323
Checking Syntax . . . . . . . . . . . . . . . . . . . . . . . 329
8.4 Creating Efficient Programs . . . . . . . . . . . . . . . . . 330
Displaying Time and Memory Statistics . . . . . . . . . . 330
Profiling a Procedure . . . . . . . . . . . . . . . . . . . . . 332
8.5 Managing Resources . . . . . . . . . . . . . . . . . . . . . 334
Setting a Time Limit on Computations . . . . . . . . . . . 334
Garbage Collection . . . . . . . . . . . . . . . . . . . . . . 335
Communicating with the Kernel . . . . . . . . . . . . . . 336
8.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
8.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . 337
Index 371
Preface
Audience
As a Maple user, you may have only used Maple interactively, written
Maple programs, or programmed in another computer language.
You should be familiar with the following:
• Example worksheets
1
The command-line version provides optimum performance. However, the worksheet
interface is easier to use and renders typeset, editable math output and higher quality
plots.
1
2 • Preface
Manual Set
There are three other manuals available for Maple users, the Maple Get-
ting Started Guide, the Maple User Manual, and the Maple Advanced
Programming Guide.2
• The Maple Getting Started Guide provides extensive information
for new users on using Maple, and the resources available in the soft-
ware and on the Maplesoft Web site (http://www.maplesoft.com).
Conventions
This manual uses the following typographical conventions.
• courier font - Maple command, package name, and option name
Customer Feedback
Maplesoft welcomes your feedback. For suggestions and comments related
to this and other manuals, email [email protected].
1 Introduction to
Programming in Maple
In This Chapter
• Components of the Maple software
• Maple statements
• User Interface
• Kernel
• Library
5
6 • Chapter 1: Introduction to Programming in Maple
1
For more information about the Maple user interface and worksheets, refer to the
Maple Getting Started Guide or Maple User Manual.
2
Throughout this book, the Maple notation (or one-dimensional) input format is
1.2 Maple Statements • 7
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 routine, or define a procedure.3
Most Maple statements must have a trailing semicolon (;) or colon (:).
If you enter a statement with a trailing semicolon, for most statements,
the result is displayed. However, if you enter a statement with a trailing
colon, the result is computed but not displayed.
> 2 + 3;
> 2 + 3:
Getting Help
To view an online 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.4 This
type of Maple statement does not have a trailing colon or semicolon.
“Hello World”
used to enter Maple statements. For more information on starting a Maple session,
toggling between Maple notation (the default on most platforms) and standard math
notation, and managing your files, refer to the Maple Getting Started Guide and Maple
User Manual or enter ?managing at the Maple prompt.
3
For more information about statements in Maple, see chapter 3.
4
For more information about getting help in Maple, refer to ?help and ?HelpGuide.
5
For more information about strings in Maple, see chapter 2 or refer to ?string.
8 • Chapter 1: Introduction to Programming in Maple
103993
33102
103993
33102
Assigning to a Name
By naming a calculated result or complicated expression, you can refer-
ence it. To assign to a name, use the assignment operator, :=.8
> a := 103993/33102;
103993
a :=
33102
> 2 * a;
6
To enter a statement on more than one line, hold the Shift key and press Enter
at the end of each line.
7
For more information about commands that control printing, see Printing Out-
put to the Screen on page 257. For information about arithmetic operators, see
page 70.
8
For more information about names and assignment, see chapter 2.
1.3 Procedures • 9
103993
16551
1.570796326
You can use the Maple library of routines, introduced on page 6, for
many purposes. For example, you can find the derivative of an expression
by using the diff command.9
> diff(x^2 + x + 1/x, x);
1
2x + 1 −
x2
1.3 Procedures
This section formally introduces the concept of procedures in Maple. For
more information about procedures, see chapter 6.
9
For more information about the Maple library routines, refer to the Maple User
Manual or the online help.
10 • Chapter 1: Introduction to Programming in Maple
“Hello World”
10
For more information, see Unexpected End of Statement on page 17.
1.3 Procedures • 11
0.3333333333
> half(a);
0.5000000000 a
1.500000000
103993
a :=
33102
> evalf(a/2);
1.570796326
The procedure definition for these statements does not explicitly re-
quire input, but it does include a local variable. A local variable a in a
procedure is different from the variable a outside the procedure (if one
exists). Thus, you can use a as a variable name outside of the procedure
f without conflict.11
> f := proc() local a;
> a := 103993/33102;
> evalf(a/2);
> end proc;
11
For more information about local variables, see Variables on page 201.
12 • Chapter 1: Introduction to Programming in Maple
f :=
proc() local a; a := 103993/33102 ; evalf(1/2 ∗ a) end proc
The interpretation of this procedure definition appears immediately
after the statements that define it. Examine it carefully and note the
following characteristics.
• The end proc keywords and colon or semicolon mark the end of the
procedure.
• Omit the semicolon (or colon) from the statement preceding end proc
12
For more information about local variables, see Variables on page 201.
1.3 Procedures • 13
1.570796326
13
For more information about built-in kernel routines, see page 207 or refer to
?builtin.
14 • Chapter 1: Introduction to Programming in Maple
The routines in the Maple library are written in the Maple program-
ming language. These routines exist as individual routines or as packages
of routines. They are accessed and interpreted by the Maple system as
required.
The code for the library routines and the definitions of user-defined
procedures can be viewed and modified. However, before exploring that, it
is important that you learn about evaluation rules so that you understand
the code.
Full Evaluation and Last Name Evaluation For most named objects in
Maple, such as e defined with the following command, you can obtain its
value by entering its name.
> e := 3;
e := 3
> e;
c := b
> b := a;
b := a
> a := 1;
a := 1
> c;
1
1.3 Procedures • 15
Viewing Procedure Definitions and Maple Library Code You can learn
about programming in Maple by studying the procedure definitions of
Maple library routines. To print the body of Maple library routines, set
the Maple interface variable verboseproc to 2, and then use the print
command.
Example Look at the procedure definition for the Maple least common
multiple routine, lcm, enter the following statements.15
> interface(verboseproc = 2):
> print(lcm);
14
Last name evaluation applies to procedures, tables, and modules in Maple. For
more information, refer to ?last_name_eval.
15
For more information about interface variables, see page 258 or refer to
?interface.
16 • Chapter 1: Introduction to Programming in Maple
proc(a, b)
local q, t;
optionremember , ‘Copyright (c) 1990 by the Unive\
rsity of Waterloo. All rights reserved .‘;
if nargs = 0 then 1
elif nargs = 1 then t := expand(a) ; sign(t) ∗ t
elif 2 < nargs then lcm(a, lcm(op(2..nargs, [args])))
elif type(a, integer ) and type(b, integer ) then ilcm(a, b)
else gcd(a, b, q) ; q ∗ b
end if
end proc
Because the built-in kernel routines are written in the C programming
language and compiled, you cannot view their definitions. If you print
the definition of a built-in procedure, the procedure body is comprised of
the option builtin statement and a positive integer that identifies the
procedure.
> print(add);
16
Maple does not always respond immediately to an interrupt request if it is perform-
ing a complex computation. You may need to wait a few seconds before the computation
is halted.
17
For more information on toolbar icons, refer to ?worksheet,reference,toolbar.
1.5 Troubleshooting • 17
• 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).
1.5 Troubleshooting
This section provides you with 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.20
18
For more information on toolbar icons, refer to ?worksheet,reference,toolbar.
19
For more information about clearing the Maple internal memory and the restart
command, refer to ?restart.
20
You can use the parse routine for finding errors in statements, and the Maple
debugger for finding errors in programs. For more information, see chapter 8, or refer
to ?parse and ?debugger.
18 • Chapter 1: Introduction to Programming in Maple
3
Maple also inserts a semicolon after end proc in procedure definition.
> p := proc()
> "Hello World";
> end proc
Missing Operator
The most common error of this type is omitting the multiplication oper-
ator.
> 2 a + b;
1.5 Troubleshooting • 19
2a + b
If such an error occurs, check the appropriate online help page for the
correct syntax. Enter ?topic_name at the Maple prompt.
Unbalanced Parentheses
In complicated expressions or nested commands, it is easy to omit a clos-
ing parenthesis.
> [(1,0), (0,1];
[1, 0, 0, 1]
20 • Chapter 1: Introduction to Programming in Maple
x=2
> x;
> evalb(x=2);
false
> x + 5;
x+5
x := 2
> x;
21
For more information about equations and Boolean testing, see page 84 or refer to
?evalb.
22
For more information about names and assignment, see pages 26 and 111, respec-
tively.
1.6 Exercises • 21
> evalb(x=2);
true
> x + 5;
1.6 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? 23
1.7 Conclusion
This chapter presented a basic overview of the Maple system and the
Maple programming language. The Maple system consists of three main
components: the kernel, which contains compiled built-in commands; the
library which contains routines written in the Maple programming lan-
guage; and, the interface, which handles the input and output of math-
ematical expressions and functions. You were introduced to the essential
elements of writing and executing Maple procedures, along with common
syntax errors related to writing procedures.
23
For more information about procedure definitions, see chapter 6.
22 • Chapter 1: Introduction to Programming in Maple
To learn more about the Maple programming language, read the re-
maining chapters in this guide and, when you encounter other example
programs, try to write variations. Study the details, exceptions, and op-
tions in these chapters, as the need arises. References to related topics in
other chapters, manuals, and online help pages that provide additional
information are included where relevant.
2 Maple Language
Elements
In This Chapter
• Basic elements of the Maple language: the character set and tokens
a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
23
24 • Chapter 2: Maple Language Elements
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
There are also 32 special characters, which are listed in Table 2.1. The
use of special characters is discussed in 2.3 Using Special Characters.
2.2 Tokens
The Maple language combines characters into tokens. The set of tokens
consists of reserved words (also called keywords ), programming-language
operators, names, strings, and natural integers.
Reserved Words
The Maple keywords are reserved words that have special meanings.
Thus, you cannot change them or use them as variables in procedures.
The keywords are listed in Table 2.2. You can find information about a
specific keyword in the subsequent chapters of this guide or in the online
help pages.1
1
For general information about reserved words in Maple, refer to ?keywords.
2.2 Tokens • 25
Programming-Language Operators
There are three types of Maple language operators: nullary, unary, and
binary.2
In Maple, there are three nullary operators (operators that take no
arguments and return values from the environment of the Maple session).
They are constructed from the Maple ditto operator. The percent sign %
is the ditto operator. It is a special Maple name used to refer to previ-
ously computed non-NULL expressions. Specifically, the following nullary
operators are defined as:
% last expression
%% second-last expression
%%% third-last expression
2
For more information about the order of precedence of programming-language op-
erators, see Table 3.4 on page 89 or refer to ?precedence.
26 • Chapter 2: Maple Language Elements
Note: The nullary operators do not reference the results of the lines
located above the execution groups in which they are used. They refer-
ence the results of the most recently performed computations in the
Maple session, regardless of the execution group or worksheet that con-
tains them. Also, since the ditto operators do not recall the results of past
computations, but re-evaluate the results of these computations, the use
of local variables to save and recall computed expressions is preferred in
procedures. For more information about local variables, see Variables on
page 201.3
The Maple binary and unary operators, and their meanings, are listed
in Table 2.3 and Table 2.4, respectively. For additional information about
these operators, see page 70.
Names
A name in Maple is a sequence of one or more characters that uniquely
identifies a command, file, variable, or other entity. There are two distinct
types of names: indexed names and symbols, which are non-indexed
3
For more information about the ditto operators, refer to ?ditto.
2.2 Tokens • 27
names. For more information about indexed names, see page 34.
The simplest instance of a name consists of a sequence of letters,
digits, and underscores. If you require a name that includes blank spaces,
use left single quotes (for more information, see page 28).
> My_Name_1;
My _Name_1
You can confirm that the previous statement is a valid name (and
symbol) by using the whattype command.
> whattype(%);
symbol
For example, in the first statement below, y is a name that does not
have a value. In the second statement, the variable x has the value 3.
> 2*y - 1;
2y − 1
> x := 3; x^2 + 1;
x := 3
10
Names that begin with an underscore are reserved by Maple for inter-
nal use only, and names of the form ñame are permitted for spreadsheet
references (refer to cell references in ?spreadsheet,references).
In general, names can also be formed by using left single quotes or
concatenation. Other categories of names in Maple include indexed names,
initially-known names, environment variables, constants, and protected
names. These are discussed in the following sections.
Forming a Name By Using Left Single Quotes You can form a name in
Maple by enclosing any sequence of characters in left single quotes (also
called back quotes). To form a name that includes blank spaces, use left
single quotes.
> ‘This is a name!‘;
This is a name!
> whattype(%);
2.2 Tokens • 29
symbol
The cat Command You can construct a name (or string) by using the
cat command
cat( sequence )
ab
ab
“ab”
a2
4
You can also use the cat command to form strings. For more information, see
page 41 or refer to ?cat.
30 • Chapter 2: Maple Language Elements
“a2”
> a;
> globalassign();
> a;
name || name
name || naturalInteger
name || string
name || ( expression )
5
For more information about procedure syntax, see chapter 6.
6
For more information about the assignment statement, see page 111.
7
For more information about local and global variables, see Variables on page 201.
2.2 Tokens • 31
i := 5
> i || 7;
i7
> p || "in";
pin
> a || (2*i);
a10
> a || i || b;
a5b
p9
32 • Chapter 2: Maple Language Elements
p||(2 m + 1)
Differences Between cat and || Although you can use both cat and
|| to concatenate, there are subtle differences in the way each performs.
The concatenation operator does not evaluate its first argument, whereas
cat does.8
> a := 2;
a := 2
> a || 4;
a4
8
In this example, the result from cat(a,4) is the name 24 not the integer 24.
2.2 Tokens • 33
24
Also, the result of the statement that uses the concatenation operator
is evaluated; this is not the case for the cat command.
> a4 := 5;
a4 := 5
> a || 4;
a4
a‘b
a\b
34 • Chapter 2: Maple Language Elements
name [ sequence ]
Since an indexed name is itself a valid name, you can add a succession
of subscripts.
> A[1,2];
A1, 2
> A[i,3*j-1];
Ai, 3 j−1
fCu := 1.512
a1 2
a1 := 3
9
2.2 Tokens • 35
Note: The use of an indexed name such as A[1,2] does not automati-
cally imply that A is an array, as in some languages. The statement
> a := A[1,2] + A[2,1] - A[1,1]*A[2,2];
Initially Known Names Maple ships with a collection of names that are
initially known to the Maple system. These are names of global or envi-
ronment variables and names of constants related to functions. Table 2.5
lists some of the initially known Maple names.10
9
For more information about arrays, Arrays, and tables, see chapter 4 or refer to
?array, Array, and ?table.
10
For general information about initially known names, refer to ?ininames.
11
For more information about assigned names, see pages 111–114 or refer to ?anames.
36 • Chapter 2: Maple Language Elements
> anames(‘environment‘);
10
> evalf(2/13);
0.1538461538
> envtest();
0.154
> Digits;
10
> evalf(2/13);
12
For more information about environment variables, refer to ?envvar. For more
information about procedures, see chapter 6 or refer to ?procedures.
13
The evalf command is used to evaluate its argument to a floating-point (decimal)
number. For more information, refer to ?evalf.
14
For more information on variable scoping, see Variables on page 201 or refer to
chapter 1 of the Maple Advanced Programming Guide.
2.2 Tokens • 37
0.1538461538
Constants You can display a sequence of all the currently active sym-
bolic constants in Maple by using the global variable constants.
> constants;
15
For general information about constants in Maple, refer to ?constants.
16
You can usually undo assignments made to Maple system names by entering a
restart command, or by ending the session. However, in general, it is dangerous to
reassign Maple system names; using the unprotect command to modify Maple system
names is not recommended.
38 • Chapter 2: Maple Language Elements
true
mysqr := x → x2
false
Strings
A string is a sequence of characters that evaluates to itself. To create a
string, enclose any sequence of characters in double quotes.
> "This is a string";
“This is a string”
17
You can perform type checking for many types of objects in Maple. For more
information, see 2.4 Types and Operands or refer to ?type.
18
For more information on the select function, see page 156.
2.2 Tokens • 39
34
All characters between, but excluding, the double quotes are counted.
Each blank space is counted as one character.
The Empty String The empty string (or null string) is represented by
two double quotation marks with no enclosed characters (not even a blank
space).
> "";
“”
> length(%);
> whattype(%%);
string
40 • Chapter 2: Maple Language Elements
The null string is not the same as the global variable NULL, which is
an empty expression sequence. The output for the null string consists of
zero printed characters.
S := “abcdef”
“e”
“cdef”
“def”
19
It is more efficient to use the selection operation than the substring command to
access a substring of a string. Therefore, whenever possible, use a selection operation
instead of the substring command for accessing substrings from procedures. For more
information about selection, see page 114.
2.2 Tokens • 41
S := “This is a string”
> S[6];
“i”
> S[6..9];
“is a”
> S[-6..-1];
“string”
The cat Command You can construct a string by using the cat com-
mand, where sequence contains any number of expressions, separated by
commas.
cat( sequence )
“ab”
“a2”
20
For more information on the differences between cat and ||, see pages 29–32 or
refer to ?cat.
42 • Chapter 2: Maple Language Elements
> i := 5;
i := 5
string || name
string || naturalInteger
string || string
string || ( expression )
“The value of i is 5”
“p9”
“p”||(2 m + 1)
2.2 Tokens • 43
“a“b 00
“a\b”
44 • Chapter 2: Maple Language Elements
“while”
Parsing Strings The parse command accepts any Maple string and
parses the string as if it had been entered or read from a file.
The string must consist of exactly one Maple expression. The expres-
sion is parsed, and returned unevaluated.
> parse("a+b");
a+b
> parse("a+b;");
a+b
sin(π)
21
For more information about the parse command, see page 268 or refer to ?parse.
46 • Chapter 2: Maple Language Elements
“a”
“a+b-c*d/e”
Natural Integers
A natural integer is a sequence of one or more decimal digits.23
> 00003141592653589793238462643;
3141592653589793238462643
22
Maple has the facility to convert a variety of objects. For more information about
expressions, see 3.2 Expressions and 3.3 Using Expressions. For more information
about conversions in Maple, refer to ?convert.
23
For more information about integers in Maple, see page 62 or refer to ?integer.
2.3 Using Special Characters • 47
ax + xy
a := 1 + x + x2
Since white space and new line characters are functionally identical,
you can continue statements from line to line, as described in chapter 1.
> a:= 1 + x +
> x^2;
a := 1 + x + x2
To continue numbers and strings over multiple lines, use the back-
slash (\) as a line continuation character. The behavior of line continua-
tion is as follows.
If the special character backslash \ immediately precedes a new
line character, the Maple parser ignores both the backslash and the
new line. If a backslash occurs in the middle of a line, Maple usually
ignores it. 25
24
For information about comments in Maple procedures, see 6.5 Documenting
Your Procedures.
25
For more information about the backslash and exceptions to this rule, refer to
?backslash.
48 • Chapter 2: Maple Language Elements
You can use this rule to break up a long sequence of digits into groups
of smaller sequences, to enhance readability.
> "The input should be either a list of \
> 6512090082402\43104215933593992;
G := 0.577215664901532860606512090082402431\
04215933593992
Punctuation Marks
The punctuation marks that act as token separators are listed in Table 2.6.
; and : Use the semicolon and the colon to separate statements. The
distinction between these marks is that, during an interactive session,
a colon prevents the result of the statement from printing.
> f:=x->x^2;
f := x → x2
2.3 Using Special Characters • 49
’sin’(π)
> %;
sin(π)
> %;
() The left and right parentheses group terms in an expression and group
parameters in a function call.
> (a+b)*c; cos(Pi);
(a + b) c
−1
> proc( x, y, z )
> x+y+z;
> end proc:
50 • Chapter 2: Maple Language Elements
[] Use the left and right square brackets to form indexed (subscripted)
names and to select components from aggregate objects such as ar-
rays, tables, and lists. For more information on data structures, see
chapter 4.
> a[1]; L:=[2,3,5,7]; L[3];
a1
L := [2, 3, 5, 7]
5
[] and {} Use the left and right square brackets to form lists, and the
left and right braces to form sets. For more information on sets and
lists, see chapter 4.
> L:=[2,3,5,2]; S:={2,3,5,2};
L := [2, 3, 5, 2]
S := {2, 3, 5}
<> and | The left and right angle brackets in conjunction with the ver-
tical bar are used to construct Matrices and Vectors. For more infor-
mation, refer to ?Matrix and ?MVshortcut.
> <<1,2,3> | <4,5,6>>;
1 4
2 5
3 6
0, 0, 0
2.4 Types and Operands • 51
Escape Characters
An escape character indicates that the following character must be han-
dled in a special manner. The escape characters in Maple are ?, !, #, and
\.
# The pound sign character indicates that the characters that follow it on
the line are a comment. For more information, see 6.5 Documenting
Your Procedures or refer to ?comment.
op( i, expression );
nops( expression );
Integers
The type of an integer is integer. The type command also understands
the subtypes of integers listed in Table 2.7.
An integer has only one operand, itself.
> x := 23;
x := 23
true
> op(x);
23
26
For more information about data types and operands in Maple, see chapter 3 or
refer to ?type and ?op.
2.4 Types and Operands • 53
Integer
Strings
The type of a string is string. A string also has only one operand, itself.
> s := "Is this a string?";
true
> nops(s);
> op(s);
Names
The type of a name is name. However, the type command also understands
the type names symbol and indexed. The type name is defined as symbol
or indexed.
> x := ‘my name‘;
x := my name
true
true
54 • Chapter 2: Maple Language Elements
x := A12, 3
true
true
> nops(x);
> op(x);
2, 3
> op(0,x);
A1
> y:=%;
y := A1
true
1, A, 1
2.5 Troubleshooting • 55
Concatenations
The type of an unevaluated concatenation is “||”. This type has two
operands, the left-hand side expression and the right-hand side expression.
> c := p || (2*m + 1);
c := p||(2 m + 1)
true
||
> nops(c);
> op(c);
p, 2 m + 1
2.5 Troubleshooting
This section provides you with 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.
27
For more information about protected names, see page 37 or refer to ?protect.
56 • Chapter 2: Maple Language Elements
The error message indicates the character number (counted from the
left double quote) where error was detected. In this case, the 6th character
(the second minus sign) caused the error.
true
28
For more information about strings, see page 38 or refer to ?string.
29
For more information about parsing, see page 44 or refer to ?parse.
2.5 Troubleshooting • 57
“2 + 3”
> whattype(%);
string
2 + 3
> whattype(%);
symbol
f := x + y
> f := x + y;
f := 5
30
For more information about using quotes, see Punctuation Marks on page 48 or
refer to ?quotes.
58 • Chapter 2: Maple Language Elements
2.6 Exercises
1. Using the %, %%, and %%% operators, find the:
a) Sum of 5434 and 6342.
b) Product of 92 and 310.
c) Quotient of the result from a) divided by the result from b).
d) Quotient of the result from b) divided by the result from a).
3. Concatenate the three strings "int", "(x^2,", and "x)". Parse the
resulting string. Evaluate the parsed string.
4. The Fibonacci numbers are a sequence of numbers. The first two num-
bers in the sequence are zero (0) and one (1). For n greater than two,
the nth number in the sequence is the sum of the two preceding num-
bers. Assign values to indexed names representing the first, second,
and general Fibonacci numbers.
6. Assign the expressions x^2 and x*x to the names a and b. Find
the three operands of a and b. Compare the results with those re-
turned by using the dismantle function, that is, dismantle(a) and
dismantle(b). The dismantle function displays the internal data
structure used.
2.7 Conclusion
This chapter introduced the Maple language elements. In particular, to-
kens are the smallest meaningful elements in Maple. Tokens are used to
form Maple expressions and statements. The next chapter shows how to
use the information presented in this chapter to build expressions, and
discusses how to form Maple statements.
3 Maple Expressions and
Statements
In This Chapter
• Syntax and semantics of the Maple language
Syntax
Syntax defines valid forms of input, for example, expressions, statements,
and procedures. It dictates, for example:
59
60 • Chapter 3: Maple Expressions and Statements
However, you must place at least one digit between the decimal point
and the exponent suffix.
> 2.e-3;
Semantics
The semantics of a language specifies how expressions, statements, and
programs execute—that is, the actions Maple performs with them. It
controls:
1 1x
x z,
2 2 z
3.2 Expressions
Expressions are the fundamental entities in the Maple language and the
most important type of Maple statement. The types of expressions are
the following:
• constants
• operator-based expressions
• data structures
• function calls
Procedures and modules1 are also valid expressions because you can use
them wherever an expression is accepted. This is an important feature of
the Maple language. Procedures are described separately in chapter 6.
Expressions are now presented in detail, beginning with the numeric
constants. The presentation shows how to input the expression, gives ex-
amples of how and where to use the expression, and illustrates the action
of the type, nops, op, and subsop commands on the expression.
Constants
The Maple language contains both symbolic and numeric constants.
1
For information on modules, refer to chapter 2 of the Maple Advanced Programming
Guide or ?module.
62 • Chapter 3: Maple Expressions and Statements
• Of type complex(extended_numeric)
true
true
true
2
The integer zero (0) does not have a sign. However, the floating-point zeros, +0.0
and -0.0, are signed. For more information, see page 65.
3
The evalb command evaluates a Boolean expression. For more information, see
page 86 or refer to ?evalb.
3.2 Expressions • 63
true
true
true
268435448
true
integer/natural
4
For more information about integers in Maple, refer to ?integer.
64 • Chapter 3: Maple Expressions and Statements
> -30/12;
−5
2
> whattype(%);
integer
2
x :=
3
true
true
2, 3
2, 3
natural.natural
natural.
.natural
natural exponent
natural.natural exponent
.natural exponent
Note that
> 1.e2;
−0.8 6= 0.02
x := 231.3
> SFloatMantissa(x);
2313
> SFloatExponent(x);
−1
You can also use the Float command to construct floating-point num-
bers.
Float( m, e );
0.0012
5
For information about the full suite of numeric types and subtypes, refer to
?numeric_type.
6
For more information, see page 62 or refer to ?maxdigits.
3.2 Expressions • 67
0.001200000000
0.3783783784
In general, you can use the evalf command to force the evaluation
of a non-floating-point expression to a floating-point expression, where
possible.
> x := ln(2);
x := ln(2)
> evalf(x);
0.6931471806
7
For more information, refer to ?Digits.
8
For more information about evaluation using floating-point arithmetic, refer to
?evalf.
68 • Chapter 3: Maple Expressions and Statements
> evalf[15](x);
0.693147180559945
I, I, I
2 + 3I
2 + 3I
z := 2 + 3 I
2, 3
9
In an expression such as x + y*I, where x and y are symbols, Maple does not
assume that x is the real part and y is the imaginary part.
3.2 Expressions • 69
x := 1 + I
y := 2.0 − 1. I
> x + y;
3.0 + 0. I
1
a−I
> evalc(%);
70 • Chapter 3: Maple Expressions and Statements
a I
+ 2
a2 +1 a +1
To use another letter, say j, to represent the imaginary unit, use the
interface command as follows.
> interface(imaginaryunit = j);
{z = j}, {z = −j}
{z = I}, {z = −I}
Operators
A Maple operator is a symbol indicating that a mathematical operation
is to be performed. This section discusses the Maple operators, and how
to create expressions involving them.
• The operands of the power xa are the base x and the exponent a.
> whattype(x-y);
> whattype(x^y);
Arithmetic Maple always computes the result to the five arithmetic op-
erations x + y, −y, x × y, x/y, and xn , if n is an integer, and x and y
are numbers. For example, you cannot prevent Maple from simplifying 2
+ 3 to 5 in output.10 If the operands are floating-point numbers, Maple
performs the arithmetic computation in the floating-point environment.
> 2 + 3, 6/4, 1.2/7, (2 + I)/(2 - 2*I);
3 1 3
5, , 0.1714285714, + I
2 4 4
10
For information on displaying output that appears unsimplified, refer to the exam-
ples in section 1.3 of the Maple Advanced Programming Guide.
72 • Chapter 3: Maple Expressions and Statements
3.737192819, 0. + 4.810477381 I
nb = nq+r/d → nq × nr/d .
For example,
> 2^(3/2), (-2)^(7/3);
√
2 2, 4 (−2)(1/3)
0, 2 x, x, x2 , 1, x, 1, x
undefined
> infinity/infinity;
undefined
> 0/0;
ax + bx → (a + b)x
xa × xb → xa+b
a(x + y) → ax + ay
The first two simplifications mean that Maple adds like terms in
polynomials automatically. The third simplification means that Maple
distributes numerical constants (integers, fractions, and floating-point
numbers) over sums, but does not do the same for non-numerical con-
stants.
> 2*x + 3*x, x*y*x^2, 2*(x + y), z*(x + y);
5 x, x3 y, 2 x + 2 y, z (x + y)
11
For more information, refer to ?simplify.
12
For more information, refer to ?expand.
74 • Chapter 3: Maple Expressions and Statements
√ √ √
Simplifying 2 3 to 6 in the previous expression would create a
third unique square root. Calculating with roots is, in general, difficult
and expensive. Therefore, new roots are avoided.
Use the combine command to combine roots.13
A . B;
42
> M:=<<1,0,2>|<0,1,2>|<0,0,2>>;
13
For more information, refer to ?combine.
14
For more information about Matrix, Vector, and the LinearAlgebra package in
Maple, refer to ?LAOverview. For more information about the non-commutative multi-
plication operator, refer to ?dot. For more information about the VectorCalculus dot
product operator, refer to ?VectorCalculus[DotProduct].
3.2 Expressions • 75
1 0 0
M := 0 1 0
2 2 2
> V:=<10,0,0>;
10
V := 0
0
> M . V;
10
0
20
> lambda . M . V;
10
λ. 0
20
Any dot with spaces before and/or after it that is not part of a
number is interpreted as the non-commutative multiplication
operator.
2.3, 6, 6
15
For more information about floating-point numbers, see page 65 or refer to ?Float.
For more information about the range operator, see page 77 or refer to ?range.
76 • Chapter 3: Maple Expressions and Statements
> 2. 3;
f(g(x))
> (sin@cos)(Pi/2);
(f (2) )(x)
> expand(%);
f(f(x))
> (D@@n)(f);
(D(n) )(f )
1
sin(x)2 , (sin(2) )(x), , arcsin(x)
sin(x)
0, 0
The Ditto Operators %, %%, and %%% The sequence of expressions as-
signed to the three ditto nullary operators is the last three non-NULL
results generated in the Maple session independent of where they are lo-
cated in the session.16,17
expression1 .. expression2
1..3
1, 2, 3
r := 3..7
16
For more information about the ditto operator and nullary operators, see page 25
or refer to ?ditto.
17
The ditto operators are technically not operators.
18
For more information about the seq command, see page 183 or refer to ?seq.
78 • Chapter 3: Maple Expressions and Statements
true
A range has two operands, the left-hand limit and the right-hand
limit. You can access these limits by using the op command or the lhs
and rhs commands.
> op(1,r), op(2,r);
3, 7
3, 7
You can also use the range construct in conjunction with the op
command to extract a sequence of operands from an expression.
> a := [ u, v, w, x, y, z ];
a := [u, v, w, x, y, z]
> op(2..5,a);
v, w, x, y
n!
1, 120
> 2.5!;
3.323350970
> (-2)!;
720
e mod m ;
19
For information on the Maple doublefactorial command, refer to
?doublefactorial.
20
Use left single quotes around mod when it is not used as an operator because it is
a reserved word. For more information about reserved words, see page 24 or refer to
?keyword.
80 • Chapter 3: Maple Expressions and Statements
mod := modp
> 9 mod 5;
mod := mods
> 9 mod 5;
−1
Alternatively, you can invoke the modp and mods commands directly.
> modp(9,5), mods(9,5);
4, −1
The mod operator accepts the inert operator &^ for powering. That
is, i&^j mod m calculates ij mod m. Instead of separately computing the
integer ij , which may be too large to compute, and then reducing modulo
m, Maple computes the power by using binary powering with remainders.
> 2^(2^100) mod 5;
21
For more information on the floor function, refer to ?floor.
3.2 Expressions • 81
4 x2 + 3 x + 3
4 (x + 3) (x + 4)
The mod command can also compute over a Galois field GF (pk ), that
is, the finite field with pk elements.23
The Neutral Operators &name Maple has a neutral operator (or user-
defined) facility. You can form a neutral operator symbol by using the
ampersand character “&” followed by one or more characters. There are
two varieties of &-names: alphanumeric and non-alphanumeric.
alphanumeric The & character followed by any Maple name not requir-
ing left single quotes, for example, &wedge.
22
Do not confuse the commands factor and Factor or int and Int. The former
evaluate immediately; the latter are inert commands which Maple does not evaluate
until you make the call to mod. For more information on inert functions, refer to ?inert.
23
For more information and a list of commands that mod accepts, refer to ?mod.
82 • Chapter 3: Maple Expressions and Statements
& | ( ) [ ] { } ; : ’ ‘ # \ %
(a &~ b) &~ c
> op(%);
a &~ b, c
> op(0,%%);
&~
The Relational Operators <, >, <=, >=, and <> You can form new types
of expressions from ordinary algebraic expressions by using the relational
operators <, >, <=, >=, and <>. The semantics of these operators depend
on whether they occur in an algebraic context or in a Boolean context.
In an algebraic context, the relational operators are simply placehold-
ers for forming equations or inequalities. Maple fully supports addition of
equations or inequalities, and multiplication of an equation or inequality
3.2 Expressions • 83
e := x + 3 y = z
> 2*e;
2x + 6y = 2z
> whattype(e);
An equation has two operands, the left-hand side and the right-hand
side. In addition to using the op command to select the operands of an
equation, you can use the lhs and rhs commands.
> lhs(e);
x + 3y
The type command also accepts the types <>, <, and <=. Maple auto-
matically converts inequalities involving > or >= to < and <=, respectively.
All the relational types have two operands.
> e := a > b;
e := b < a
84 • Chapter 3: Maple Expressions and Statements
> op(e);
b, a
“less”
“first half”
In the case of the relations = and <>, the operands can be arbitrary
expressions (algebraic or non-algebraic). This equality test for expressions
tests object equality of the Maple representations of the expressions, which
is not the same as mathematical equivalence.
To evaluate a relation in a Boolean context, use the evalb command.
> evalb( x + y = y + x );
true
false
For the latter example, apply the expand command to show that the
equation is true.
24
For more information about if statements and while clauses, see chapter 5, or
refer to ?if and ?while.
3.2 Expressions • 85
true
You can also use the is command, instead of evalb, to evaluate re-
lations in a Boolean context.
> is( x^2 - y^2 = (x - y)*(x + y) );
true
true
The Logical Operators and, or, xor, implies, and not Generally, you
can form an expression by using the logical operators and, or, xor,
implies, and not. The first four are binary operators and the last is
a unary (prefix) operator. An expression containing one or more logical
operators is automatically evaluated in a Boolean context.
> 2>3 or not 5>1;
false
false
The precedence of the logical operators and, or, and not is analogous
to that of multiplication, addition, and exponentiation, respectively. Here
no parentheses are necessary.25
> (a and b) or ((not c) and d);
The xor operator is of lower precedence than or. The implies oper-
ator has the lowest precedence of the logical operators.
25
For more information about precedence of Maple operators, see Table 3.4 on page 89
or refer to ?precedence.
86 • Chapter 3: Maple Expressions and Statements
The type names for the logical operators and, or, xor, implies, and
not are and, or, xor, implies, and not, respectively. The first four have
two operands, the last has one operand.
> b := x and y or z;
b := x and y or z
> whattype(b);
or
> op(b);
x and y, z
a and b and c
true
> is(a1,positive);
false
The Set Operators union, minus, intersect, and subset The union,
intersect, minus, and subset commands are used for the set union,
intersection, difference, and subset operations. The union and intersect
commands are infix n-ary operators. The minus and subset commands
are binary infix operators.
> A:={1,2,3}; B:={2,3,4};
A := {1, 2, 3}
B := {2, 3, 4}
> A union B;
{1, 2, 3, 4}
> A intersect B;
{2, 3}
> A minus B;
{1}
> A subset B;
false
Associated with each set operator, there is a type of the same name.
For more information, refer to ?type.
Data Structures
The Maple system includes many data structures. The more common
ones are mentioned here in the context of expressions. For a thorough
discussion on sequences, sets, lists, tables, arrays, Arrays, and others, see
chapter 4.
26
For more information about precedence in Maple, refer to ?precedence.
90 • Chapter 3: Maple Expressions and Statements
s := 5, 6, 7
> whattype(%);
exprseq
5, 6, 7
myset := {5, 6, 7}
> whattype(%);
set
mylist := [5, 6, 7]
> whattype(%);
list
3.2 Expressions • 91
Tables, arrays, and Arrays The table data structure in Maple is a spe-
cial object for representing data in tables. You can create a table either
explicitly by using the table command or implicitly by assignment to an
indexed name. The following statements are equivalent.
> T := table([(Na,11) = 23]);
TNa, 11 := 23
They both create a table object with one component. The purpose of
a table is to allow fast access to data.
> T[Na,11];
23
For more information about tables, arrays, and Arrays, see chapter 4.
27
For information on the differences between arrays and Arrays, see 4.4 arrays and
Arrays.
92 • Chapter 3: Maple Expressions and Statements
Functions
A function expression represents a function call, or in other words, an
application of a function or procedure to arguments. Such an expression
is said to be of type function. A typical example of an expression of type
function is the expression f(x), which represents the application of the
expression f to the argument sequence x. The entire expression f(x) is of
type function (that is, a function call or function application), while
the expression f is typically not itself of type function (but it is often
of type procedure).
A function call in Maple takes the following form.
f( sequence )
sin(x)
> min(2,3,1);
> g();
g()
> a[1](x);
a1 (x)
28
In the example below, the arrow (->) notation is used. For more information about
creating procedures using the arrow notation, see page 207.
3.2 Expressions • 93
> x := 1:
> f(x);
f(1)
> s := 2,3;
s := 2, 3
> f(s,x);
f(2, 3, 1)
> f := g;
f := g
> f(s,x);
g(2, 3, 1)
g := (a, b, c) → a + b + c
> f(s,x);
m := min(1, y, z)
> op(0,m);
94 • Chapter 3: Maple Expressions and Statements
min
> op(m);
1, y, z
> type(m,function);
true
> f := n!;
f := n!
true
factorial
> op(f);
• name
• procedure definition
• integer
• float
• function
t2 (1 − t2 )
> h(t^2);
t2 (t2 − 1)
Recall that the @ sign denotes functional composition, that is, f@g
denotes f ◦ g. These rules together with the previous rule mean the fol-
lowing.
> (f@g + f^2*g +1)(x);
(f (3) )(x)
> expand(%);
f(f(f(x)))
> f(g)(0);
f(g)(0)
> D(cos)(0);
The commands have been introduced previously, but they are now
formally presented in Table 3.5.
Consider the following formula.
29
For more information about how to define a function by using functional operators,
see page 231 or refer to ?unapply.
30
An expression can have multiple types.
3.3 Using Expressions • 97
true
false
> nops(f);
sin(x)
sin(x) + 3
op(i..j, f)
op([i, j, k], f)
is an abbreviation of
is an abbreviation of
op(f)
31
For a complete description of op(0,f), refer to ?op.
3.3 Using Expressions • 99
sin
3 * sin
x
sin ^ 2
x
cos 2
The first “node” of the expression tree labeled “+” is a sum. This
indicates the expression’s type (from op(f, 0)).
This expression has three branches corresponding to the three terms
in the sum (from op(1..3, f))—that is, sin(x), 2 cos(x)2 sin(x), and 3.
The nodes of each branch indicate the type of each term in the sum.
The leaves of the tree are the names and integers in this example.32,33
32
The idea of an expression tree closely models how Maple interprets expressions.
More precisely, Maple uses DAGs (directed acyclic graphs) to represent arbitrary ex-
pressions. While similar to this idea of an expression tree, they have the additional
property that all common subexpressions are identified by Maple only once. As a re-
sult, since all like subexpressions are shared, expressions are nonmutable, and changing
an expression involves a copy operation. For more information about DAGs, refer to
chapter 6 of the Maple Advanced Programming Guide.
33
For more information about the display of Maple data structures, refer to
?dismantle.
100 • Chapter 3: Maple Expressions and Statements
17
4
Maple first reads and parses the input. As the input is parsed, Maple
builds an expression tree to represent the value
Maple simplifies the expression tree, and then evaluates the result.
The evaluation process substitutes values for variables and invokes any
functions or procedures. In this case, x evaluates to π/6. Hence, with these
substitutions, the expression is:
Invoking the sin and cos functions, Maple obtains a new “expression
tree”, √
1/2 + 2 × (1/2 3)2 × 1/2 + 3.
Maple simplifies this result to obtain the fraction 17/4.
x := 1
Unevaluated Expressions
In general, Maple evaluates all expressions immediately. In some situa-
tions, it is necessary to delay evaluation. An expression enclosed in right
single quotes is called an unevaluated expression.
3.3 Using Expressions • 101
’expression’
a := 1
x := 1 + b
a := 1
x := a + b
x := 5
x−2
102 • Chapter 3: Maple Expressions and Statements
uneval
To reset the value of a name, assign the unevaluated name (its initial
value) to the name.34
> x := ’x’;
x := x
’f’(sequence)
’sin’(π)
> %;
sin(π)
> %;
You will find this facility useful when writing procedures that imple-
ment simplification rules—refer to the section 1.4 of the Maple Advanced
Programming Guide.35
34
For more information about unassigning names, see page 111.
35
For more information and examples regarding unevaluated expressions in Maple,
refer to ?uneval.
3.3 Using Expressions • 103
Substituting Subexpressions
To combine the acts of substitution and evaluation, use the two-parameter
version of the eval command.
The eval command has the following syntax, where s is an equation,
list, or set of equations.
eval( expr, s );
expr := x3 + 3 x + 1
y3 + 3 y + 1
15
subs( s, expr );
The subs command traverses the expression expr and compares each
operand in expr with the left-hand side(s) of the equation(s) s. If an
operand is equal to a left-hand side of an equation in s, subs replaces
the operand with the right-hand side of the equation. If s is a list or set
of equations, Maple makes the substitutions indicated by the equations
simultaneously.
> f := x*y^2;
104 • Chapter 3: Maple Expressions and Statements
f := x y 2
y z2
y w2
cos(0)
abc
The substitution does not result in d*c because the operands of the
product a*b*c are a, b, c. That is, the products a*b, b*c, and a*c do not
appear explicitly as operands in the expression a*b*c. The easiest way
to make such substitutions is to solve the equation for one unknown and
substitute for that unknown.
> eval( a*b*c, a=d/b );
dc
You cannot always do this, and you may find that it does not always
produce the results you expect. The algsubs routine provides a more
powerful substitution facility.
> algsubs( a*b=d, a*b*c );
dc
%natural
36
The percent sign performs two roles in the Maple program: a label indicator and
the ditto operator, which represents the result of the last, second last, and third last
result. For more information on the ditto operator, see page 25.
106 • Chapter 3: Maple Expressions and Statements
1
{y = %1, x = − %1 (−4 %13 − 3 − %12 + 6 %1 + 2 %14 )}
3
%1 := RootOf(3 _Z 2 + 3 − 3 _Z 4 + 2 _Z 6 + 4 _Z 3 )
After Maple executes this statement, the label %1 is an assigned name
with a value of the preceding RootOf expression.
> %1;
RootOf(3 _Z 2 + 3 − 3 _Z 4 + 2 _Z 6 + 4 _Z 3 )
Two facilities are available for use with labels. The command
interface( labelwidth=n );
specifies that Maple should not display expressions less than (approx-
imately) n characters wide as labels. The default value is 20 characters.
The command
interface( labeling=truefalse );
enables the use of %1, %2, ... labels for output subexpressions. You can
turn off this facility by using the following command.
> interface(labeling=false);
Structured Types
A simple type check may not provide sufficient information. For example,
the command
> type( x^2, ‘^‘ );
true
true
3.3 Using Expressions • 107
false
false
true
true
true
true
true
108 • Chapter 3: Maple Expressions and Statements
true
e2
false
true
The next example illustrates the need to use right single quotes (’) to
delay evaluation when including Maple commands in type expressions.37
> type( int(f(x), x), int(anything, anything) );
1
anything 2
2
This is not a valid type. If you enclose the int command in right
single quotes, the type checking works as intended.
37
For more information on delayed evaluation, see page 100.
3.3 Using Expressions • 109
true
true
true
true
true
In addition to testing the type of arguments, you can test the number
of arguments. The type anyfunc(t1, ..., tn) matches any function
with n arguments of the listed types in the correct order.
> type( f(1,x), anyfunc(integer, name) );
true
false
false
110 • Chapter 3: Maple Expressions and Statements
Another useful variation is to use the And, Or, and Not type construc-
tors to create Boolean combinations of types. Note that these are different
from the logical operators and, or, and not discussed on page 85.38
> type(Pi, ’And( constant, numeric)’);
false
true
3.4 Statements
The statement is an important component in the Maple language. There
are many types of statements in Maple.
• assignment statement
• selection statements
• repetition statements
• use statement
• quit statement
• expressions
38
For more information on structured types, refer to ?type,structured. For more
information on how to define your own types, refer to ?type,definition.
3.4 Statements • 111
name := expr;
(name1, ..., namen) := (expr1, ..., exprn);
a := 0
a, b := 1, 2
> a; b;
39
You can also use the assign command to make an assignment. For more informa-
tion, refer to ?assign.
112 • Chapter 3: Maple Expressions and Statements
eq1 := y = 3 x − 4
1 4
y+
3 3
Testing for Assignment You can test whether a name has an assigned
value by using the assigned command.
assigned( name );
false
anames();
> a := 0: b:=1:
> anames();
b, a
a := 4
> a;
> a := ’a’;
a := a
> a;
i := 1
> unassign(i);
> unassign(’i’);
evaln( name );
a := 4
> a := evaln(a);
a := a
> a;
Selection Statements
Selection is an important operation in programming. To perform selection,
use the conditional or if statement. It has the following syntax.
“a is larger”
3.4 Statements • 115
Repetition Statements
Looping constructs, such as the for loop and the while loop, are used to
repeat similar actions a number of times.
total := 0
total := 1
total := 3
total := 6
total := 10
Example 2 The same calculation is simpler if you use the for loop.
> total := 0;
total := 0
total := 1
total := 3
total := 6
total := 10
10
Example 3 Alternatively, you can calculate the sum of the first four
natural numbers by using the while loop.
> total := 0; i := 0;
total := 0
i := 0
total := 0
i := 1
total := 1
i := 2
total := 3
i := 3
total := 6
i := 4
total := 10
i := 5
Before each cycle through the while loop, Maple checks whether i
is greater than 4. If it is not, then Maple executes the body of the loop.
When the execution of the loop finishes, the value of total is 10 and the
value of i is 5.
The while and the for loop are both special cases of a more general
repetition statement. It has the following syntax.
For more information about repetition using loops, see 5.2 Repeti-
tion.
> for i in L do
> if i=8 then
> break
> end if;
> print(i);
> end do;
7
6
a := “Φd8p!<vΥ”
“/9BkOHAhPHaEzw==”
quit;
3.5 Troubleshooting
This section provides you with a list of common mistakes, examples, and
hints that will help you understand and avoid common errors. Use this
120 • Chapter 3: Maple Expressions and Statements
section to study the errors that you may encounter when entering the
examples from this chapter in a Maple session.
Syntax Errors
If input is not syntactically correct, Maple reports a syntax error.
> 2+-3;
40
For more information about reserved words, see page 24 or refer to ?keyword.
3.6 Exercises • 121
To avoid this error, use left single quotes when you must use reserved
words as a name, for example, in function calls.
> ‘mod‘(4,2);
3.6 Exercises
1. Find the numerator and denominator of the irreducible form of
4057114691 divided by 4404825097799.
4. Calculate the negative complex root of -1369, and then sum 3 and
the root. Find the inverse of this complex sum. Find the inverse of
(a*b)/c+((a-d)/(b*e))*I) in standard form, where a, b, c, d, and
e are real.
41
For more information about break and next, see page 179.
122 • Chapter 3: Maple Expressions and Statements
3.7 Conclusion
This chapter discussed the syntax and semantics of Maple expressions
and statements. There are many expression types in Maple, and by using
expression trees you can understand the types and the operands in an
expression. Expressions are commonly used in Maple statements. Maple
has many types of statements in its language, including assignments, con-
ditional and looping statements, and statements to read from and save to
files.
With the knowledge of how to form valid Maple statements, you can
proceed to the next chapter which discusses Maple data structures.
4 Basic Data Structures
In This Chapter
• Defining and manipulating sets, lists, tables, arrays, and Arrays
• Stacks and queues, two additional data structures that are imple-
mented using tables
4.1 Sets
A set is an unordered sequence of unique expressions enclosed in braces
({}). Recall that a sequence is a group of expressions separated by com-
mas.
{ sequence }
1
Compare the results of these examples to those in 4.2 Lists.
123
124 • Chapter 4: Basic Data Structures
{x, y}
{1, 2, a, b}
> {y[1],x,x[1],y[1]};
{y1 , x, x1 }
Manipulating a Set
There are a variety of commands that perform operations on sets.
Set Arithmetic The most commonly used built-in set arithmetic op-
erators are union, minus, and intersect. These operators perform set
union, set difference, and set intersection, respectively.
> s := {x, y, z};
s := {x, y, z}
t := {y, z, w}
> s union t;
{x, y, z, w}
> s minus t;
{x}
> s intersect t;
{y, z}
4.1 Sets • 125
Testing Set Equality You can force the evaluation of expressions that
involve relational operators by using evalb. To perform equality testing
with sets, use the evalb command in conjuction with the relational op-
erator =.
> evalb(s = t);
false
Testing Set Membership To test for set membership, use the member
command or the in operator.
> member(x, s);
true
true
false
map( f, S );
> S := {1,-2,3,-4};
S := {−4, −2, 1, 3}
126 • Chapter 4: Basic Data Structures
> map(abs,S);
{1, 2, 3, 4}
{1, 4, 9, 16}
You can also apply a function to the members of a set by using the
in command.
> for elem in S do
> elem^3;
> end do;
−64
−8
1
27
4.2 Lists
A list is an ordered sequence of expressions enclosed in square brackets
([]).
[ sequence ]
The ordering of the list is the same as the sequence ordering (specified
by the user). Also, unlike sets, duplicate entries are retained in the list.
In the case where sequence is empty, [] represents an empty list.2
> [x, y, y];
[x, y, y]
2
Compare the results of these examples to those in 4.1 Sets.
4.2 Lists • 127
[a, 1, b, 2]
> [y[1],x,x[1],y[1]];
[y1 , x, x1 , y1 ]
Maple gives nested lists whose inner lists have the same number of
elements a special name—listlist.3
> M := [[a,b], [1,2], [3, 4]];
true
false
true
3
For more information about nested lists, refer to ?listlist.
128 • Chapter 4: Basic Data Structures
By changing the braces and brackets, you can create a set of lists, list
of lists, or set of sets.
> {seq( [ seq( i^j, j=1..3) ], i=-2..2 ) };
{[−2, 4, −8], [−1, 1, −1], [0, 0, 0], [1, 1, 1], [2, 4, 8]}
Manipulating a List
There are a variety of commands that perform operations on lists.
L := [1, 2, 3]
true
false
true
> p;
> L1 := [a,b,c];
L1 := [a, b, c]
> L2 := [y,z];
L2 := [y, z]
L3 := [a, b, c, y, z]
You can also concatenate parts of lists with another list by using the
op command to select particular elements from a list.4
> L4 := [op(2, L1), op(L2)];
L4 := [b, y, z]
L1 := [grape]
[banana, grape]
[grape, orange]
You can also insert elements in a list by using the nops command.5
4
For more information about selection using the op command, see page 155.
5
The nops command determines the number of operands in an expression. For more
information about nops, refer to ?nops.
130 • Chapter 4: Basic Data Structures
L1 2 := kiwi
> L1;
6
For more information about the selection operation, see page 152 or refer to
?selection.
4.2 Lists • 131
Sorting a List To sort the elements in a list, use the sort command. It
has the following syntax where L is a list and F is an optional parameter
that specifies the sort order.
sort( L, F );
[b, e, z]
7
For more information on the seq command, see page 183 or refer to ?seq.
8
The algorithm that Maple uses for sort is a recursive implementation of merge
sort with an early detection of sorted sequences. For more information about sorting
lists, refer to ?sort.
132 • Chapter 4: Basic Data Structures
7
[ , 2.5, 10]
3
7
[10, 2.5, ]
3
map( f, L );
[1, 2, 3, 4]
[1, 4, 9, 16]
[5, 7, 9]
[5, 7, 13]
4.3 Tables
The table data structure in Maple is used for representing data in a
table—an arrangement of rows and columns. To create a table explicitly,
use the table command. The optional parameters F and L specify an
indexing function, and a list or set that specifies the initial values of the
table, respectively.
table( F, L );
T := table([1 = a, 2 = b, 3 = c])
9
The use of a set of initial values is ambiguous because there is no fixed ordering
of set elements. Hence, the ordering of the entries in the result may not correspond to
the ordering in which the entries are given.
10
You can also create a table implicitly by using an indexed name. For more infor-
mation, see page 135 or refer to ?table.
134 • Chapter 4: Basic Data Structures
T1 := table([0 = α, 1 = β])
T2 := table([y1 = x, y3 = x2 , y2 = x3 ])
table([])
tan
11
For more information about table entry selection, see 4.5 Selecting Elements
from a Data Structure or refer to ?selection.
4.3 Tables • 135
> T3[shirt,M];
T [ indexExpr ] = entryValue ;
T4 := table([(Cu, 1) = 64])
T4 Cu, 1 := 64
T5 := table([1 = 1, 2 = 2, 3 = 3, 4 = 4])
> T5;
T5
12
In Maple, an expression is normally evaluated by using full recursive evaluation—
that is, the result of the expression is the fully evaluated expression. For more infor-
mation about evaluation rules, see page 14 or refer to ?last_name_eval.
136 • Chapter 4: Basic Data Structures
table([1 = 1, 2 = 2, 3 = 3, 4 = 4])
Manipulating a Table
There are a variety of commands that perform operations on tables.
mytable 1 := apple
mytable 2 := banana
> eval(mytable);
mytable 2 := orange
> eval(mytable);
table([1 = 8])
newtable := table([])
true
13
For more information about flow control statements, see 5.1 Selection and Con-
ditional Execution.
138 • Chapter 4: Basic Data Structures
T5 3 := T5 3
> eval(T5);
table([1 = 1, 2 = 2, 4 = 4])
indices(T );
> T := table([[shirt,S]=42,[shirt,M]=16,[shirt,L]=36]);
> indices(T);
entries(T );
> entries(T);
14
The order of the keys in the returned sequence does not necessarily correspond to
the order of the keys in the table because tables in Maple are implemented by using
hash tables. However, there is a one-to-one correspondence between the order of the
indices and the order of the entries.
15
The order of the entries in the returned sequence does not necessarily correspond
to the order of the entries in the table.
4.3 Tables • 139
and corresponding op command that you can use to access them. In the
op commands shown, T is the name of the table.16
The call op(T) returns the actual table structure.
> op(T4);
table([(Cu, 1) = 64])
table
The table T4 has no indexing function and the list of entries has only
one key/value pair.
> op(1,eval(T4));
> op(2,eval(T4));
[(Cu, 1) = 64]
T6 := table([1 = w, 2 = x, 3 = y, 4 = z])
16
Tables have special evaluation rules. To access the table object, you must apply
the eval command. For more information, see page 135.
140 • Chapter 4: Basic Data Structures
> b := T6:
> b[1] := 7;
b1 := 7
> eval(T6);
table([1 = 7, 2 = x, 3 = y, 4 = z])
> eval(b);
table([1 = 7, 2 = x, 3 = y, 4 = z])
In this example, there is only one table. The name b points to the
name T6 which points to the table structure.
To create a copy of a table that is independent of the original, use the
copy command.
copy( T );
> c := copy(T6);
c := table([1 = 7, 2 = x, 3 = y, 4 = z])
table([1 = 7, 2 = x, 3 = y, 4 = z])
> eval(c);
2
table([1 = 1, 2 = 2 x, 3 = 3 x2 − 1, 4 = − ])
x3
To modify the values in-place, that is, change the values in the original
table, use the following method.
> for entry in op(2,eval(T6)) do
> T6[lhs(entry)] := 2*rhs(entry)
> end do;
T6 1 := 14
T6 2 := 2 x
T6 3 := 2 y
T6 4 := 2 z
> eval(T6);
17
For more information about the map command, refer to ?map.
142 • Chapter 4: Basic Data Structures
array( F, B, L );
a2 := array(1..3, [])
a3 := [a, b, c]
a4 := [a, b, c]
Array( F, B, L );
A2 := [0, 0, 0]
A3 := [a, b, c]
A4 := [a, b, c]
a := [1, 2, 3, 4]
> a;
> eval(a);
[1, 2, 3, 4]
18
There are additional built-in indexing function names for Arrays. For a complete
list, refer to ?rtable_indexingfunctions.
19
For more information about evaluation rules, see page 14 or refer to
?last_name_eval.
4.4 arrays and Arrays • 145
a3 3 := d
> eval(a3);
[a, b, d]
> A3[3] := d;
A3 3 := d
> A3;
[a, b, d]
> a7 := array(symmetric,1..2,1..2);
> a7[1,1] := 3;
a7 1, 1 := 3
> a7[1,2] := 4;
a7 1, 2 := 4
> eval(a7);
´ µ
3 4
4 ?2, 2
146 • Chapter 4: Basic Data Structures
a3 3 := a3 3
> eval(a3);
[a, b, ?3]
indices( a );
The order of the indices in the returned sequence does not necessarily
correspond to the order of the indices in the array.
> indices(a3);
[1], [2]
entries( a );
The order of the entries in the returned sequence does not necessarily
correspond to the order of the entries in the array.
> entries(a3);
20
For a list of Array storage formats, refer to ?Array.
4.4 arrays and Arrays • 147
[a], [b]
array
As with tables, the first operand is the indexing function (if any).
> op(1,eval(a7));
symmetric
21
Recall that arrays (like tables) have special evaluation rules. To access the array
object, apply the eval command.
148 • Chapter 4: Basic Data Structures
> op(2,eval(a7));
1..2, 1..2
[(1, 1) = 3, (1, 2) = 4]
The example above displays only two entries in array a7 because the
values of the entries located at (2, 1) and (2, 2) are implicitly specified
by the symmetric indexing function.
Similarly, you can use the op command to return the operands of an
Array, that is, the data type, indexing function, bounds, entries, entry
data type, storage type, and order. Table 4.4 lists the operands and the
corresponding op commands.
> op(A6);
a8 := [w, x, y, z]
4.4 arrays and Arrays • 149
> b := a8;
b := a8
> b[1] := 7;
b1 := 7
> eval(a8);
[7, x, y, z]
> eval(b);
[7, x, y, z]
> A8 := Array([1,2,4,8]);
A8 := [1, 2, 4, 8]
> B := A8;
B := [1, 2, 4, 8]
> B[1] := 0;
B1 := 0
> A8;
[0, 2, 4, 8]
> B;
[0, 2, 4, 8]
In the preceding examples, there is only one array (or Array). The
name b (B) points to the name a8 (A8) that points to the array (or Array)
structure.
150 • Chapter 4: Basic Data Structures
copy( a );
> c := copy(a8);
c := [7, x, y, z]
c1 := 10
> eval(a8);
[7, x, y, z]
> eval(c);
[10, x, y, z]
C := [0, 2, 4, 8]
C1 := π
> A8;
[0, 2, 4, 8]
> C;
[π, 2, 4, 8]
4.4 arrays and Arrays • 151
a8 := [2 x4 − x2 , x2 + 2 x, x3 + x]
A8 := [x, 23, y − 2]
> LinearAlgebra[Map](x->x*y,A8);
[x y, 23 y, (y − 2) y]
To modify the values in-place, that is, change the values in the original
array or Array, use the following method.23
> for entry in op(3,A8) do
> A8[lhs(entry)] := rhs(entry) + 1
> end do;
A8 1 := x + 1
A8 2 := 24
A8 3 := y − 1
22
For more information about the map command, refer to ?map.
23
This method (with op(2,...)) is used to modify tables in-place.
152 • Chapter 4: Basic Data Structures
> A8;
[x + 1, 24, y − 1]
name [ sequence ]
L := [x, y, z, x, y, z]
> S := {s,s};
S := {x, y, z}
24
For more information about selecting elements, refer to ?selection.
25
Although you can use the selection operation to select elements of a set, the order
of elements in a set is session dependent. Do not make any assumptions about this
order.
4.5 Selecting Elements from a Data Structure • 153
> S[2];
> L[-4];
[y, z]
> L[3..3];
[z]
> L[3..2];
[]
> L[3..1];
x, y, z
154 • Chapter 4: Basic Data Structures
Joe
> T[3,1];
T3, 1
a := [w, x, y, z]
> a[3];
> a[1..3];
a1..3
In this case, Arrays behave like lists. The range selection evaluates to
a subArray.
> B := Array([[1,2,3],[4,5,6],[7,8,9]]);
4.5 Selecting Elements from a Data Structure • 155
1 2 3
B := 4 5 6
7 8 9
> B[1..2,1..2];
´ µ
1 2
4 5
The op Command
You can use the op command to extract operands from sets, lists, tables,
and arrays.26 To use op in this manner, use the following syntax, where
i is an integer or integer range that represents the operand(s) to extract
and e is the data structure.27
op( i, e );
Sets and Lists Notice that if negative integers are used to indicate the
operands in a set or list, the elements are counted from the end: using -1
indicates the last element, using -2 indicates the second last, and so on.
> S := {10,11,12,13};
10
11, 12
26
In general, the use of op to extract operands from a list or set is less efficient than
using the selection operation because the entire list or set is evaluated. Therefore, if
possible, use the selection operation.
27
You cannot use the op command on a sequence because Maple interprets the ele-
ments of the sequence as individual arguments to op. Instead, you must access elements
of a sequence by using the selection operation []. For more information on sequence
selection, see page 152 or refer to ?sequence.
156 • Chapter 4: Basic Data Structures
> L := [a,b,c,d,e];
L := [a, b, c, d, e]
c, d, e
Tables, arrays, and Arrays Unlike sets, lists, and Arrays, tables and
arrays have special evaluation rules. For more information on using op
with tables, see 4.3 Tables. For more information on using op with arrays
and Arrays, see 4.4 arrays and Arrays.
select( f, x )
remove( f, x )
selectremove( f, x )
X := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
> select(isprime,X);
[2, 3, 5, 7]
> remove(isprime,X);
[1, 4, 6, 8, 9, 10]
The selectremove function returns two new objects of the same type
as x, the first containing the operands for which the Boolean-valued func-
tion f returns true and the second containing the operands for which f
returns false. The result is computed more efficiently than using both
select and remove because it evaluates f(xi) once for each operand.
> selectremove(isprime,X);
{sin(1), e(2 x) }
[11, 13]
T := table([1 = x, 2 = x2 , 3 = x3 , 4 = x4 ])
[x, x2 , x3 , x4 ]
Stacks
A stack is a data structure in which the removal order of the elements is
the reverse of the entry order. You can only insert (or push) and delete
(or pop) elements from the top of the stack. This behavior is referred to
160 • Chapter 4: Basic Data Structures
as LIFO (last in, first out). Stacks are implemented as tables in Maple.
They are created by using the stack commands.28
Begin by creating a new (empty) stack.
> s := stack[new]();
s := table([0 = 0])
Check the depth, the value of the top element, and the contents of
the stack.
> stack[depth](s);
> stack[top](s);
> eval(‘s‘);
table([0 = 3, 1 = h, 2 = a, 3 = t])
28
For more information about stacks in Maple, refer to ?stack.
4.7 Other Maple Data Structures • 161
Pop the letters off the stack. The original order of the letters is re-
versed.29
> while not stack[empty](s) do stack[pop](s); end do;
a
h
Queues
A queue is a data structure in which the removal order of elements is
the same as the entry order. This behavior is referred to as FIFO (first in,
first out). Queues are implemented as tables in Maple and are created by
using the queue commands.30
Create a new (empty) queue.
> q := queue[new]();
q := table([0 = 0])
Check the length, the value of the front element, and the contents
of the queue.
29
The order of this result is the reverse of that in the example in the following
subsection Queues.
30
For more information about queues in Maple, refer to ?queue.
162 • Chapter 4: Basic Data Structures
> queue[length](q);
> queue[front](q);
> eval(‘q‘);
table([0 = 3, 1 = h, 2 = a, 3 = t])
Remove the letters from the queue. The original order of the letters
is maintained.31
> while not queue[empty](q) do queue[dequeue](q); end do;
a
t
Other important data structures are the connected graph and adja-
cency matrix. For more information on these data structures, see 6.10 Us-
ing Data Structures to Solve Problems.
There are many other data structures in Maple. For example, the
matrix32 and vector33 constructors create special cases of arrays, and
the Matrix34 and Vector35 constructors create special cases of Arrays.
4.8 Troubleshooting
This section provides you with a list of common mistakes, examples, and
hints that will help you understand and avoid common errors. Use this
31
The order of this result is the reverse of that in the example in the preceding
subsection Stacks.
32
For information on the matrix constructor, refer to ?matrix.
33
For information on the vector constructor, refer to ?vector.
34
For information on the Matrix constructor, refer to ?Matrix.
35
For information on the Vector constructor, refer to ?Vector.
4.8 Troubleshooting • 163
section to study the errors that you may encounter when entering the
examples from this chapter in a Maple session.
s := a, b, c
L := [a, b, c, d]
> L[3..1];
36
For more information, refer to ?op.
37
For more information about selection and ranges, refer to ?selection.
164 • Chapter 4: Basic Data Structures
> L[0];
To avoid this error, use a range with a lower bound that is less than
the upper bound.
> L[1..3];
[a, b, c]
a := array(1..3, [])
a := array(1..3, [])
> a[4] := p;
> A := Array(1..2);
A := [0, 0]
To avoid this error, assign the entry to an index within the bound.
> a[3] := 100;
a3 := 100
> eval(a);
[?1 , ?2 , 100]
A2 := x − y
> A;
[0, x − y]
4.9 Exercises
1. Define a set with elements that are the powers of 13 modulo 100 for
exponents ranging from 1 to 1000. Is 5 a member of the set? Why is
it beneficial to use a set instead of a list?
Hint : You can determine the set by using one statement if you use
the seq command.
3. Find floating-point approximations for the sum of the square root and
cubic root of each of the first 15 powers of 2.
Hint : Use map, seq, and zip.
4.10 Conclusion
When you write a procedure, you generally have freedom to choose the
data structure used for the data. The choice of data structure can have
a great impact on the complexity and efficiency of the procedure. This
chapter presented a variety of data structures that you can use to write
procedures in Maple.
Procedures were introduced in chapter 1. Detailed information about
procedures is provided in chapter 6.
The next chapter formally discusses the statements and other con-
structs that control the number of times and order in which operations
are executed. These include the for...while...do looping construct,
and the if...then...else selection statement.
5 Flow Control
In This Chapter
• Selection and conditional execution control structures, the if state-
ment and the ‘if‘ operator
The if Statement
The most general form of the if statement has the following syntax.
1
Procedure calls and exception handlers (try...catch...finally statements) are
also forms of flow control in Maple. For more information about procedure calls, see
chapter 6. For more information about handling exceptions, see chapter 8.
167
168 • Chapter 5: Flow Control
if expr then
statseq
end if
if expr then
statseq1
else
statseq2
end if
Maple executes these selection statements as follows.
1. The conditional expression (expr) in the if clause is evaluated. The
conditional expression can be any Boolean expression, which evaluates
to true, false, or FAIL, formed by using:
2. If the result of the if clause is the Boolean value true, Maple executes
the statement sequence in the then clause. If the result of the if clause
is the Boolean value false or FAIL, Maple executes the statement
sequence in the else clause (if there is one).2
> if x<0 then
> 0
> else
> 1
> end if;
You can omit the else clause if you do not want to specify an action
if the condition is false.
> if x>0 then
> x := x-1
> end if;
“Negative”
2
For more information about Boolean expressions in Maple, see page 86 or refer to
?boolean.
170 • Chapter 5: Flow Control
> if r then
> print(1)
> else
> if not r then
> print(0)
> else
> print(-1)
> end if
> end if;
−1
if expr then
statseq
elif expr then
statseq
end if
if expr then
statseq
elif expr then
statseq
else
statseq
end if
The elif expr then statseq construct can appear more than once.
The following example implements the mathematical sign function by
using an elif clause.
> x := -2;
x := −2
−1
Maple does not have a formal case statement. However, you can use
the if statement as a case statement with the optional else clause as the
default case. For example, to write a program that accepts a parameter
n with four possible values (0, 1, 2, and 3), use the following code.3,4
> n := 5;
n := 5
3
A case statement is one that directs a program to choose one action from a list of
alternatives, depending on the value of a given variable. Case statements (or similar
constructs) are common to most programming languages.
4
For more information about the error statement, see page 219 or refer to ?error.
172 • Chapter 5: Flow Control
name of this function must be enclosed in right single quotes (’) because
if is a Maple reserved word.5
> b:=4;
b := 4
11
11
5.2 Repetition
A loop structure (repetition statement) executes a section of code multiple
times. Maple has two general forms of repetition statements that you can
use to perform looping in procedures. They have the following syntax.
5
For more information about reserved words in Maple, see page 24 or refer to
?reserved.
5.2 Repetition • 173
• for name
• from expr
• by expr
• to expr
• while expr
You can also omit the sequence of statements statseq. Excluding the
for clause, which must appear first, the clauses can appear in any order.
If you omit a clause, it has the default value shown in Table 5.1.
A typical for...from loop is used to generate a sequence of results.
6
You can replace many of the loops that use for or while statements with more effi-
cient and concise special forms. For more information, see 5.3 Looping Commands.
174 • Chapter 5: Flow Control
9
16
25
• The loop executes until i is strictly larger than 5. In this case, the
final value of i is 6.
> i;
You can also write the previous example by using the following state-
ment.
> for i from 2 by 1 to 5
> while true do
> i^2
> end do:
5.2 Repetition • 175
25
16
9
4
Example To find the first prime number greater than 107 , you could
write:
> for i from 10^7
> while not isprime(i) do
> end do;
After this statement is executed, i is the first prime larger than 107 .
> i;
10000019
Notice that the body of the loop is empty. Maple permits the empty
statement. Improve the program by considering only odd numbers.
> for i from 10^7+1 by 2
> while not isprime(i) do
> end do;
> i;
10000019
> to 5 do
> die();
> end do;
2
5
6
2
If all of the clauses in the for statement are omitted, an infinite loop
is produced.
do statseq end do
This has the same effect as the following code, but the do loop does
not assign a value to a dummy variable each iteration.
The for...in Loop The for...in loop has the following syntax.
The loop index name is assigned the operands of the first expr. You
can test the value of the index in the optional while clause, and, of course,
the value of the index is available when you execute the statseq. If the
object in expr contains at least one operand, then the value of the index
variable name remains assigned at the end of the loop .
For example, given a list L of integers, to find the integers that are
less than or equal to 7, use the following for loop.
5.2 Repetition • 177
> L := [7,2,5,8,7,9];
L := [7, 2, 5, 8, 7, 9]
> for i in L do
> if i <= 7 then
> print(i)
> end if;
> end do;
2
5
7
This code cycles through the operands of object L, in this case, a list.
The object can be, for example, a set, sum of terms, product of factors,
or string of characters.
while expr do
statseq
end do
x := 256
x := 64
x := 16
x := 4
x := 1
• The loop repeats until the while condition evaluates to false or FAIL.7
> x := 1/2:
> x;
1
2
> while x do
> x := x/2
> end do;
7
Maple evaluates the while condition before it executes the body of the loop.
5.2 Repetition • 179
L := [2, 5, 7, 8, 9]
> for i in L do
> print(i);
> if i=7 then
> break
> end if;
> end do;
5
7
L := [7, 2, 5, 8, 7, 9]
> for i in L do
> if i=7 then
> next
> end if;
> print(i);
> end do;
5
8
9
8
For more information about the break statement, refer to ?break.
180 • Chapter 5: Flow Control
2. zip
map( f, x )
9
When possible, use these Maple commands instead of a generic for or while loop
since the code for these commands is built into the Maple kernel. Therefore, it is
usually more efficient to perform computations by using them. However, there are
circumstances in which it is not desirable to use these special looping commands. For
more information, see page 185.
10
The exceptions are for a table, array, Array, or rtable. Maple applies the function
to the entries of the table, array, or Array not the operands or indices. For an rtable,
the function is applied to each element of the rtable, and then returns a new rtable of
the mapped result.
5.3 Looping Commands • 181
Example Given a list of integers, you can create a list of their absolute
values and of their squares by using the map command.
> L := [ -1, 2, -3, -4, 5 ];
q := [1, 2, 3, 4, 5]
X := 2 x y 2 − 3 y 4 z + 3 z w + 2 y 3 − z 2 w y
−3 y 4 z + 3 z w − z 2 w y
2 x y2 + 3 z w + 2 y3
For more information about these commands, see page 156 or refer to
?select.
zip(f, u, v )
zip(f, u, v, d )
[a1 , b2 , c3 , d4 , e5 , f6 ]
If the lists or vectors are not the same length, the length of the result
depends on whether you provide the argument d.
If you do not specify d, the length of the result is the same as the
length of the smaller list or vector.
11
There is a similar command for rtable-based Matrices and Vectors. For more in-
formation, refer to ?Zip.
5.3 Looping Commands • 183
[a + 1, b + 2, c + 3]
[a + 1, b + 2, c + 3, d + ξ, e + ξ, f + ξ]
seq(f, i = a..b )
add(f, i = a..b )
mul(f, i = a..b )
4.123, 5.123
1, 4, 9, 16
The result returned by add is the sum of the sequence. The result of
mul is the product of the sequence.
> add(i^2, i=1..4);
184 • Chapter 5: Flow Control
30
576
x1 + x2 + x3 + x4
In the case that a is greater than b, the result returned by seq, add,
and mul is the NULL sequence, 0, and 1, respectively.
> mul(i^2, i = 4..1);
You can also use the seq, add, and mul commands with the following
syntax.
seq(f, i = X )
add(f, i = X )
mul(f, i = X )
a := x3 + 3 x2 + 3 x + 1
3, 2, 1, 0
The result of add is the sum of the sequence. The result of mul is the
product of the sequence.
> add(degree(i,x), i=a);
> a := [23,-42,11,-3];
2423
31878
x1 , x2 , x3 , x4 , x5
if versus map The use of map or zip to simplify procedure code is not
always recommmended. For example, it is common for a procedure to
move to the next iteration once a result is determined without performing
all the operations. In these cases, use an if statement instead of the map
or zip command.
186 • Chapter 5: Flow Control
However, this “simpler” form allocates storage for a new set that is
otherwise unrelated to the problem and tests every element of the list.
Procedure IsStringList could also be written by using the following
code.
> IsStringList := proc( e )
> type( e, ’list’ ) and evalb( remove( type, e, ’string’ )
> = [] )
> end proc:
seq, add, and mul versus $, sum, and product The sequence operator,
$, and the sum and product commands are very similar to the seq, add,
and mul commands. However, they differ in an important way—the index
variable i and the end points a and b do not have to be integers.
> x[k] $ k=1..n;
5.4 Troubleshooting • 187
xk $ (k = 1..n)
1 1 1 1
(n + 1)3 − (n + 1)2 + n +
3 2 6 6
k := 10
5.4 Troubleshooting
This section provides you with a list of common mistakes, examples, and
hints that will help you understand and avoid common errors. Use this
12
The sum and product commands are not built into the kernel. Therefore, in general,
they are not as efficient as add and mul. For more information about efficiency, see
page 330 or refer to ?efficient.
188 • Chapter 5: Flow Control
section to study the errors that you may encounter when entering the
examples from this chapter in a Maple session.13
> p(a);
13
You can also use the Maple debugger to find errors in programs. For more infor-
mation, see chapter 8 or refer to ?debugger.
14
For more information about Boolean expressions, see page 86 or refer to ?boolean.
15
For more information about types, see 2.4 Types and Operands or refer to
?type.
5.4 Troubleshooting • 189
“a”
“b”
“c”
“d”
0.4142135625
1.914213562
3.414213562
16
For more information about the global variables, see Variables on page 201.
190 • Chapter 5: Flow Control
> k := 100;
k := 100
30
i := 100
17
For more information on delaying evaluation, see Unevaluated Expressions on
page 100.
18
For more information about the global variables, see Variables on page 201.
19
For more information on delaying evaluation, see Unevaluated Expressions on
page 100.
5.5 Exercises • 191
a1 , a2 , a3
5.5 Exercises
1. Find the product of the square root of all prime numbers less than
100.
Hint : The function isprime determines the primality of an integer.
2. Find the sum of all odd composite numbers less than 150.
4. Write a looping structure that finds the four substrings (of a string
assigned to the name MyString) containing only lower case letters,
upper case letters, decimal digits, and special characters.
Hint : You can use relational operators to compare characters.
5.6 Conclusion
This chapter discussed flow control in the Maple programming language.
Normally, the statements in a procedure body are executed sequentially.
However, you can control the order in which operations are executed by us-
ing the if...then...else selection statement, or the for...while...do
looping construct. For certain procedures, it is more efficient to use the
specialized looping commands: map; select, remove, and selectremove;
zip; seq, add, and mul; and $, sum, and product.
192 • Chapter 5: Flow Control
6 Maple Procedures
In This Chapter
• Structure of procedures
• Using procedures
• Automatic simplification of procedures
• Procedure return values
• Adding comments, such as copyright statements, and help pages for
procedures
• Alternate methods for defining procedures
• The procedure object
• Implementing data structures, using procedures, to solve problems
193
194 • Chapter 6: Maple Procedures
proc( P )
local L ;
global G ;
options O ;
description D ;
procedure body
end proc
Naming a Procedure
You can name a procedure by using an assignment statement in the same
manner as for other Maple objects. In general, a procedure must be as-
signed to a name so that you can invoke it with procedure calls. For
information about unnamed procedures, see page 232.1
> f := proc(x,y)
> x^2 + y^2
> end proc;
Executing a Procedure
You can execute (or invoke) a procedure assigned to a name by using a
procedure call.
1
You can assign a procedure to any number of names. For example, both f and g
are assigned the same procedure by using the following commands. f:=proc(x) x2 end
proc; g:=eval(f); map(addressof@eval,[f,g]);
6.1 Defining a Procedure • 195
procedureName( A );
Note: Maple evaluates the actual parameters before they are substi-
tuted for the formal parameters. These parameters are not evaluated
again during execution of the procedure. Prior to substitution, each actual
parameter is also checked against its specified type, if any (see page 197).
If the type checking fails, the procedure returns an error. The order in
which Maple tests the types of the actual parameters is unspecified. Type
checking actual parameters is optional.
13
The number of actual parameters need not be the same as the number
of specified formal parameters. If too few actual parameters are specified,
an error occurs if (and only if) a missing parameter is used during the ex-
ecution of the procedure body. Maple does not process extra parameters.
> f := proc(x,y,z)
> if x>y then
> x
> else
> z
> end if
> end proc:
> f(1,2,3,4);
2
For more information about return values, see 6.4 Procedure Return Values.
196 • Chapter 6: Maple Procedures
> f(1,2);
> f(2,1);
Formal Parameters
proc( P )
...
end proc
> F();
6.2 Procedure Components • 197
“Hello World”
p ::t
3
Maple has many expression types. For more information, refer to ?type. For more
information about parameters and type checking, refer to ?paramtype.
198 • Chapter 6: Maple Procedures
If you do not declare the type of a parameter, it can have any type.
For example, proc(x) is equivalent to proc(x::anything). In that case
it is recommmended that you use the latter form to inform other users
that the procedure works for any input.
The closing bracket of the formal parameter list can optionally be fol-
lowed by ::type_name; where type_name specifies a Maple type. Unlike
the case of formal parameters, this is not a type declaration, but rather
an assertion—a statement about the procedure that you assert to be
true. This optional assertion facility checks the return value type if you
set kernelopts(assertlevel=2). If the type violates the assertion, an
exception is raised.4
> F := proc(x :: numeric ) :: integer;
> x/2;
> end proc:
> F(3);
3
2
> kernelopts(assertlevel=2):
> F(3);
4
For more information about assertions and exceptions, see 8.3 Detecting Errors.
6.2 Procedure Components • 199
d2
> ans;
d2
The procedure squares the value of d and assigns the result to the
name ans.
To demonstrate parameter evaluation, first assign the name a the
value b. Then assign the name b the value c.
> a:=b;
a := b
> b:=c;
b := c
Use a as the first argument. Reset ans to a name so that the procedure
type check does not fail.
> ans := ’ans’;
ans := ans
c2
> ans;
c2
From the answer, it is clear that the value c is assigned to the param-
eter x.
Maple evaluates the arguments before invoking the procedure.
When you call a procedure, Maple evaluates the arguments as de-
termined by the context of the call. For example, if you call Sqr1 from
inside a procedure, Maple evaluates the local variable a to one level. For
more information about procedure variable evaluation rules, see page 203.
Thus, in the procedure g below, Maple evaluates a to b not c.
> g := proc()
> local a,b,ans;
> a := b;
> b := c;
> Sqr1(a,ans);
> end proc;
g := proc()
local a, b, ans ;
a := b ; b := c ; Sqr1(a, ans )
end proc
> g();
b2
Whether you call a procedure from the interactive level or from inside
a procedure, Maple evaluates the arguments to the level specified by the
context before invoking the procedure. Once Maple evaluates the argu-
ments, it replaces all occurrences of the corresponding formal parameters
with the actual arguments. Then Maple invokes the procedure.
Because Maple only evaluates parameters once, you cannot use them
as local variables. This is demonstrated by the following procedure.
> Cube := proc(x::anything, y::name)
> y := x^3;
> y;
> end proc:
> ans := ’ans’;
6.2 Procedure Components • 201
ans := ans
ans
> ans;
Maple replaces each y with ans, but does not evaluate these occur-
rences of ans again. Thus, the final line of Cube returns the name ans,
not the value assigned to ans.
Use parameters only to pass information into the procedure. Param-
eters are objects that are evaluated to zero levels.
Variables
A variable represents a data item, such as a numerical value or a character
string, that can change its value during the execution of a program. This
section describes local variables, global variables, and their use in Maple
procedures.
A local variable is a variable that has meaning only within a particu-
lar procedure. If the name of a local variable is used outside the procedure,
it (usually) refers to a different instantiation of the name. Global vari-
ables are recognized inside and outside the procedure.
Like procedure return values, you can assert the type of each local
variable in the local variable declaration statement by using the following
syntax.
f := x + y
> x := z^2/ y;
z2
x :=
y
> z := y^3 + 3;
z := y 3 + 3
(y 3 + 3)2
+y
y
x+y
> eval(f,2);
204 • Chapter 6: Maple Procedures
z2
+y
y
> eval(f,3);
(y 3 + 3)2
+y
y
y2
5
The concept of one-level evaluation does not occur in traditional programming
languages. However, in Maple, you can assign to a variable a formula involving other
variables (to which you can assign values, and so on).
6.2 Procedure Components • 205
1 1√ 1 √ p √
[1, − + 5 + I 2 5 + 5,
4 4 4
1 1√ 1 √ p √ 1 1√ 1 √ p √
− − 5 + I 2 5 − 5, − − 5 − I 2 5 − 5,
4 4 4 4 4 4
1 1√ 1 √ p √
− + 5 − I 2 5 + 5]
4 4 4
Undeclared Variables If a variable is not declared local or global in the
one (or more) procedures in which it is enclosed, Maple determines its
scope. A variable is automatically made local in the following two cases.
• It appears on the left-hand side of an assignment statement. For ex-
ample, A in A := y or A[1] := y.
• It appears as the index variable in a for loop, or seq, add, or mul
command.
If neither of these two rules applies, the variable is a global variable.
To illustrate how Maple reacts to undeclared variables, consider the
revised Max procedure.
> Max := proc()
> if nargs = 0 then
> return -infinity
> end if;
> m := args[1];
> for i from 2 to nargs do
> if args[i] > m then
> m := args[i]
> end if;
> end do;
> m;
> end proc:
The NewName procedure creates the next unused name in the sequence
C1, C2, .... The name that NewName creates is a global variable since neither
of the two previous rules apply to cat(C,N).
> NewName := proc()
> global N;
> N := N+1;
> while assigned(cat(C,N)) do
> N := N+1;
> end do;
> cat(C,N);
> end proc:
> N := 0;
N := 0
C1 sin(x) + C2 cos(x)
Procedure Options
proc( ... )
variable declarations
options O ;
description
procedure body
end proc
6
As is the case with any global side effect, assigning to a global variable in a pro-
cedure invalidates that procedure for option remember. For more information about
option remember, see page 210.
6.2 Procedure Components • 207
You can use any symbol to specify an option name. However, the
following terms have special meanings.7
The arrow Option The arrow option has meaning only when specified in
conjunction with option operator. The arrow option causes the Maple
prettyprinter to print the procedure using arrow notation. For more
information, see page 209.
> f := proc(x, y)
> option operator;
> x^2 + y^2
> end proc;
> f := proc(x, y)
> option operator, arrow;
> x^2 + y^2
> end proc;
f := (x, y) → x2 + y 2
The builtin Option Maple has two classes of procedures: kernel pro-
cedures written in the C programming language, and library procedures
written in the Maple programming language. Because the built-in kernel
functions are compiled, you cannot view their procedure definitions. The
builtin option is used to identify a kernel procedure.
You see this option when you evaluate a built-in procedure. Also,
instead of displaying the source code, a number is displayed. This number
uniquely identifies each built-in procedure. You cannot create built-in
procedures.8
For example, the add function is in the kernel.9
> eval(add);
7
For more information about symbols in Maple, see Names on page 26 or refer to
?symbol. For more information about procedure options, refer to ?options.
8
For information on using external compiled code, see the call_external option in
this section.
9
For more information about the Maple system and built-in functions, refer to
?builtin.
208 • Chapter 6: Maple Procedures
true
false
10
For more information about using the interface variable, see page 258 or refer to
?interface.
6.2 Procedure Components • 209
> interface(verboseproc=2);
> eval(f);
(x, y) → x2 + y 2
11
For more information about functional operators, see page 231 or refer to
?operators,functional.
210 • Chapter 6: Maple Procedures
> f := proc(x, y)
> option operator;
> x^2 + y^2
> end proc;
> f := proc(x, y)
> option operator, arrow;
> x^2 + y^2
> end proc;
f := (x, y) → x2 + y 2
12
You can also explicitly associate a remember table with a procedure by direct
assignment to the table. For example, if f is the name of the procedure definition,
the commands f(0):=0; f(2):=1; creates the remember table table([0=0, 2=1)] for
procedure f. For more information about tables and remember tables in Maple, refer
to ?table or ?remember.
13
For a comparison of run-time efficiency with option remember, see Profiling a
Procedure on page 332.
6.2 Procedure Components • 211
Fib := proc(n::nonnegint )
option remember ;
if n < 2 then n else Fib(n − 1) + Fib(n − 2) end if
end proc
> Fib(4);
> eval(Fib);
proc(n::nonnegint )
option remember ;
if n < 2 then n else Fib(n − 1) + Fib(n − 2) end if
end proc
# (0) = 0
# (1) = 1
# (2) = 1
# (3) = 2
# (4) = 3
Since Fib has the remember option, if you invoke the procedure again
with an argument greater than 4:
• The results for all calls to Fib with arguments less than or equal to 4
are read from the Fib remember table, and
14
An alternate way to view the remember table of a procedure that has option
remember is to use op(4, eval(f)), where f is the name of the procedure definition.
For more information, see Procedure Operands on page 237, or refer to ?procedure
or ?op.
212 • Chapter 6: Maple Procedures
• All calls to Fib with arguments greater than 4 are computed and
appended to the Fib remember table.
> Fib(7);
13
> eval(Fib);
proc(n::nonnegint )
option remember ;
if n < 2 then n else Fib(n − 1) + Fib(n − 2) end if
end proc
# (0) = 0
# (1) = 1
# (2) = 1
# (3) = 2
# (5) = 5
# (4) = 3
# (7) = 13
# (6) = 8
The system Option If option system is specified in conjunction with
option remember in the options field of a Maple procedure, entries in
the procedure’s remember table are removed during garbage collection,
freeing the space occupied by the remember table and its entries.15
> Fib := proc( n :: nonnegint )
> option remember, system;
> if n<2 then
> n
> else
> Fib(n-1) + Fib(n-2)
> end if;
> end proc;
15
For more information about garbage collection in Maple, see page 335 or refer to
?gc.
6.2 Procedure Components • 213
Fib := proc(n::nonnegint )
option remember , system;
if n < 2 then n else Fib(n − 1) + Fib(n − 2) end if
end proc
The trace Option If the trace option is included in a procedure defini-
tion, Maple shows the entry and exit calls, and all the internal statements
when the procedure is executed. This effect is independent of the value of
the printlevel variable.16
16
For more information about tracing a procedure and printlevel, see chapter 8 or
refer to ?trace and ?printlevel.
214 • Chapter 6: Maple Procedures
Procedure Description
proc( ... )
variable and option declarations
description D ;
procedure body
end proc
The last part of the procedure header is the description field. It is used
to specify lines of text that describe a procedure. Its use is optional. How-
ever, if used, it must be entered after local variables, global variables, and
options, and before the body of the procedure. Descriptions are specified
by using the following format, where D is any symbol or string.
description string ;
proc(x::integer , y::integer )
local a;
description “compute the average of two integers”;
a := 1/2 ∗ x + 1/2 ∗ y
end proc
Maple prints the description field even if it does not print the body
of a procedure because there is a copyright option.
6.3 Procedure Interpretation • 215
> f := proc(x)
> option ‘Copyrighted ?‘;
> description "computes the square of x";
> x^2; # compute x^2
> end proc:
> eval(f);
proc(x)
description “computes the square of x”
...
end proc
You can include more than one line of text in the description field by
splitting the description string into smaller strings.
> f := proc(x)
> description "This example shows "
> "how to include "
> "a multi-line description.";
> x^2;
> end proc:
> eval(f);
proc(x)
description“This example shows how to include a \
multi-line description.”;
x2
end proc
17
For more information about statements to perform numeric, symbolic, and graph-
ical computations, refer to the Maple Advanced Programming Guide.
216 • Chapter 6: Maple Procedures
G := proc(x)
x ∗ 1/0.1000000000000000000010 ∗ 102 1
end proc
If these procedures are executed with Pi as the parameter and then
evaluated to a floating-point result, procedure F works correctly, but pro-
cedure G does not because the reciprocal has already been computed at
10 Digits of precision. Notice the different results.18
> evalf[200]( F(Pi) );
18
For more information about floating-point numbers and Digits, see page 65 and
refer to ?Digits.
6.4 Procedure Return Values • 217
0.3141592653589793238431227456743604951812\
85712480766977145681602105973970857164083\
84174374282564006595979737122307183000511\
14107487243399231214218333256047125138141\
919369378049854178225429255174431840210−19
> evalf[200]( G(Pi) );
0.3141592653589793238431227456743604951812\
85712480766977145681602105973970857164083\
84174374282564006595979737122307183000511\
14107487243399231214218333256047125138141\
919369378049854178225429255174431840210−19
• explicit return
• error return
Explicit Returns
An explicit return occurs when a return statement is executed inside a
procedure. The return statement causes an immediate return to the point
where the current procedure was invoked. It has the following syntax,
where sequence is a sequence, set, or list of zero, one, or more expressions.
19
It is possible to return a value through a parameter in a Maple procedure, but
it is not recommended. Parameters in Maple procedures should be treated as input
parameters—used for input, but not changed in the procedure. For more information,
see page 220.
218 • Chapter 6: Maple Procedures
return sequence
0, 0, 0
> GCD(12,8);
4, 3, 2
You can use the Boolean constants true, false, and FAIL in a return
statement. In particular, FAIL is often used in a return statement to
indicate that the computation failed or was abandoned.20
20
For more information about return statements, refer to ?return and ?FAIL.
6.4 Procedure Return Values • 219
FAIL
Error Returns
An error return occurs when an error statement is executed inside a pro-
cedure. The error statement indicates that an exception has occurred,
and the execution of the current statement sequence in the procedure is
interrupted. Then, control is passed to the next applicable catch clause
in the enclosing try...catch statement (if one exists) to test whether
the error can be handled. If control is not passed to a catch clause at this
level, or if the exception cannot be handled by a catch clause at this level,
the exception is re-raised at the next higher execution handler level (in
other words, at the next enclosing try...catch statement). This process
continues until either the exception is handled or execution returns to
the top level (in which case the exception becomes an error). The error
statement has the following syntax, where msgString is the string Maple
displays when the error occurs and msgParams are the parameters substi-
tuted into msgString.21
error msgString
error msgString, msgParams
21
For more information, refer to ?error.
22
For more information about error returns and handling exceptions, see page 323
or refer to ?error.
220 • Chapter 6: Maple Procedures
If Member is called with two arguments, that is, nargs is 2, the part
of the body of Member that is executed does not refer to the formal pa-
rameter, p. Therefore, Maple does not return an error.
> Member( x, [a,b,c,d] );
false
q := 78
23
If the third parameter has not been declared as evaln, enclose the name q in single
right quotes (’q’) to ensure that the name, and not the value, of q is passed to the
procedure.
6.4 Procedure Return Values • 221
true
> q;
0<m
24
For a simple example, see page 200.
222 • Chapter 6: Maple Procedures
m+1
m+2
Returning Unevaluated
If a procedure cannot perform a computation, the unevaluated function
invocation may be returned. For example, procedure Max calculates the
maximum of two numbers, x and y.
> Max := proc(x,y)
> if x>y then
> x
> else
> y
> end if
> end proc:
This version of Max requires that its arguments are numerical values.
> Max(3.2, 2);
3.2
The error occurs because Maple evaluates Max(x, 1/x) before the
plot command is invoked. The solution is to make Max return unevaluated
when its parameters, x and y, are not numeric. That is, in such cases Max
should return ’Max’(x,y).
> Max := proc(x, y)
> if type(x, numeric) and type(y, numeric) then
> if x>y then
> x
> else
> y
> end if;
> else
> ’Max’(x,y);
> end if;
> end proc:
The new version of Max handles both numeric and non-numeric input.
> Max(3.2, 2);
3.2
Max(x, 2 y)
1.8
1.6
1.4
1.2
1
0.6 0.8 1 1.2 1.4 1.6 1.8 2
x
You can improve Max so that it can find the maximum of any number
of arguments. Inside the revised procedure, args is the sequence of actual
parameters, nargs is the number of actual parameters, and procname is
the name of the procedure.
> Max := proc() local m, i;
> m := -infinity;
> for i in (args) do
> if not type(i, numeric) then
> return ’procname’(args);
> end if;
> if i>m then
> m := i
> end if;
> end do;
> m;
> end proc:
> Max(3,1,4);
> Max(3,x,1,4);
Max(3, x, 1, 4)
The sin function and int command (integration) follow the same
model as the Max procedure. If Maple can compute the result, it is re-
turned. Otherwise, sin and int return unevaluated.
6.5 Documenting Your Procedures • 225
Indicating Copyright
The Copyright option is used to indicate a copyright notice for a proce-
dure. For more information, see page 208 or refer to ?options.
25
As described in chapter 1, you can enter Maple commands over multiple lines in
interactive mode.
226 • Chapter 6: Maple Procedures
Adding Comments
The pound sign (#) marks the characters following it on a line as a com-
ment. In other words, Maple does not process anything on the line after
the #. If you use the eval command to view the contents of a procedure
definition, any comments in the definition are not displayed.
> f := proc(x)
> x^2; # compute x^2
> end proc:
> eval(f);
> f := proc(x)
> description "computes the square of x";
> x^2; # compute x^2
> end proc:
> eval(f);
proc(x)
description “computes the square of x”;
x2
end proc
26
For more detailed information about Maple I/O features, see chapter 7, or refer to
?read and ?save.
228 • Chapter 6: Maple Procedures
The read command reads files that contain Maple statements back
into a Maple session. The statements in the file are read and executed as
if they were being entered directly into a Maple session.27
> read "myfile";
proc(x::complex(numeric), y::complex(numeric))
if abs(y) < abs(x) then x else y end if
end proc
You can also use the read command to read Maple procedures written
in your favorite text editor.
a := 3
> a;
27
When using the read command, the statements are not echoed to the display unless
interface(echo) is set to 2 or higher. For more information, refer to ?interface.
28
For more information about the built-in kernel routines, see page 207 or refer to
?builtin.
6.7 Viewing Maple Library Source Code • 229
This model of evaluation that hides the procedure details is called last
name evaluation. This approach is used because procedures can contain
many subobjects. To obtain the true value of the name f, use the eval
command, which forces full evaluation.29
> eval(f);
29
Last name evaluation applies to procedures, tables, and modules in Maple. For
more information, refer to ?last_name_eval.
230 • Chapter 6: Maple Procedures
Then, to view the code for any Maple library routine that is not built-
in or local to a module, use the name of the procedure as the argument
to the print command. For example, use the following command to view
the source code for the blackscholes routine in the finance package.30
> print(finance[blackscholes]);
30
Viewing the source code in this manner does not display any procedure documen-
tation.
31
You must set the interface option verboseproc because Maple library routines
use the copyright option, which suppresses the display of the procedure body. User-
defined procedures generally do not use this option. Hence, setting the interface option
is not necessary to view user-defined procedures. To view the code of a user-defined
procedure, use the eval command.
6.8 Alternate Methods for Defining a Procedure • 231
( P ) -> B
F := (x, y) → x2 + y 2
If the procedure requires only one parameter, you can omit the paren-
theses around the formal parameter.
> G := n -> if n<0 then 0 else 1 end if;
> G(-1);
You can also use declared parameters with the functional operator.
> H := (n::even) -> n! * (n/2)!;
1
H := n::even → n! ( n)!
2
232 • Chapter 6: Maple Procedures
> H(6);
4320
> H(5);
unapply(B, P );
F := (x, y) → x2 + y 2
32
For more information about functional operators, see page 209 or refer to
?functional.
33
For more information about the unapply command, refer to ?unapply.
34
For information about named procedures, see page 194.
6.8 Alternate Methods for Defining a Procedure • 233
x → x2
t2
You can use the same method to invoke an unnamed procedure created
by using the proc...end proc construct.
> proc(x,y) x^2 + y^2 end proc(u,v);
u2 + v 2
When using the map command35 , you can use unnamed procedures.
> map( x -> x^2, [1,2,3,4] );
[1, 4, 9, 16]
x → 2x
1
F := exp + 2 (z → )
z
35
For more information on the map command, see page 180.
36
For more information about the differential operator, refer to ?D.
234 • Chapter 6: Maple Procedures
2
ex +
x
> f(a,b,c);
[a, b, c]
> f(c);
[c]
> f();
[]
Max := proc()
if args2 < args1 then args1 else args2 end if
end proc
The special name nargs is assigned the total number of actual parame-
ters passed to a procedure. Using nargs, it is possible to write a procedure,
Max, that finds the maximum of any number of arguments, but does not
have any formal parameters declared in the procedure header.
> Max := proc()
> local i,m;
> if nargs = 0 then
> return -infinity
> end if;
> m := args[1];
> for i from 2 to nargs do
> if args[i] > m then
> m := args[i]
> end if;
> end do;
> m;
> end proc:
Find the maximum of the three values 2/3, 1/2, and 4/7.
> Max(2/3, 1/2, 4/7);
2
3
Find the maximum of the four values 1.3, 4/3, 7/5, and 9/7.
> Max(1.3, 4/3, 7/5, 9/7);
236 • Chapter 6: Maple Procedures
7
5
true
> type(F,procedure);
true
> type(F,name(procedure));
true
> type(eval(F),procedure);
true
37
For more information about if statements, see page 167 or refer to ?if.
6.9 The Procedure Object • 237
true
Procedure Operands
Every Maple procedure has seven operands (the value for any of the
operands can be NULL). Table 6.1 lists these operands and the correspond-
ing op command that you can use to access them. In the op commands,
procName is the name of the procedure.
38
For more information about structured types in Maple, see page 106 or refer to
?structured.
238 • Chapter 6: Maple Procedures
proc(x::name, n::posint )
description “a summation”
...
end proc
> op(1, eval(f)); #formal parameters
x::name, n::posint
Copyright
f(t, 3) := 12
table([(t, 3) = 12])
“a summation”
39
For more information about remember tables in procedures, see page 210.
40
The lexical table of a procedure stores information about lexically-scoped variables.
For more information, refer to ?examples,lexical.
6.10 Using Data Structures to Solve Problems • 239
Alternatively, you can list all of the operands of a procedure with one
command.
> op(eval(f));
Computing an Average
A common problem is to write a procedure that computes the average of
n > 0 data values x1 , x2 , . . . , xn according to the following equation.
n
1X
µ= xi .
n
i=1
Before the procedure is written, think about which data structure and
Maple commands to use. You can represent the data for this problem as
41
For a list of built-in Maple types, refer to ?type.
240 • Chapter 6: Maple Procedures
a list. The nops command returns the total number of entries in a list X,
while the ith entry of the list is found by using X[i].
> X := [1.3, 5.3, 11.2, 2.1, 2.1];
> nops(X);
> X[2];
5.3
You can add the numbers in a list by using the add command.
> add( i, i=X );
22.0
Using these ideas, write the procedure Average which computes the
average of the entries in a list. It handles empty lists as a special case.
> Average := proc(X::list) local n, i, total;
> n := nops(X);
> if n=0 then
> error "empty list"
> end if;
> total := add(i, i=X);
> total / n;
> end proc:
Using this procedure you can find the average of list X defined above.
> Average(X);
4.400000000
1 1 1
a+ b+ c
3 3 3
6.10 Using Data Structures to Solve Problems • 241
MyList := [1, 2, 3, 4, 5, 6]
true
The type of loop that Member uses occurs so frequently that Maple
has a special version of the for loop for it. Compare the previous version
of Member to the one below.43
> Member := proc( a::anything, L::{list, set} ) local i;
> for i in L do
> if a=i then
> return true
> end if;
> end do;
> false;
> end proc:
Test the new for loop version of the procedure Member on a set.
> myset := {1,2,3,4};
42
Instead of using procedure Member, you can use the built-in member command.
43
For more information about loops, see 5.2 Repetition or refer to ?for.
242 • Chapter 6: Maple Procedures
myset := {1, 2, 3, 4}
false
false
true
false
44
For more information about plotting in Maple, refer to the Maple User Manual or
?plot. For information about graphics programming, refer to chapter 5 of the Maple
Advanced Programming Guide.
244 • Chapter 6: Maple Procedures
1.5
0.5
–1 –0.5 0.5 1
You can use this approach to write a procedure that plots the complex
roots of a polynomial.
y := x3 − 1
First, find the roots of this polynomial. You can find the numeric
solutions to this polynomial by using fsolve.
> R := [ fsolve(y=0, x, complex) ];
R := [−0.5000000000 − 0.8660254038 I,
−0.5000000000 + 0.8660254038 I, 1.]
Next, change this list of complex numbers into a list of points in the
plane. The Re and Im commands return the real and imaginary parts of
a complex number, respectively.
> points := map( z -> [Re(z), Im(z)], R );
0.8
0.6
0.4
0.2
Using the sequence of steps in the previous example, you can write a
procedure to automate the process. The input must be a polynomial in x
with constant coefficients.
> RootPlot := proc( p::polynom(constant, x) ) local R, points;
> R := [ fsolve(p, x, complex) ];
> points := map( z -> [Re(z), Im(z)], R );
> plot( points, style=point, symbol=point,
> color=black );
> end proc:
0.5
–3 –2 –1 1
–0.5
–1
> RootPlot( y );
0.5
–1 –0.5 0 0.5 1
–0.5
–1
Connected Graphs
Suppose that there is a number of cities, some with roads between them.
You want to determine whether travel by road between any two of the
cities is possible.
You can express this problem in terms of graph theory by using the
Maple networks package. You do not need to understand graph theory or
the networks package to benefit from the examples in this section. The
networks package is used primarily as a shortcut for drawing graphs.
Create a new graph G using the new command and add a few cities
(or vertices, in the terminology of graph theory).
> new(G):
> cities := {Zurich, Rome, Paris, Berlin, Vienna};
To add roads between Zurich and each of Paris, Berlin, and Vienna,
use the connect command. The roads are automatically named e1, e2,
and e3.
> connect( {Zurich}, {Paris, Berlin, Vienna}, G );
6.10 Using Data Structures to Solve Problems • 247
e1 , e2 , e3
Similarly, add roads between Rome and Zurich, and between Berlin
and both Paris and Vienna.
> connect( {Rome}, {Zurich}, G);
e4
e5 , e6
Paris
Rome
Berlin
Vienna
Zurich
From the drawing, it is obvious that you can travel by road between
any two cities. You can also use the connectivity command to determine
this fact.
> evalb( connectivity(G) > 0 );
true
The data structures that the networks package uses are complicated
because the package supports more general structures than this example
requires. You must decide what data structure to use to determine how
the cities and roads can best be represented in this example.
248 • Chapter 6: Maple Procedures
Representing the Data as a Set Since cities have distinct names and
the order of the cities is irrelevant, represent the cities as a set of names.
> vertices(G);
{e2 , e1 , e3 , e4 , e6 , e5 }
You can also represent a road as the set consisting of the two cities
that the road connects.
> ends(e2, G);
{Zurich, Berlin}
{Zurich, Berlin}
You can represent the data as a table of neighbors; there is one entry
in the table for each city.
> T := table( map( v -> (v)=neighbors(v,G), cities ) );
> indices(T);
Since the indices command returns a sequence of lists, you must use
the op and map command to generate a set.
> map( op, {%} );
> Connected(T);
true
You can add the cities Montreal, Toronto, and Waterloo, and the
highways between them.
> T[Waterloo] := {Toronto};
TWaterloo := {Toronto}
TMontreal := {Toronto}
You can no longer travel by road between any two cities. For example,
you cannot travel from Paris to Waterloo.
> Connected(T);
false
6.11 Troubleshooting
This section provides you with 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.45
Missing Argument
Maple generates an error if an argument in a procedure call is missing,
but only when it is first required.46
45
You can also use the Maple debugger for finding errors in programs. For more
information, see chapter 8 or refer to ?debugger.
46
For more information about the if statement, see 5.1 Selection and Conditional
Execution or refer to ?if.
252 • Chapter 6: Maple Procedures
> G := proc(x, y)
> if x > 2 then
> x
> else
> y
> end if
> end proc:
> G(3);
> G(1);
> G(1,12);
12
> F := proc(x)
> y := x + 1;
> end proc;
However, you can assign any expression to a name. Study the following
examples to see the difference between assigning a value, function, and
remember table to a name.
Assign the value t^2 to the name phi.
> phi := t^2;
φ := t2
> phi;
t2
> print(phi);
t2
47
Functions can be defined by using the arrow notation ->. For more information,
see Functional Operators: Mapping Notation on page 231.
254 • Chapter 6: Maple Procedures
φ := t → t2
> phi;
> phi(3);
> print(phi);
t → t2
φ(t) := t2
> phi;
> print(phi);
table([t = t2 ])
> phi(t);
t2
6.12 Exercises • 255
6.12 Exercises
1. Improve the general Max procedure on page 224 so that Max(3,x,1,4)
returns Max(x,4). That is, the procedure returns the maximum nu-
merical value along with all nonnumerical values.
√ 3
2. Implement the function f (x ) = 1 − x2 −1, first as a procedure, and
then by using the mapping notation. Compute f (1 /2 ) and f (0 .5 ),
and comment on the different results.
3. You can use ab/g to compute the least common multiple of two inte-
gers, a and b, where g is the greatest common divisor of a and b. For
example, the least common multiple of 4 and 6 is 12. Write a Maple
procedure, LCM, which takes as input n > 0 integers a1 , a2 , ... , an
and computes their least common multiple. By convention, the least
common multiple of zero and any other number is zero.
4. Write a Maple procedure called Sigma which, given n > 1 data val-
ues, x1 , x2 , . . . , xn , computes their standard deviation. The following
equation gives the standard deviation of n > 1 numbers, where µ is
the average of the data values.
v
u n
u1 X
σ=t (xi − µ)2
n
i=1
6.13 Conclusion
This chapter discussed the various parts of a Maple procedure when it
is created by using the proc...end proc construct. Alternate methods
to create a procedure, such as using functional operators, the unapply
command, and the map command were also discussed.
Once a procedure is defined, it is beneficial to format and docu-
ment the code for readability. This saves time in the future when error-
correcting or adding enhancements.
When a procedure is invoked, Maple uses particular evaluation rules.
Local variables are, generally, evaluated to one level, and global variables
are evaluated fully. The arguments to a procedure are evaluated at the
time it is invoked. The manner in which they are evaluated depends upon
the environment in which the call occurs, and in some cases, the types
specified in the procedure definition. Once evaluated, Maple substitutes
the values into the procedure, and then executes it. Maple does no further
evaluation on the values which it substituted, unless you specifically use
an evaluation command, for example, eval. This rule makes it impractical
to use parameters to store temporary results, as you would use local
variables.
7 Input and Output
Input and output (I/O) in Maple can be divided into two categories:
screen and keyboard I/O (for communication within Maple, and between
Maple and the user), and standard disk I/O (for communication between
Maple and other software). This chapter discusses both types of I/O in
relation to writing procedures.1
In This Chapter
• Displaying output to the screen
1
The Sockets package contains routines that perform data exchanges between pro-
cesses on remote hosts on a network. This allows I/O operations over Intranets and the
Internet. For more information, refer to ?Sockets.
257
258 • Chapter 7: Input and Output
Int(x^2,x = 1 .. 10)
2
For greater control over the format of output, you can set other interface variables
such as verboseproc and screenwidth. For more information about the interface
command and these variables, refer to ?interface.
7.1 Screen and Keyboard I/O • 259
10
/
| 2
| x dx
|
/
1
If you are using Maple in a graphical user interface (GUI), you can set
the value of prettyprint to higher values, or you can use the Options
Dialog in the Maple worksheet to set the Output Display.3
> interface(prettyprint=2);
10
/
| 2
| x dx
|
/
1
> interface(prettyprint=3);
3
For more information about the Options Dialog, refer to
?worksheet,managing,preferences.
260 • Chapter 7: Input and Output
10
/
| 2
| x dx
|
/
1
The print Command The print command displays the values of the
expressions that appear as its arguments, separated by a comma and a
blank space.
4
For more information about printlevel, see Tracing a Procedure on page 315
or refer to ?printlevel.
7.1 Screen and Keyboard I/O • 261
> %;
T := table([1 = w, 2 = x, 3 = y, 4 = z])
> T;
> P;
> print(T);
table([1 = w, 2 = x, 3 = y, 4 = z])
262 • Chapter 7: Input and Output
> print(P);
The lprint Command The lprint command displays the values of the
expressions expr1, expr2, ... as valid Maple syntax in a one-dimensional
format.
> %;
%[flags][width][.precision][modifiers]code
5
The printf function is based on a C standard library function of the same name.
7.1 Screen and Keyboard I/O • 263
12345
12345
+12345
12345 6789
+12345 hi z
> printf("The %-s of the %-s\nis %-a dollars.", price, hat, 10);
Pi is approximately 3.14.
Interactive Input
Input is normally passed to Maple procedures by using parameters. How-
ever, you can write a procedure that requests input from the user while
the procedure is executing. For example, you can write a procedure that
quizes a student (for example, generates random problems, accepts input,
and then verifies the student’s answers). The input can be the value of a
certain parameter or whether a number is positive. Maple has two com-
mands for reading input from the terminal: the readline and readstat
commands.
Reading Text from the Terminal The readline command reads one
line of text from a file or the keyboard. It has the following syntax.
readline( filename )
> DetermineSign(u-1);
> y
true
Reading Expressions from the Terminal You can also write procedures
that require the user to input an expression rather than a string. The
readstat command reads one Maple statement from the keyboard.
6
You can also use the readline command to read a single line of text from a file.
For more information, see page 274 or refer to ?readline.
7
The printf command is used to print expressions. For more information about
printf, see page 262 or refer to ?printf.
266 • Chapter 7: Input and Output
readstat( promptString )
8
For information about other options available to readstat, refer to ?readstat.
7.1 Screen and Keyboard I/O • 267
> InteractiveDiff :=
> proc() local a, b;
> a := readstat("Please enter an expression: ");
> b := readstat("Differentiate with respect to: ");
> printf("The derivative of %a with respect to %a is %a\n",
> a, b, diff(a,b))
> end proc:
> InteractiveDiff();
9
The indets command finds the indeterminates of an expression. For more infor-
mation, refer to ?indets.
268 • Chapter 7: Input and Output
The readstat command can also be used to read one statement from
a file. For more information, refer to ?readstat.
s := "a*x^2 + 1"
> y := parse( s );
7.2 Standard Disk I/O • 269
2
y := a x + 1
true, true
The parse command does not evaluate the expression it returns. You
must use the eval command to evaluate the expression explicitly. For
example, Maple does not evaluate the variable a to its value 2 until you
explicitly use the eval command.
> a := 2;
a := 2
> z := parse( s );
2
z := a x + 1
> eval(z);
2
2 x + 1
This section discusses some basic tools for accessing and storing data in
files.
10
For more information about other file formats in Maple, refer to ?filetypes and
?files.
11
For more information about file management with worksheet files in a GUI envi-
ronment, refer to the Maple Getting Started Guide or ?managing.
7.2 Standard Disk I/O • 271
General Data Files Maple can import and export files that contain for-
matted numerical data, and files that contain both formatted textual and
numerical data. You can create these general data files by using a text
editor, and then read them into Maple to perform computations.
12
For more information about backslashes and filenames, refer to ?backslash and
?filename.
272 • Chapter 7: Input and Output
Maple saves each variable (and its value) in nameseq in the file
filename. Maple evaluates each argument in nameseq to a name. The
last argument (filename) is fully evaluated. It must evaluate to a string
(or name) that specifies a valid filename.
For example, clear the Maple internal memory by using the restart
command and assign new values.
> r0 :=
x^3:
> r1 :=
diff(r0,x):
> r2 :=
diff(r1,x):
> r3 :=
proc(y) local a;
> a := irem(y, 2);
> if a=0 then
> "Even"
> else
> "Odd"
> end if
> end proc:
The following statement saves r0, r1, r2, and r3 in the ASCII file
named my_file in the current working directory.13
> save r0, r1, r2, r3, "my_file";
Once this statement is executed, the following lines form the contents
of file my_file.14
r0 := x^3;
r1 := 3*x^2;
r2 := 6*x;
13
To determine the current working directory, use the currentdir function.
14
You can also append commands entered in a Maple session to an existing file. For
more information, refer to ?appendto.
7.2 Standard Disk I/O • 273
read filename;
The filename must evaluate to the name of a valid file. Reading the
file is identical to entering the same sequence of statements interactively
into a Maple session, except that the input statements are not echoed to
the screen. The system only displays the result of executing each state-
ment read from the file.
> read "my_file";
r0 := x3
r1 := 3 x2
r2 := 6 x
r3 := proc(y)
local a;
a := irem(y, 2) ; if a = 0 then “Even” else “Odd” end if
end proc
If you prefer to display both the input assignment statements and
their results, you must set the interface variable echo to 2 or higher.
For more information, refer to ?interface.16
15
The read statement is particulary useful for reading long procedure definitions. If
you must enter a long procedure that requires much formatting and indentation, it is
easier to enter it in a text editor that has a tabulation feature, and then read it into
Maple.
16
Because the Maple language contains enhancements with each new release, a con-
version utility that translates Maple language files from previous releases is shipped with
each new version of Maple that requires it. For more information, refer to ?updtsrc.
274 • Chapter 7: Input and Output
> interface(echo=2);
> read "my_file";
> r0 := x^3;
r0 := x3
> r1 := 3*x^3;
r1 := 3 x2
> r2 := 6*x;
r2 := 6 x
r3 := proc(y)
local a;
a := irem(y, 2) ; if a = 0 then “Even” else “Odd” end if
end proc
readline( filename );
1 -5.2
2 6.0
3 7.8
“1 -5.2”
The readline statement opens file mydata.txt for reading, and reads
the first line of the file. The readline statement returns the data as a
string. Numerical data is not very useful to Maple in the form of a string.
Thus, if you want to use this data for further calculations, use the string
formatting command sscanf to convert the string to a list of values.
> sscanf(%, "%d%f");
[1, −5.2]
17
If the file was not opened for reading when the readline command is entered,
Maple opens it. Once readline returns 0 to indicate that the end of the file has been
reached, the file is automatically closed.
18
To determine the current working directory, use the currentdir function.
276 • Chapter 7: Input and Output
The arguments to the sscanf command are very similar to the printf
command. Here, d indicates a decimal integer and f indicates a floating-
point value.19
To read the remaining lines in the file, continue to enter readline
statements.
> readline("mydata.txt");
“2 6.0”
> readline("mydata.txt");
“3 7.8”
> readline("mydata.txt");
The value 0 is returned because readline reached the end of the file.
You can automate the process of reading this data by using the following
procedure.
> readfile := proc(s::string) local line;
> do
> line:=readline(s);
> if line = 0 then
> break
> end if;
> print(line);
> end do;
> end proc:
19
For more information about sscanf, refer to chapter 3 of the Maple Advanced
Programming Guide or ?sscanf.
7.2 Standard Disk I/O • 277
> readfile("mydata.txt");
“1 -5.2”
“2 6.0”
“3 7.8”
0
Since readline returns lines read from a file in the form of a string,
it is more useful for reading textual data. If a file contains numerical
data formatted into columns, it is more appropriate to use the readdata
command.
If only one column of data is read, the output is a list of the data.
If more than one column is read, the output is a list of lists of data
corresponding to the rows of data in filename.
> readdata("mydata.txt", 2);
Once you have read the data from a file, use Maple commands to
process the data. For example, plot the data points from file mydata.txt.
> points := %;
8
6
4
2
01 1.5 2 2.5 3
–2
–4
1 .500 .333
2 1 .667
3 1.50 1
C, Fortran, JavaTM , MATLAB, and Visual Basic Code Generation
Maple also provides commands to translate Maple expressions to other
programming languages: C, Fortran, JavaTM , MATLAB r
, and Visual
Basic
r
. These commands are available in the Maple codegen and
CodeGeneration packages. For more information, refer to chapter 6 of the
Maple Advanced Programming Guide, ?codegen, or ?CodeGeneration.
20
For more information about writedata, refer to ?writedata.
280 • Chapter 7: Input and Output
7.3 Troubleshooting
This section provides you with 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.21
Bad Input: a ++ b;
a+b
a+b
21
For more information about I/O errors in Maple, refer to ?IO_errors.
22
For more information about the readstat statement, refer to ?readstat.
7.4 Exercises • 281
7.4 Exercises
1. Write a loop (with a single statement in its body) that prints strings
listing the cubes of the integers 1 to 10.
Save the file. In a Maple session, open the file by using the read
statement. Observe how Maple reacts to invalid statements.
3. Create a data file in a text editor that contains the following informa-
tion.
1 2 3
4 5 6
Save the file. Read this file into a Maple session, convert the data to a
list, and reverse its order. Write the reversed data in the same format
to a different file.
282 • Chapter 7: Input and Output
7.5 Conclusion
The techniques in this chapter illustrated some of the basic I/O facilities
that are available in Maple—how to incorporate interactive input in your
procedures, and how to import and export data from Maple. In addition
to the commands discussed in this chapter, Maple has many low-level
I/O routines, which are useful for reading formatted and non-uniform
data from text files.
In Maple, there are packages that generate code in the C, Fortran,
Java, MATLAB, and Visual Basic programming languages. For more in-
formation, refer to chapter 6 of the Maple Advanced Programming
Guide. The Sockets and Worksheet packages also contain important
I/O routines.
8 Debugging and Efficiency
In This Chapter
• Using the Maple debugger
283
284 • Chapter 8: Debugging and Efficiency
• a main text box that displays a procedure name and the debugger
output
sieve := proc(n::integer)
local i, k, flags, count, twicei;
1 count := 0;
2 for i from 2 to n do
3 flags[i] := true
end do;
4 for i from 2 to n do
5 if flags[i] then
6 twicei := 2*i;
7 for k from twicei by i to n do
8 flags[k] = false
end do;
9 count := count+l
end if
end do;
10 count
end proc
Note: The numbers preceeding each line differ from line numbers that
may display in a text editor. For example, keywords that end a statement
(such as end do and end if) are not considered separate commands and
are therefore not numbered.
[sieve]
sieve:
1* count := 0;
1
If a procedure has a remember table, you may have to execute a restart command
before issuing a second or subsequent stopat command. For more information about
remember tables, see page 210 or refer to ?remember.
8.1 A Tutorial Example • 287
DBG > n
10
sieve:
1* count := 0;
0
sieve:
2 for i from 2 to n do
...
end do;
288 • Chapter 8: Debugging and Efficiency
The 0 in the first line of the output represents the result of the exe-
cuted statement—that is, the result of count := 0. A “*” does not appear
next to the statement number because there is no breakpoint set immedi-
ately before statement 2. The debugger does not show the body of the for
loop, which itself consists of statements with their own statement num-
bers, unless execution actually stops within its body. Maple represents
the body of compound statements by ellipses (...).
Executing the next command again results in the following output.
DBG > next
true
sieve:
4 for i from 2 to n do
...
end do;
true
sieve:
5 if flags[i] then
...
end if
true
sieve:
6 twicei := 2*i;
8.1 A Tutorial Example • 289
If you use the step debugger command when the next statement to
execute is not a deeper structured statement or procedure call, it has the
same effect as the next debugger command.
DBG > step
4
sieve:
7 for k from twicei by i to n do
...
end do;
At any time during the debugging process, you can use the showstat
debugger command to display the current status of the debugging process.
DBG > showstat
sieve := proc(n::integer)
local i, k, flags, count, twicei;
1* count := 0;
2 for i from 2 to n do
3 flags[i] := true
end do;
4 for i from 2 to n do
5 if flags[i] then
6 twicei := 2*i;
7 ! for k from twicei by i to n do
8 flags[k] = false
end do;
9 count := count+l
end if
end do;
10 count
end proc
Maple displays a debugger prompt to indicate that you are still work-
ing inside the Maple debugger. The asterisk (*) marks the unconditional
breakpoint. An exclamation point (!) that follows a statement number
(see line 7) indicates the statement at which the procedure is stopped.
290 • Chapter 8: Debugging and Efficiency
4
sieve:
8 flags[k] = false
sieve := proc(n::integer)
local i, k, flags, count, twicei;
...
3 flags[i] := true
end do;
4 for i from 2 to n do
5 if flags[i] then
6 twicei := 2*i;
7 for k from twicei by i to n do
8 ! flags[k] = false
end do;
9 count := count+l
end if
end do;
...
end proc
8.1 A Tutorial Example • 291
true = false
sieve:
9 count := count+l
l
sieve:
5 if flags[i] then
...
end if
9l
You can now see that the procedure does not give the expected output.
Although you may find the reason obvious from the previous debugger
command examples, in most cases it is not easy to find procedure er-
rors. Therefore, continue to use the debugger. First, use the unstopat
command to remove the breakpoint from sieve.
> unstopat(sieve);
[]
292 • Chapter 8: Debugging and Efficiency
[[sieve, count ]]
count := 0
sieve:
2 for i from 2 to n do
...
end do;
Execution stops because Maple has modified count, and the debugger
displays the assignment statement count := 0. As in the case of break-
points, the debugger then displays the name of the procedure and the next
statement to be executed in the procedure. Note that execution stops af-
ter Maple has assigned a value to count.
This first assignment to count is correct. Use the cont debugger com-
mand to continue execution of the procedure.
DBG > cont
count := l
sieve:
5 if flags[i] then
...
end if
8.1 A Tutorial Example • 293
If you do not look carefully, this also looks correct. Assume that noth-
ing is wrong and continue execution.
DBG > cont
count := 2*l
sieve:
5 if flags[i] then
...
end if
[]
After correcting the source text for sieve, issue a restart command,
read the corrected version of sieve into Maple, and execute the procedure
again.
> sieve(10);
9
294 • Chapter 8: Debugging and Efficiency
This result is still incorrect. There are four primes less than 10, namely
2, 3, 5, and 7. Therefore, invoke the debugger once more, stepping into the
innermost parts of the procedure to investigate. Since you do not want to
start at the beginning of the procedure, set the breakpoint at statement
6.
> stopat(sieve,6);
[sieve]
> sieve(10);
true
sieve:
6* twicei := 2*i;
4
sieve:
7 for k from twicei by i to n do
...
end do;
4
sieve:
8 flags[k] = false
true = false
sieve:
8 flags[k] = false
8.1 A Tutorial Example • 295
The last step reveals the error. The previously computed result should
have been false (from the assignment of flags[k] to the value false),
but instead true = false was returned. An equation was used instead
of an assignment. Therefore, Maple did not set flags[k] to false.
Once again, exit the debugger and correct the source text.
DBG > quit
showstat( procedureName );
In these cases, the statements that are not displayed are represented
by ellipses (...). The procedure name, its parameters, and its local and
global variables are always displayed.
> f := proc(x)
> if x <= 2 then
> print(x);
> end if;
> print(-x)
> end proc:
f := proc(x)
...
2 print(x)
end if;
3 print(-x)
end proc
This condition argument can refer to any global variable, local vari-
able, or parameter of the procedure. These conditional breakpoints are
marked by a question mark (?) if showstat is used to display the proce-
dure.
Since the stopat command sets the breakpoint before the specified
statement, when Maple encounters a breakpoint, execution stops and
Maple engages the debugger before the statement. This means that
you cannot set a breakpoint after the last statement in a statement
sequence—that is, at the end of a loop body, an if statement body,
or a procedure.
If two identical procedures exist, depending on how you created them,
they may share breakpoints. If you entered the procedures individually,
with identical procedure bodies, then they do not share breakpoints. If
you created a procedure by assigning it to the body of another procedure,
then their breakpoints are shared.
> f := proc(x) x^2 end proc:
> g := proc(x) x^2 end proc:
> h := op(g):
> stopat(g);
[g, h]
> showstat();
g := proc(x)
1* x^2
end proc
h := proc(x)
1* x^2
end proc
298 • Chapter 8: Debugging and Efficiency
DEBUG( argument );
> showstat(f);
f := proc(x, y)
local a;
1 a := x^2;
2 DEBUG();
3 a := y^2
end proc
> f(2,3);
2
The showstat command does not mark explicit breakpoints with a “*Ô or a “?Ô.
8.2 Maple Debugger Commands • 299
4
f:
3 a := y^2
> f(2,3);
9
f:
5 print(a)
> f := proc(x)
> x^2;
> DEBUG("This is my breakpoint. The current value of x\
> is:", x);
> x^3
> end proc:
> f(2);
[f, g, h]
f:
3 x^3
f := proc(x)
1 x^2;
2 DEBUG("This is my breakpoint. The current value of x is:",x);
3 ! x^3
end proc
[f, g, h]
> print(f);
stopwhen( globalVariableName );
stopwhen( [procedureName, variableName ] );
The first form specifies that the debugger should be invoked when
the global variable globalVariableName is changed. Maple environment
variables, such as Digits, can also be monitored by using this method.
> stopwhen(Digits);
[Digits ]
The second form invokes the debugger when the (local or global) vari-
able variableName is changed in the procedure procedureName.
When any form of stopwhen is called, Maple returns a list of the
current watchpoints.
Execution stops after Maple assigns a value to the watched vari-
able. The debugger displays an assignment statement instead of the last
computed result (which would otherwise be the right-hand side of the
assignment statement).
stoperror( "errorMessage" );
[]
> stoperror();
1
9
> f(0);
[]
[traperror ]
However, Maple invokes the debugger when the trapped error occurs.
> g(0);
[ ]
[f ]
> f(10);
f:
1* x^2
.1411200081
f:
1* x^2
100
The debugger evaluates any variable names that you use in the ex-
pression in the context of the stopped procedure. Names of parameters or
local variables evaluate to their current values in the procedure. Names of
global variables evaluate to their current values. Environment variables,
8.2 Maple Debugger Commands • 307
> stopat(f,2);
[f ]
> f(3);
f:
2* i^2
1
f:
2* i^2
3
f:
2* i^2
While execution is stopped, you can modify local and global vari-
ables by using the assignment operator (:=). The following example sets
a breakpoint in the loop only when the index variable is equal to 5.
> sumn := proc(n) local i, sum;
> sum := 0;
> for i to n do
> sum := sum + i
> end do;
> end proc:
> showstat(sumn);
sumn := proc(n)
local i, sum;
1 sum := 0;
2 for i to n do
3 sum := sum+i
end do
end proc
> stopat(sumn,3,i=5);
[sumn]
> sumn(10);
10
sumn:
3? sum := sum+i
sumn:
3? sum := sum+i
8.2 Maple Debugger Commands • 309
17
sumn:
3? sum := sum+i
62
where numLevels
sumn := proc(n)
local i, sum;
1 sum := 0;
2 for i to n do
3? sum := sum+i
end do
end proc
10
sumn:
3? sum := sum+i
TopLevel: check(9)
[9]
check: a := sumn(p)
[23]
sumn:
3? sum := sum+i
true
> showstat(fact);
fact := proc(x)
1 if x <= 1 then
2 1
else
3 x*fact(x-1)
end if
end proc
> stopat(fact,2);
[fact ]
> fact(5);
fact:
2* 1
312 • Chapter 8: Debugging and Efficiency
TopLevel: fact(5)
[5]
fact: x*fact(x-1)
[4]
fact: x*fact(x-1)
[3]
fact: x*fact(x-1)
[2]
fact: x*fact(x-1)
[1]
fact:
2* 1
If you are not interested in the entire history of the nested procedure
calls, use the numLevels parameter in the call to where to print a specified
number of levels.
DBG > where 3
fact: x*fact(x-1)
[2]
fact: x*fact(x-1)
[1]
fact:
2* 1
showstop();
Set breakpoints.
> stopat(f):
> stopat(f,2):
> stopat(int);
[f, int ]
Set watchpoints.
> stopwhen(f,y):
> stopwhen(Digits);
Breakpoints in:
f
int
Watched variables:
Digits
y in procedure f
Watched errors:
314 • Chapter 8: Debugging and Efficiency
Except for these rules, the debugger prompt call for each command
is of the same form and takes the same arguments as the corresponding
top-level command call.
Restrictions
At the debugger prompt, the only permissible Maple statements are de-
bugger commands, expressions, and assignments. The debugger does not
permit statements such as if, while, for, read, and save. However, you
can use ‘if‘ to simulate an if statement, and seq to simulate a loop.
The debugger cannot set breakpoints in, or step into, built-in routines,
such as diff and has. These routines are implemented in C and compiled
into the Maple kernel. Debugging information about these routines is
not accessible to Maple. However, if a built-in command calls a library
routine, for example, the diff command calling ‘diff/sin‘, you can use
a breakpoint to stop in the latter.
If a procedure contains two identical statements that are expressions,
the debugger cannot determine with certainty the statement at which
execution stopped. If this situation occurs, you can still use the debugger
8.3 Detecting Errors • 315
and execution can continue. The debugger merely issues a warning that
the displayed statement number may be incorrect.3
Tracing a Procedure
The simplest tools available for error detection in Maple are the printlevel
global variable, and the trace and tracelast commands. These facili-
ties enable you to trace the execution of both user-defined and Maple
library procedures. However, they differ in the type of information that
is returned about a procedure.
The printlevel variable is used to control how much information is
displayed when a program is executed. By assigning a large integer value
to printlevel, you can monitor the execution of statements to selected
levels of nesting within procedures. The default value of printlevel is
1. Larger, positive integer values cause the display of more intermediate
steps in a computation. Negative integer values suppress the display of
information.
The printlevel global variable is set by using the following syntax,
where n is the level to which Maple commands are evaluated.
printlevel := n ;
3
This problem occurs because Maple stores all identical expressions as a single occur-
rence of the expression. The debugger cannot determine at which invocation execution
stopped.
316 • Chapter 8: Debugging and Efficiency
> f(3);
81
2
> printlevel := 5;
printlevel := 5
> f(3);
y := 9
81
2
printlevel := 10
8.3 Detecting Errors • 317
> f(3);
y := 9
z := 81
162
printlevel := 1
trace(arguments );
f, g
> f(3):
> f(3);
y := 9
z := 81
162
81
2
f, g
> f(3);
81
2
tracelast;
• The first line displays which procedure was called and what parameter
was used.
• The second line displays the # symbol, the procedure name with the
line number of the statement that was executed, and the statement
that was executed.
• Finally, if there are any local variables in the procedure, they are
displayed with their corresponding values.
4
You can use debug and undebug as alternate names for trace and untrace.
320 • Chapter 8: Debugging and Efficiency
f := proc(x)
local i, j, k;
i := x ; j = x2 ; seq(k, k = i..j)
end proc
> f(2,3);
> tracelast;
Using Assertions
An assertion is a statement about a procedure that you assert to be
true. You can include assertions in your procedure to guarantee pre- and
post-conditions, and loop invariants during execution by using the ASSERT
command. You can also use assertions to guarantee the value returned by
a procedure or the value of local variables inside a procedure. The ASSERT
command has the following syntax.
5
For more information about garbage collection in Maple, see page 335 or refer to
?gc.
8.3 Detecting Errors • 321
false
false
At any time during the Maple session, you can confirm whether as-
sertion checking is on by entering the following command.
> kernelopts(ASSERT);
true
6
For more information about kernelopts, refer to ?kernelopts.
322 • Chapter 8: Debugging and Efficiency
f := proc(x, y)
local i, j;
i := 0 ;
j := 0 ;
while i 6= x do
ASSERT(0 < i, “invalid index”) ; j := j + y ; i := i + 1
end do;
j
end proc
> f(2,3);
true
f := proc(x)
if x < 0 then WARNING(“the result is complex”) end if ;
sqrt(x)
end proc
> f(-2);
√
2I
> f(-2);
√
2I
Handling Exceptions
An exception is an event that occurs during the execution of a procedure
that disrupts the normal flow of instructions. Many kinds of errors can
cause exceptions, for example, attempting to read from a file that does
not exist. Maple has two mechanisms available when such situations arise:
The msgString parameter is a string that gives the text of the error
message. It can contain numbered parameters of the form %n or %-n,
where n is an integer. These numbered parameters are used as placeholders
for actual values. In the event that the exception is printed as an error
message, the actual values are specified by the msgParams.
For example, the error message "f has a 4th argument, x, which
is missing" is specified by the following error statement.
error "%1 has a %-2 argument, %3, which is missing", f, 4, x
A numbered parameter of the form %n displays the nth msgParam in
line-printed notation (that is, as lprint would display it). A numbered
parameter of the form %-n displays the nth msgParam, assumed to be
an integer, in ordinal form. For example, the %-2 in the error statement
above is displayed as “4th”. The special parameter %0 displays all the
msgParams, separated by a comma and a space.
The error statement evaluates its arguments, and then creates an
exception object which is an expression sequence with the following ele-
ments.
• The name of the procedure in which the exception was raised, or the
constant 0 if the exception was raised at the top-level.
• The msgString.
7
The actual arguments to the error statement are also assigned to lasterror for
compatibility with older versions of Maple. For more information, refer to ?traperror.
8
To view the value of the lastexception variable inside the debugger, use the
showexception debugger command.
8.3 Detecting Errors • 325
In this case, msgText is the text of the error message (which is con-
structed from the msgString and optional msgParams of the error state-
ment), and procName is the procedure in which the error occurred. If
the procedure does not have a name, procName is displayed as unknown.
If the error occurs at the top-level, outside of any procedure, the (in
procName) part of the message is omitted.
The error statement is commonly used when parameter declarations
are not sufficient to check that the actual parameters to a procedure are of
the correct type. The following pairup procedure takes a list L of the form
[x1 , y1 , x2 , y2 , . . . , xn , yn ] as input, and creates from it a list of the form
[[x1 , y1 ], [x2 , y2 ], . . . , [xn , yn ]]. A simple type check cannot determine if list
L has an even number of elements, so you need to check this explicitly by
using an error statement.
> pairup := proc(L::list)
> local i, n;
> n := nops(L);
> if irem(n,2) = 1 then
> error "list must have an even number of "
> "entries, but had %1", n
> end if;
> [seq( [L[2*i-1],L[2*i]], i=1..n/2 )]
> end proc:
try tryStatSeq
catch catchStrings : catchStatSeq
finally finalStatSeq
end try
• Neither the exception object nor the catchStrings are evaluated (the
exception object has already been evaluated by the error statement
that produced it).
that it will not succeed. You would like to abort that method and try
another method. The following code implements this example.
> try
> result := MethodA(f,x)
> catch "FAIL":
> result := MethodB(f,x)
> end try:
MethodA can abort its computation at any time by executing the state-
ment error "FAIL". The catch clause will catch that exception, and pro-
ceed to try MethodB. If any other error occurs during the execution of
MethodA, or if an error occurs during the execution of MethodB, it is not
caught.
Another useful application of the try statement is to ensure that
certain resources are freed when you are done with them, regardless of
whether anything went wrong while you were using them.
Example 2 Use the following code to access the Maple I/O facilities to
read the lines of a file and process them in some way.
> f := fopen("myfile",TEXT,READ):
> try
> line := readline(f);
> while line < 0 do
> ProcessContentsOfLine(line);
> line := readline(f)
> end do
> finally
> fclose(f)
> end try:
If any exception occurs, it is caught with the catch clause that has no
catchString, and the exception object is written into the file. The excep-
tion is re-raised by executing the error statement with no msgString. In
all cases, the file is closed by executing fclose(f) in the finally clause.
Checking Syntax
The Maple maplemint command generates a list of semantic errors for
a specified procedure, if any. The semantic errors for which maplemint
checks include parameter name conflicts, local and global variable name
conflicts, unused variable declarations, and unreachable code. The maplemint
command has the following syntax.
maplemint( procedureName );
> maplemint(f);
9
For more information about efficiency in Maple programming, refer to
?efficiency.
8.4 Creating Efficient Programs • 331
showtime();
02 := ‘+‘(seq(2^i, i=1..100)):
03 := add(2^i, i=1..100):
To turn showtime off, enter the off command. Maple returns to its
normal interactive mode using the standard prompt.
04 := off:
10
For more information about using the global variables 0i at a later time in a Maple
session, refer to ?history.
332 • Chapter 8: Debugging and Efficiency
time();
st := time():
... statements to be timed ...
time() - st;
8.402
Profiling a Procedure
Used in conjunction with the profile command, the showprofile com-
mand is used to display run-time information about a procedure. The
run-time information is displayed in tabular form and it contains the
number of calls to the procedure, the nesting level of each call, the CPU
time used, and the number of bytes used by each call. To turn on profiling,
use the profile command.
profile( procedureName );
showprofile( procedureName );
11
For more information about option remember, see page 210 or refer to ?remember.
8.4 Creating Efficient Programs • 333
fib1 := proc(n)
option remember ;
if n < 2 then n else fib1(n − 1) + fib1(n − 2) end if
end proc
> fib2:=proc(n)
> if n<2 then
> n
> else
> fib2(n-1)+fib2(n-2)
> end if;
> end proc;
fib2 := proc(n)
if n < 2 then n else fib2(n − 1) + fib2(n − 2) end if
end proc
Turn on profiling for both procedures.
> profile(fib1);
> profile(fib2);
55
> fib2(10);
55
unprofile( procedureName );
Garbage Collection
Garbage collection deletes all objects that are no longer in use by the
program and are occupying space in memory. In Maple, garbage collection
also clears the remember tables of procedures that use an option system
or option builtin by removing entries that have no other references to
them.12
The Maple garbage collection function is gc. The gc command has
the following syntax.
gc();
12
For more information about procedure options, see page 206 or refer to ?options.
336 • Chapter 8: Debugging and Efficiency
8.6 Exercises
1. The following procedure tries to compute 1 − x|a| .
> f := proc(a::integer, x::anything)
> if a<0 then
> a := -a
> end if;
> 1-x^a;
> end proc:
13
For information about the KernelOpts Maplet application, which provides a graph-
ical user interface to the kernel options, refer to ?Maplets[Examples][KernelOpts].
14
For more information about kernelopts, refer to ?kernelopts.
8.7 Conclusion • 337
The following procedure computes Tn (x) in a loop for any given integer
n.
> T := proc(n::integer, x) local t1, tn, t;
> t1 := 1; tn := x;
> for i from 2 to n do
> t := expand(2*x*tn - t1);
> t1 := tn; tn := t;
> end do;
> tn;
> end proc:
8.7 Conclusion
This chapter surveyed a variety of Maple commands that are available to
help you find errors in procedures, and those available to analyze the time
and memory consumption involved in running a program. In particular,
the Maple debugger was presented as a tool that you can use to find and
correct errors.
338 • Chapter 8: Debugging and Efficiency
9 Introduction to the
Maplet User Interface
Customization System
In This Chapter
• Uses of Maplet applications
339
340 • Chapter 9: Introduction to the Maplet User Interface Customization System
1
For more information on this Maplet application, refer to
?examples/VectorNormMaplet.
2
For information on using this Maplet application, refer to
?Maplets[Examples][VectorNorm].
342 • Chapter 9: Introduction to the Maplet User Interface Customization System
Queries
The Maplet system can be used to create queries. Users can be prompted
for information, from the basic name and student number query, to ’Is x
positive?’ and arguments to a routine.
Messages
The Maplet system can be used to create various messages, which display
information, a warning, or an error. Additionally, users can be informed
of their progress in a session.
• Elements
• Examples
• Tools
• Display
9.3 Terminology • 343
Elements
Elements are the individual components used to create a Maplet appli-
cation, for example, windows, buttons, and check boxes. A variety of
different elements are used in the Maplets[Examples] subpackage. Each
element has a help page, describing various options.
Examples
Example Maplet applications show how the Maplet system can be used.
The more complicated examples have an associated help page and work-
sheet describing how particular Maplet applications were constructed.
The worksheets guide you from simple to complex Maplet applications.
Tools
Tools are aids for Maple software users developing Maplet applications.
Display
The Display function is used to display (run) a Maplet application.
9.3 Terminology
Maplet Application A Maplet application is a collection of elements,
such as window, layout, dialog, and command elements. A Maplet appli-
cation contains windows and dialogs.
9.4 Elements
Each element belongs to one of seven categories:
• Layout Elements
• Menubar Elements
• Toolbar Elements
• Command Elements
• Dialog Elements
• Other Elements
ComboBox Displays a box in which users can enter a value or select from
a predefined list of strings. An initial value can be specified, otherwise it
defaults to the first element in the list. The predefined list of strings can
be entered either by using Item elements, or simply as a list of strings.
When the combo box is queried for its value, the currently selected string
is returned.
346 • Chapter 9: Introduction to the Maplet User Interface Customization System
3
For more information on the MatrixNorm and VectorNorm Maplet applications,
refer to ?Maplets[Examples][MatrixNorm] and ?Maplets[Examples][VectorNorm].
9.4 Elements • 347
ListBox A list box is similar to a drop-down box, in that the user must
select from a list, but more than one selection can be made, and more
than one entry appears on the screen. The Shift and Control keys are
used to make multiple selections. The return value is a comma-delimited
(separated) string, which can be converted to a list of strings by using the
ListBoxSplit function from the Maplets[Tools] subpackage.
348 • Chapter 9: Introduction to the Maplet User Interface Customization System
MathMLEditor Displays, and allows the user to edit and create math-
ematical expressions. To enter mathematical constructs, use the input
expression templates and keyboard. Subexpressions can be deleted, cut,
or copied to the clipboard as MathML. From the clipboard, you can paste
them into a Maple session.
TextBox A multiple line box for input, output, or labels. The ’editable’
option can be set to true to create input fields and false to create output
fields or labels. Text boxes have pop-up menus, which can be accessed by
right-clicking the field. By default, an editable=true text box has the
entries Cut, Copy, Paste, Delete, and Select All in the pop-up menu.
An editable=false text box has Copy and Select All in the pop-up
menu.
Layout Elements
The layout of a window describes how various elements in a Maplet ap-
plication are positioned. Two different forms of layout are provided by
the elements BoxLayout and GridLayout. Additionally, nested lists can
be used to define box layouts. When writing a Maplet application, text
strings, user prompts, or text fields are defined as expressions in lists. A
Maplet application window definition includes the main list, which con-
tains the lists of text strings, user prompts, and other elements.
The following elements are classified as layout elements:
• BoxCell
• BoxColumn
• BoxLayout
• BoxRow
• GridCell
• GridLayout
• GridRow
For details about each element, see the help pages.
Nested Lists Nested lists (lists of lists) can be used to define box layouts.
In Maple, a list is an ordered sequence of comma-delimited expressions
that is enclosed in square brackets ([ ]).
For example:
> List := [1,5,7];
List := [1, 5, 7]
For example:
> NestedList:= [1, [2,3], [4,[5,6]], 7, 8, [9,10]];
MenuBar Elements
The following elements are classified as menubar elements:
A menu bar can contain any number of menus. Each menu can
contain items, defined by using the MenuItem, CheckBoxMenuItem, and
RadioButtonMenuItem elements, and submenus, defined by nesting Menu
elements. Separators can be used to group the menu into logically distinct
groups separated by horizontal bars.
9.4 Elements • 355
The default pop-up menu contains Copy and Select All. If the box
or field is editable, it also contains the selection items Paste, Delete,
and Clear. Other entries can be appended to the pop-up menu.
ToolBar Elements
A toolbar can contain any number of buttons. The buttons can be grouped
into logically distinct groups by using a separator, which produces a large
space between adjacent buttons. The following elements are classified as
toolbar elements:
Command Elements
A Maplet application can perform actions in response to user actions such
as clicking a button or changing the value in a text field. Each command
element is performed before the next one is started. These are non-visual
elements. The following elements are classified as command elements:
• CloseWindow
• Evaluate
• RunDialog
• RunWindow
• ShutDown
• SetOption
CloseWindow Closes a running window by referencing the window.
Dialog Elements
Dialogs are small windows that provide information, such as alert or warn-
ing messages, and gather input, such as a filename, from users. Users
respond to a dialog by clicking a button. The Maplet application author
can modify only specific features in the layout, for example, the text in
the title bar, in a caption, or on a button. Dialogs are displayed by using
the RunDialog element.
Important: Dialog element values cannot be queried after the dialog
closes. As a Maplet application author, it is important to create a Maplet
application that returns relevant information to the Maple session.
Other Elements
Action Defines an action in a Maplet application. Contains any number
of Action or command elements to be executed.
Font Specifies a font for an element. The fonts available are dependent
on your operating system. If you specify a family that is not recognized by
your system, the Unrecognized Font message dialog displays. To view
the Maplet application using the default font, click OK. To determine
which font families are recognized, click Valid fonts....
Note: A table with a header must be specified in a scroll pane, that is, a
BoxCell or GridCell element with the ’vscroll’=’as_needed’ option.
Otherwise, the header is not displayed. If a table without a header is spec-
ified in a scroll pane, default header values are used: A,...Z, AA,...ZZ...
Note: Each TableRow must have the same number of TableItem ele-
ments. The number of TableItem elements in the TableHeader, if spec-
ified, must equal the number of TableItem elements in each TableRow.
9.5 Example Maplet Applications • 363
Reference Options
Most elements can be given an identifying reference by using the ’reference’
option, or as a short cut, by placing the reference in an index.
• Alert
• Confirm
• GetColor
• GetEquation
• GetExpression
• GetFile
• GetInput
• Message
• Question
• Selection
• SignQuery
Advanced Example Maplet Applications:
• Integration
• KernelOpts
• ShowTable
• LinearAlgebra subpackage.
9.6 Tools
Maplets tools are aids for Maplet application authors. The Maplets[Tools]
subpackage contains routines for manipulating and interacting with
Maplet applications and Maplet application elements.
The package can be accessed by using either the long or short form
of the function name in the command calling sequence. For example, the
short form is with(Maplets[Tools]). For complete details regarding the
command calling sequence, see the Maplets[Tools], overview help page.
The following functions are available in the Tools subpackage:
Note: To run this Maplet application, use the top-level Display func-
tion. For more information, see 9.7 Running a Maplet Application.
4. The Font and Image elements can be defined anywhere. The Maplet
application code, however, is easier to read if these elements are de-
fined first in the Maplet application. These two elements are listed
under the category of Other Elements on page 361.
7. In a procedure, use the use statement rather than the with statement.
If another user runs your code, the with command affects that user’s
environment, while use does not.
9.10 Conclusion
This book described the basic programming concepts in the Maple lan-
guage: the construction of expressions and other statements from tokens,
data structures, flow control, procedures, I/O, debugging, and efficiency.
In this chapter, the Maple Maplets package, which provides the tools
necessary to create graphical user interfaces to Maple, was introduced.
For more information about programming topics, refer to the Maple
online help system and the Maple Advanced Programming Guide.
Index
371
372 • Index
constants defining
complex numbers, 37 Maplet applications, 368
floating-point numbers, 37 procedures, 9
fractions, 37 definition
integers, 37 procedure, 12
constants, 35 description, 226
cont, 305 detecting
control key, 347 errors, 315
converting Digits, 35
data structures, 158 Display, 343, 367
sequences to sets or lists, 158 display
Copyright option, 208, 225 procedure, 12
creating help pages, 227 displaying
customer feedback, 4 library source code, 229
ditto operators, 25, 77
data do loop, 176
exporting, 278 double quotes
importing, 274 ", 7
reading, 271 and strings, 7
saving, 271 DropDownBox, 346
data structures, 89–91, 123–166 Item, 361
and procedures, 239
converting, 158 elif, 167
DEBUG, 298 else, 168
debugger, 284, 296 end proc, 9, 193
breakpoints, 297, 298 entering
clearing watchpoints, 301 input, 6
controlling execution, 305 statements, 6
explicit breakpoints, 298 environment
interactive, 284 worksheet, 6
invoking, 296 equality, 20
numbering statements, 296 testing
removing explicit breakpoints, evalb, 20
300 vs. assignment, 20
tutorial, 284 equations, 20
watchpoints, 301, 302 error statement, 118, 219, 323
debugging error return, 219
procedures, 284, 296 errors
default detecting, 315
pop-up menu, 355 syntax, 19
define_external, 208 trapping, 302, 325
374 • Index
select, 181 ?, 7
selection, 167–172 ", 7
operation, 152 list of, 24
statements, 114 using, 46
selectremove, 182 square brackets, 353
semicolons sscanf, 275
omitting in procedures, 12 stacks, 159
separators, 354 standard worksheet, 1
seq, 77, 183 start, 367
Set, 367 StartEngine, 367
set operators, 88 statements, 7
SetOption, 356 arithmetic, 8
reference options, 363 assignment, 8, 111
Set routine, 356 break, 118, 179
sets, 123 displaying strings, 7
applying functions to, 125 entering, 6, 8
arithmetic, 124 error, 118
manipulating, 124 help, 7
testing equality, 125 if, 167
testing membership, 125 library routines, 9
shift key, 347 Maple commands, 9
showstat, 296, 297 next, 118, 179
showstop, 312 quit, 119
Shutdown, 357 read, 117
significand, 66 repetition, 115
SingularValues, 365 return, 118, 217
Slider, 350 save, 117
software selection, 114
Maple, 5 try..catch, 219
sort use, 119
order, 131 step, 305, 306
special characters stop, 367
>, 6 stopat, 297, 306
*, 8 StopEngine, 367
+, 8 stoperror, 302
-, 8 stopping
/, 8 Maple computation, 16
:, 7 stopwhen, 301
:=, 8, 20 strings, 7, 366
;, 7 ", 7
=, 20 double quotes, 7
Index • 385
entering, 7 top-level
special characters in, 43 Maplet, 361, 367
subset, 26, 88, 89 Maplet function, 342
subsop, 97 trace, 315, 317
subtype trace option, 213
integer, 52 tracelast, 315, 319
sum, 187 tracing
vs add, 186 procedures, 315, 317, 319
syntax traperror, 324
checking procedures, 329 trapping
errors, 19 errors, 325
system troubleshooting, 17, 162
Maple, 5 invalid arguments, 19
system option, 212 missing operator, 18
premature end of input, 17
Table, 350 syntax errors, 19
TableHeader, 362 true, 35
table truth tables, 87
accessing, 139 try, 302, 323, 325
data type, 139 try..catch statement, 219
entries, 139 type, 97
indexing function, 139 ||, 55
op, 139 complex(float), 69
operands, 139 complex(integer), 69
TableHeader, 350, 362 complex(numeric), 68, 69
TableRow, 362 complex(rational), 69
TableItem, 350, 362 concatenation, 55
TableHeader, 362 even, 52
TableRow, 362 extended_numeric, 62, 66
TableRow, 350, 362 float, 65, 66
tables fraction, 64, 66
last name evaluation, 15 indexed, 53
remember, 210 integer, 52, 62–66
TextBox, 346, 351, 352 integer subtypes, 52
TextField, 346, 352 name, 53
thismaplet, 367 negint, 52
ToggleButton, 352 nonnegint, 52
ToolBar, 355 nonposint, 52
Window element, 363 numeric, 65, 68
ToolBarButton, 355 numeric_type, 66
ToolBarSeparator, 355 odd, 52
386 • Index
zip, 182
388 • Index