Maple Programming Guide
Contents
Preface
Audience
Maple User Interfaces
The Standard Interface
Other Maple Interfaces
Programming in the Standard Interface
Document Mode and Worksheet Mode
1-D and 2-D Math Notation
Web Resources
Conventions
Customer Feedback
1 Introduction to Programming in Maple
1.1 In This Chapter
1.2 The Maple Software
The User Interface
The Computation Engine
1.3 Maple Statements
Getting Help
Displaying a Text String
Performing an Arithmetic Operation
Assigning to a Name
Using Maple Library Commands
1.4 Procedures
Defining a Simple Procedure
Entering a Procedure Definition
Adding Comments to a Procedure
Calling a Procedure
Maple Library Commands, Built-In Commands, and User-Defined Procedures
Full Evaluation and Last Name Evaluation
Viewing Procedure Definitions and Maple Library Code
1.5 Interrupting Computations and Clearing the Internal Memory
Interrupting a Maple Computation
Clearing the Maple Internal Memory
1.6 Avoiding Common Problems
Unexpected End of Statement
Missing Operator
Invalid, Wrong Number or Type of Arguments
Unbalanced Parentheses
Assignment Versus Equality
1.7 Exercises
2 Maple Language Elements
2.1 In This Chapter
2.2 Character Set
2.3 Tokens
Reserved Words
Programming-Language Operators
Names
2.4 Natural Integers
2.5 Strings
Length of a String
Substrings
Searching a String
String Concatenation
Mutability of Strings
Special Characters in Strings
Parsing Strings
Converting Expressions to Strings
2.6 Using Special Characters
Token Separators
Blank Spaces, New Lines, Comments, and Continuation
Punctuation Marks
Semicolon (;) and Colon (:)
Right Single Quotes (')
Left Single Quotes (`)
Parentheses
Square Brackets
Square Brackets and Braces
Angle Brackets
Comma
Escape Characters
2.7 Types and Operands
DAGs
Maple Types
Operands and op
2.8 Avoiding Common Problems
Attempting to Assign to a Protected Name
Invalid Left-Hand Assignment
Incorrect Syntax in Parse
White Space Characters within a Token
Incorrect Use of Double and Single Quotes
Avoid Using Maple Keywords as Names
2.9 Exercises
3 Maple Expressions
3.1 In This Chapter
3.2 Introduction
Expressions and Statements
Automatic Simplification and Evaluation
Syntax and Constructors
3.3 Names
Creating Names: Lexical Conventions
Environment Variables
Constants
Protected Names
3.4 Unevaluated Expressions
Protecting Names and Options
Generic Expressions
Pass by Reference
Displaying the Original Command
Unassigning Names
Evaluation and Automatic Simplification
Example: Defining a Procedure That Is Returned Unevaluated
3.5 Numbers
Integers
Fractions
Floats
Complex Numbers
3.6 Indexed Expressions
3.7 Member Selection
3.8 Functions
Calls to Procedures
3.9 Arithmetic Expressions
Arithmetic Operators
Addition and Subtraction
Multiplication and Division
Exponentiation
Rational Expressions
Noncommutative Multiplication
Factorials
Forming Sums and Products
3.10 Boolean and Relational Expressions
Boolean Constants
Boolean Operators
The not Operator
The and Operator
The or Operator
The xor Operator
The implies Operator
Relational Operators
Efficient Boolean Iteration
3.11 Expressions for Data Structures
Sequences
Lists
Sets
Tables
Rectangular Tables
3.12 Set-Theoretic Expressions
Membership
Set Inclusion
Other Binary Operators for Sets
3.13 Other Expressions
Functional Operators
Composition
Neutral Operators
Ranges
The Concatenation Operator
The Double Colon Operator
Series
3.14 Attributes
3.15 Using Expressions
Evaluating and Simplifying Expressions
Example 1
Example 2
Substituting Subexpressions
Structured Types
3.16 Exercises
4 Basic Data Structures
4.1 In This Chapter
4.2 Introduction
4.3 Immutable Data Structures
Creating Lists
Accessing Data Stored in a List
Determining If an Element Is in a List
Getting the Number of Elements in a List
Sorting a List
Applying a Function to the Contents of a List
Creating Sets
Set Arithmetic
Accessing Data Stored in a Set
Determining If an Element Is in a Set
Getting the Number of Elements in a Set
Applying a Function to the Contents of a Set
4.4 Mutable Data Structures
Creating Tables
Accessing Stored Values
Removing an Element
Getting the Number of Elements Stored in a Table
Checking If an Index Is Used
Evaluation Rules for Tables
Extracting Data
Copying Tables
Applying a Function to the Contents of a Table
Arrays
Creating Arrays
Basic Data Access
Sub-Array Access
Automatic Resizing
More Array Indexing
Getting the Number of Elements in an Array
Getting the Bounds of an Array
Copying an Array
Testing If Two Arrays Are Equal
Applying a Function to the Contents of an Array
Better Performance with Numeric Arrays
Deprecated: array
4.5 Other Data Structure Operations
Filtering Data Structure Elements
Converting Data Structures
4.6 Other Data Structures
Records
Create a Record
Record Equality
Packed Records
Stacks
Creating a Stack
Pushing and Popping
More Stack Functions
Queues
Create a Queue
Enqueue and Dequeue
More Queue Functions
4.7 Data Coercion
4.8 Data Structure Performance Comparisons
Indexing
Building a Collection of Data
4.9 Avoiding Common Problems
Passing Sequences into Functions
Incorrect Index Values
Array Indices Do Not Always Start at 1
Do Not Treat Lists and Sets as Mutable
4.10 Exercises
5 Maple Statements
5.1 In This Chapter
5.2 Introduction
5.3 Statement Separators
5.4 Expression Statements
5.5 Assignments
Multiple Assignment
Assignment Expressions
Operator Assignments
Special Semantics of the ,= Assignment Operator
5.6 Flow Control
Sequencing
Branching
Using if Statements in Expressions
The if Command
Loops
While Loops
Until Loops
Counted Loops
Inductive Loops
Iterating over a Data Structure
Using Loops in Expressions
Looping Commands
The map Command
The select, remove, and selectremove Commands
The zip Command
Non-Local Flow Control
The return Statement
The error Statement and Exception Handling
5.7 The use Statement
5.8 Other Statements
The quit Statement
The save Statement
The read Statement
5.9 Exercises
6 Procedures
6.1 Terminology
6.2 Defining and Executing Procedures
6.3 Parameter Declarations
Required Positional Parameters
Optional Ordered Parameters
Expected Ordered Parameters
Keyword Parameters
The End-of-Parameters Marker
Default Value Dependencies
Parameter Modifiers
The seq Modifier
The depends Modifier
The uneval Modifier
The evaln Modifier
The coercion Modifiers
Procedures without Declared Parameters
6.4 Return Type
6.5 The Procedure Body
Description
Options
The arrow and operator Options
The builtin Option
The call_external Option
The hfloat Option
The inline Option
The overload Option
The procname Option
The remember, cache, and system Options
The trace Option
Variables in Procedures
Global Variables
Local Variables
Lexically Scoped Variables
Scoping Rules
Non-Variable Name Bindings
The Statement Sequence
Referring to Parameters within the Procedure Body
Parameters Are Not Variables
Required Parameters
Parameters with the seq Modifier
Parameters with the uneval or evaln Modifiers
Optional and Expected Ordered Parameters
Special Sequences for Referring to Parameters and Arguments
6.6 How Procedures Are Executed
Binding of Arguments to Parameters
Binding of Keyword Arguments
The Special Case of evaln and uneval Modifiers
Binding of Arguments to Positional and Ordered Parameters
Statement Sequence Interpretation
Variable Evaluation Rules within Procedures
Returning Values from a Procedure
Returning Unevaluated
6.7 Using Data Structures with Procedures
Passing Data Structures to Procedures
Returning Data Structures from Procedures
Example: Computing an Average
Example: Binary Search
Example: Plotting the Roots of a Polynomial
6.8 Writing Usable and Maintainable Procedures
Formatting Procedures for Readability
Commenting Your Code
6.9 Other Methods for Creating Procedures
Functional Operators: Mapping Notation
The unapply Function
Anonymous Procedures
6.10 Recursion
6.11 Procedures That Return Procedures
Example: Creating a Newton Iteration
Example: A Shift Operator
6.12 The Procedure Object
The procedure Type
Procedure Operands
6.13 Exercises
7 Numerical Programming in Maple
7.1 In This Chapter
7.2 Numeric Types in Maple
Rationals
Floating-Point Numbers
Hardware Floating-Point Numbers
Extended Numeric Types
Non-numeric Constants
7.3 More about Floating-Point Numbers in Maple
Representation of Floating-Point Numbers in Maple
Precision and Accuracy
Floating-Point Contagion
More on the Floating-Point Model
7.4 Maple Commands for Numerical Computing
The evalf Command
When Not to Use evalf
Numeric Solvers
The evalhf Command
Numerical Linear Algebra
7.5 Writing Efficient Numerical Programs
Writing Flexible Numerical Procedures
Example: Newton Iteration
Example: Jacobi Iteration
8 Programming with Modules
8.1 In This Chapter
8.2 Introduction
Encapsulation
Creating a Custom Maple Package
Creating Objects
Creating Generic Programs
8.3 A Simple Example
8.4 Syntax and Semantics
The Module Definition
The Module Body
Module Parameters
Implicit Parameters
Named Modules
Declarations
Description Strings
Exported Local Variables
Determining the Export Names
Testing for Membership in a Module
Module Options
The package Option
The record Option
Special Exports
The ModuleApply Procedure
The ModuleIterator Procedure
The ModuleLoad Procedure
ModulePrint
ModuleUnload
Implicit Scoping Rules
Lexical Scoping Rules
Module Factory
Modules and Types
8.5 Records
Creating Records
Record Types
Using Records to Represent Quaternions
Object Inheritance
8.6 Modules and use Statements
Operator Rebinding
8.7 Interfaces and Implementations
Generic Programming as a Good Software Engineering Practice
Distinction between Local and Exported Variables
Interfaces
A Package for Manipulating Interfaces
The load Option
9 Object Oriented Programming
9.1 In This Chapter
9.2 Introduction to Object Oriented Programming
Terminology
Benefits of Object Oriented Programming
9.3 Objects in Maple
Creating a New Class of Objects
Creating More Objects
Objects and Types
9.4 Methods
Methods Can Access Object Locals
Method Names Should Be Declared static
Methods Are Passed the Objects They Manipulate
Calling Methods
Objects in Indexed Function Calls
Special Methods
9.5 Overloading Operators
Supported Operators
Implementing Operators
9.6 Overloading Built-in Routines
Overridable Built-in Routines
9.7 Examples
9.8 Avoiding Common Mistakes
Be Aware of NULL
Lexical Scoping Does Not Circumvent local
10 Input and Output
10.1 In This Chapter
10.2 Introduction
10.3 Input and Output in the Worksheet
Interactive Output
Interactive Input
Customization
10.4 Input and Output with Files
Introduction
Working with General Files
The Maple I/O Library
The FileTools Package
Importing and Exporting Numerical Data
ImportMatrix and ExportMatrix
Other Commands
Files Used by Maple
10.5 Reading and Writing Formatted Data
The scanf and printf Commands
Format Strings
Related Commands
10.6 Useful Utilities
The StringTools Package
Conversion Commands
10.7 2-D Math
The Typesetting Package
Additional Tips
10.8 Exercises
11 Writing Packages
11.1 In This Chapter
11.2 What Is a Package
Packages in the Standard Library
Packages Are Modules
Package Exports
Using Packages Interactively
11.3 Writing Maple Packages By Using Modules
A Simple Example
Custom Libraries
11.4 A Larger Example
ModuleLoad
The Preprocessor and Structured Source Files
Subpackages
11.5 Example: A Shapes Package
Source Code Organization
Package Architecture
The Package API
The make Procedure
The area Procedure
The circumference Procedure
Shape Representation
Procedure Dispatching
Dispatching on Submodule Exports
Conditional Dispatching
Table-based Dispatching
Shape-specific Submodules
The point Submodule
The circle Submodule
12 Graphics
12.1 In This Chapter
12.2 Introduction
Plots in Maple
Generating a Plot
12.3 The Plot Library
Generating 2-D and 3-D Plots
Expression and Operator Forms
Parametric Form
Plotting Points, Polygons, and Text
Points
Polygons and Polyhedra
Text on Plots
Combining Plots
Merging Plots
Generating an Array of Plots
Specialty Plots
Other Packages
12.4 Programming with Plots
A 2-D Example
A 3-D Example
12.5 Data Structures
Types of Data Structures
Basic Structures
Object Structures
Option Structures
Creating Plot Structures
Altering Plot Structures
12.6 Customizing Plots
Controlling the Sampling
Number of Points
Adaptive Plotting
Discontinuities
Colors
Specifying a Single Color
Using Multiple Colors
The ColorTools Package
Coloring Surfaces
Images and Backgrounds
Size and View
smartview option
Typesetting
Axes and Gridlines
Coordinate Systems
Setting Options
12.7 Animations
Building an Animation with plots:-display
The plots:-animate command
3-D Animations with the viewpoint Option
Other Animation Commands
Displaying an Animation as an Array of Plots
12.8 Miscellaneous Topics
Efficiency in Plotting
The Floating-Point Environment
Lists and rtables
Interfaces and Devices
12.9 Avoiding Common Problems
Mixing Expression and Operator Forms
Generating Non-numeric Data
13 Programming Interactive Elements
13.1 In This Chapter
13.2 Programming Embedded Components
Adding Embedded Components to a Document
Editing Component Properties
Example: Creating a Random Plot Application
Example: Creating a Tic-Tac-Toe Game
Retrieving and Updating Component Properties
Using the GetProperty Command to Retrieve Properties
Using the SetProperty Command to Update Properties
Using the Do Command to Retrieve and Update Component Properties
Example: Extending the Tic-Tac-Toe Game
13.3 Programmatically Creating an Interface that Contains Embedded Components
Constructing a Portion of a Worksheet
Example: Dynamically Creating a Random Plot Application
Example: Dynamically Creating a Tic-Tac-Toe Application
13.4 Programmatically Creating an Interface using the DocumentTools:-Canvas Package
Example: Text, Math and Plot
Example: Find Prime Numbers
Example: Random Plot
13.5 Programming Maplets
14 Advanced Connectivity
14.1 In This Chapter
Connecting to the Maple Engine
Using External Libraries in Maple
Connecting Maple to Another Program
Code Generation
14.2 MapleNet
Computation on Demand
14.3 OpenMaple
Runtime Environment Prerequisites
Interface Overview
Text Callbacks
Initializing the Maple Engine
Calling API Commands to Compute with Maple
C/C++ Example
C# Example
Java Example
Visual Basic 6 Example
Visual Basic .NET Example
Memory Usage
14.4 The Maple Command-line Interface
Batch Files
Directing Input to a Pipeline
Specifying Start-up Commands
14.5 External Calling: Using Compiled Code in Maple
Calling a Function in a Dynamic-link Library
Create or Obtain a .dll file
Create a Function Specification
Calling the External Function
Specifying Parameter Types for Function Specifications
Scalar Data Formats
Structured Data Formats
External Function Interface
Specifying Parameter Passing Conventions
Generating Wrappers Automatically
Passing Arguments by Reference
External API
System Integrity
14.6 Accessing Data over a Network with TCP/IP Sockets
Socket Server
Socket Client
14.7 Code Generation
Calling CodeGeneration Commands
Notes on Code Translation
Translation Process
Example 1: Translating a Procedure to Java
Example 2: Translating a Procedure to C
Example 3: Translating a Procedure to Fortran
Example 4: Translating an Expression to MATLAB®
Example 5: Translating an Expression to Perl
Example 6: Translating an Expression to Python
Example 7: Translating Commands to R
Example 8: Translating a Procedure to Visual Basic
Example 9: Using the defaulttype and deducetypes Options
Example 10: Using the declare Option
The Intermediate Code
Extending the CodeGeneration Translation Facilities
The Printing Phase
Defining a Custom Translator
Using a Printer Module
Language Translator Definition
Using the Define Command
Creating a Language Definition Module
Using a New Translator
14.8 CAD Connectivity
14.9 Maple Plug-in for Excel
14.10 Connecting MATLAB® and Maple
Accessing the MATLAB® Computation Engine from Maple
Accessing the Maple Computational Engine from MATLAB®
15 Parallel Programming
15.1 In This Chapter
15.2 Introduction
15.3 Introduction to Parallel Programming with Tasks
Parallel Execution
How the Ordering Is Determined
Issues Caused by Multiple Orders
Controlling Parallel Execution
Execution Orders That Do Not Matter
Shared Data in Maple
Sharing Data Safely
Protecting Critical Sections
15.4 Task Programming Model
Tasks
The Task Tree
Starting Tasks
Task Management
Coarse-grained Versus Fine-grained Parallelism
15.5 Examples
The N Queens Problem
15.6 Limitations of Parallel Programming
Library Code
Maple Interpreter
15.7 Avoiding Common Problems
Every Execution Order Will Happen
Lock around All Accesses
Debugging Parallel Code
15.8 Introduction to Grid Programming
Starting a Grid-Based Computation
Communicating between Nodes
Launch
Send
Receive
An Example Using Send and Receive
15.9 Grid Examples
Computing a Mandelbrot Set
15.10 The Grid Computing Toolbox
15.11 Limitations
Cost of Communication
Load Balancing
15.12 Troubleshooting
Deadlocking
libname and Other Engine Variables
Missing Functions
16 Testing, Debugging, and Efficiency
16.1 In This Chapter
16.2 The Maple Debugger: A Tutorial Example
Example
Numbering the Procedure Statements I
Invoking the Debugger I
Setting a Breakpoint
Controlling the Execution of a Procedure during Debugging I
Invoking the Debugger II
Setting a Watchpoint
16.3 Maple Debugger Commands
Numbering the Procedure Statements II
Invoking the Debugger III
Setting Breakpoints
Removing Breakpoints
Setting Explicit Breakpoints
Removing Explicit Breakpoints
Setting Watchpoints
Clearing Watchpoints
Setting Watchpoints on Specified Errors
Clearing Watchpoints on Specified Errors
Controlling the Execution of a Procedure during Debugging II
Changing the State of a Procedure during Debugging
Examining the State of a Procedure during Debugging
Using Top-Level Commands at the Debugger Prompt
Restrictions
16.4 Detecting Errors
Tracing a Procedure
Using Assertions
Handling Exceptions
Raising Exceptions
Checking Syntax
16.5 Creating Efficient Programs
Displaying Time and Memory Statistics
Profiling a Procedure
16.6 Managing Resources
Setting a Time Limit on Computations
Garbage Collection
Other Kernel Options for Managing Resources
16.7 Testing Your Code
Verifying Results with verify
A Simple Test Harness
Writing Good Tests
Test Coverage
16.8 Exercises
Internal Representation
Internal Functions
Evaluators
Algebraic Functions
Algebraic Service Functions
Data Structure Manipulation Functions
General Service Functions
Flow of Control
Internal Representations of Data Types
AND: Logical AND
ASSIGN: Assignment Statement or Expression
BINARY: Binary Object
BREAK: Break Statement
CATENATE: Name Concatenation
COMPLEX: Complex Value
CONTROL: Communications Control Structure
DCOLON: Type Specification or Test
DEBUG: Debug
EQUATION: Equation or Test for Equality
ERROR: Error Statement
EXPSEQ: Expression Sequence
FLOAT: Software Floating-Point Number
FOR: For/While Loop Statement
FOREIGN: Foreign Data
FUNCTION: Function Call
GARBAGE: Garbage
HFLOAT: Hardware Float
IF: If Statement
IMPLIES: Logical IMPLIES
INEQUAT: Not Equal or Test for Inequality
INTNEG: Negative Integer
INTPOS: Positive Integer
LESSEQ: Less Than or Equal
LESSTHAN: Less Than
LEXICAL: Lexically Scoped Variable within an Expression
LIST: List
LOCAL: Local Variable within an Expression
MEMBER: Module Member
MODDEF: Module Definition
MODULE: Module Instance
NAME: Identifier
NEXT: Next Statement
NOT: Logical NOT
OR: Logical OR
PARAM: Procedure Parameter in an Expression
POLY: Multivariate Polynomials with Integer Coefficients
POWER: Power
PROC: Procedure Definition
PROD: Product, Quotient, Power
RANGE: Range
RATIONAL: Rational
READ: Read Statement
RETURN: Return Statement
RTABLE: Rectangular Table
SAVE: Save Statement
SDPOLY: Sparse Distributed Multivariate Polynomial
SERIES: Series
SET: Set
STATSEQ: Statement Sequence
STOP: Quit Statement
STRING: Character String
SUM: Sum, Difference
TABLE: Table
TABLEREF: Table Reference
TRY: Try Statement
UNEVAL: Unevaluated Expression
USE: Use Statement
XOR: Logical Exclusive-Or
ZPPOLY: Polynomials with Integer Coefficients modulo n
Hashing in Maple
Basic Hash Tables
Hash Table
Hash Chain
Dynamic Hash Tables
Cache Hash Tables
The Simplification Table
The Name Table
Remember Tables
Maple Language Arrays and Tables
Maple Language Rectangular Tables
Portability
Index
List of Figures
Figure 1.1: Maple Toolbar
Figure 2.1: Expression Tree
Figure 2.2: Expression DAG
Figure 2.3: Actual Expression DAG
Figure 3.1: expr DAG
Figure 3.2: subsop Example DAGs
Figure 11.1: Organization of Package Source Files
Figure 11.2: Design of Package
Figure 13.1: Code Region for an Embedded Component
Figure 14.1: Maple in Excel
Figure 16.1: The Maple Debugger in the Standard Interface
List of Tables
Table 2.1: Special Characters
Table 2.2: Reserved Keywords
Table 2.3: Binary Operators
Table 2.4: Unary Operators
Table 2.5: Element-wise Operators
Table 2.6: Token Separators
Table 2.7: Subtype
Table 3.1: Initially Known Names
Table 5.1: Operators That Can Be Rebound
Table 6.1: Procedure Operands
Table 7.1: Floating-Point Contagion Rules
Table 11.1: RandomnessTests
Table 14.1: Basic Data Types
Table 14.2: Compound Data Types
Table 14.3: Printer Commands
Table 16.1: sieveTest.mpl
Table 16.2: sieveTest2.mpl
Table 16.3: Modified sieveTest2.mpl
Table appendix1.1: Maple Structures
Download Help Document