100% found this document useful (1 vote)
60 views

Download ebooks file Maple 9 advanced programming guide 1st Edition Monagan all chapters

The document provides information about the 'Maple 9 Advanced Programming Guide' by Monagan, including download links and details about the book's content. It also lists additional programming-related ebooks available for download. The guide is intended for users looking to enhance their programming skills with Maple software.

Uploaded by

hasnatruhelw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
60 views

Download ebooks file Maple 9 advanced programming guide 1st Edition Monagan all chapters

The document provides information about the 'Maple 9 Advanced Programming Guide' by Monagan, including download links and details about the book's content. It also lists additional programming-related ebooks available for download. The guide is intended for users looking to enhance their programming skills with Maple software.

Uploaded by

hasnatruhelw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Visit https://ebookfinal.

com to download the full version and


explore more ebooks

Maple 9 advanced programming guide 1st Edition


Monagan

_____ Click the link below to download _____


https://ebookfinal.com/download/maple-9-advanced-
programming-guide-1st-edition-monagan/

Explore and download more ebooks at ebookfinal.com


Here are some suggested products you might be interested in.
Click the link to download

SAS Certification Prep Guide Advanced Programming for SAS


9 Fourth Edition Sas Institute

https://ebookfinal.com/download/sas-certification-prep-guide-advanced-
programming-for-sas-9-fourth-edition-sas-institute/

SAS Certification Prep Guide Base Programming for SAS 9


Third Edition Sas

https://ebookfinal.com/download/sas-certification-prep-guide-base-
programming-for-sas-9-third-edition-sas/

Advanced 3D Game Programming with DirectX 9 Wordware Game


Developer s Library 600th Edition Peter Walsh

https://ebookfinal.com/download/advanced-3d-game-programming-with-
directx-9-wordware-game-developer-s-library-600th-edition-peter-walsh/

Programming Ruby 1 9 2 0 The Pragmatic Programmers Guide


Fourth Edition Dave Thomas

https://ebookfinal.com/download/programming-ruby-1-9-2-0-the-
pragmatic-programmers-guide-fourth-edition-dave-thomas/
Advanced Graphics Programming Using OpenGL 1st Edition Tom
Mcreynolds

https://ebookfinal.com/download/advanced-graphics-programming-using-
opengl-1st-edition-tom-mcreynolds/

Websphere Studio Application Developer Version 5


Programming Guide Programming Guide 1st Edition Ibm
Redbooks
https://ebookfinal.com/download/websphere-studio-application-
developer-version-5-programming-guide-programming-guide-1st-edition-
ibm-redbooks/

Advanced Programming Using Visual Basic 2008 4th Edition


Julia Case Bradley

https://ebookfinal.com/download/advanced-programming-using-visual-
basic-2008-4th-edition-julia-case-bradley/

Base SAS 9 2 Procedures Guide 1st Edition Sas Publishing

https://ebookfinal.com/download/base-sas-9-2-procedures-guide-1st-
edition-sas-publishing/

Getting Started With Advanced C Upgrade Your Programming


Skills 1st Edition Vaskaran Sarcar

https://ebookfinal.com/download/getting-started-with-advanced-c-
upgrade-your-programming-skills-1st-edition-vaskaran-sarcar/
Maple 9 advanced programming guide 1st Edition
Monagan Digital Instant Download
Author(s): Monagan, Geddes, Heal, Labahn, et al.
ISBN(s): 9781894511445, 1894511441
Edition: 1
File Details: PDF, 2.25 MB
Year: 2003
Language: english
Maple 9
Advanced Programming
Guide
M. B. Monagan K. O. Geddes K. M. Heal
G. Labahn S. M. Vorkoetter J. McCarron
P. DeMarco

­
c Maplesoft, a division of Waterloo Maple Inc. 2003.
ii •

Maple, Maplesoft, Maplet, and OpenMaple are trademarks of Water-


loo Maple Inc.

­
c Maplesoft, a division of Waterloo Maple Inc. 2003. All rights re-
served.

The electronic version (PDF) of this book may be downloaded and


printed for personal use or stored as a copy on a personal machine. The
electronic version (PDF) of this book may not be distributed. Information
in this document is subject to change without notice and does not rep-
resent a commitment on the part of the vendor. The software described
in this document is furnished under a license agreement and may be used
or copied only in accordance with the agreement. It is against the law to
copy the software on any medium as specifically allowed in the agreement.

Windows is a registered trademark of Microsoft Corporation.


Java and all Java based marks are trademarks or registered trade-
marks of Sun Microsystems, Inc. in the United States and other countries.
Maplesoft is independent of Sun Microsystems, Inc.
All other trademarks are the property of their respective owners.
This document was produced using a special version of Maple that
reads and updates LATEX files.

Printed in Canada

ISBN 1-894511-44-1
Contents

Preface 1
Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Worksheet Graphical Interface . . . . . . . . . . . . . . . . . . 2
Manual Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Customer Feedback . . . . . . . . . . . . . . . . . . . . . . . . . 3

1 Procedures, Variables, and Extending Maple 5


Prerequisite Knowledge . . . . . . . . . . . . . . . . . . . 5
In This Chapter . . . . . . . . . . . . . . . . . . . . . . . 5
1.1 Nested Procedures . . . . . . . . . . . . . . . . . . . . . . 5
Scoping Rules . . . . . . . . . . . . . . . . . . . . . . . . . 6
Local Versus Global Variables . . . . . . . . . . . . . . . . 6
The Quick-Sort Algorithm . . . . . . . . . . . . . . . . . . 8
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Creating a Uniform Random Number Generator . . . . . 11
1.2 Procedures That Return Procedures . . . . . . . . . . . . 14
Conveying Values . . . . . . . . . . . . . . . . . . . . . . . 14
Creating a Newton Iteration . . . . . . . . . . . . . . . . . 14
Example 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Example 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
A Shift Operator . . . . . . . . . . . . . . . . . . . . . . . 17
1.3 Local Variables and Invoking Procedures . . . . . . . . . . 19
Example 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Example 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Procedure as a Returned Object . . . . . . . . . . . . . . 22
Example 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Example 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1.4 Interactive Input . . . . . . . . . . . . . . . . . . . . . . . 27

iii
iv • Contents

Reading Strings from the Terminal . . . . . . . . . . . . . 27


Example 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Reading Expressions from the Terminal . . . . . . . . . . 28
Example 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Converting Strings to Expressions . . . . . . . . . . . . . 30
1.5 Extending Maple . . . . . . . . . . . . . . . . . . . . . . . 31
Defining New Types . . . . . . . . . . . . . . . . . . . . . 31
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Neutral Operators . . . . . . . . . . . . . . . . . . . . . . 33
Example 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Extending Commands . . . . . . . . . . . . . . . . . . . . 39
1.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . 42

2 Programming with Modules 43


Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Module Versus Procedure . . . . . . . . . . . . . . . . . . 45
Accessing Module Exports . . . . . . . . . . . . . . . . . . 46
In This Chapter . . . . . . . . . . . . . . . . . . . . . . . 46
2.1 Syntax and Semantics . . . . . . . . . . . . . . . . . . . . 47
The Module Definition . . . . . . . . . . . . . . . . . . . . 47
The Module Body . . . . . . . . . . . . . . . . . . . . . . 48
Module Parameters . . . . . . . . . . . . . . . . . . . . . . 48
Named Modules . . . . . . . . . . . . . . . . . . . . . . . 48
Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Exported Local Variables . . . . . . . . . . . . . . . . . . 52
Module Options . . . . . . . . . . . . . . . . . . . . . . . . 57
Implicit Scoping Rules . . . . . . . . . . . . . . . . . . . . 58
Lexical Scoping Rules . . . . . . . . . . . . . . . . . . . . 58
Modules and Types . . . . . . . . . . . . . . . . . . . . . . 60
Example: A Symbolic Differentiator . . . . . . . . . . . . 61
2.2 Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
2.3 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
What Is a Package . . . . . . . . . . . . . . . . . . . . . . 78
Writing Maple Packages by Using Modules . . . . . . . . 80
The LinkedList Package . . . . . . . . . . . . . . . . . . 80
Code Coverage Profiling Package . . . . . . . . . . . . . . 87
The Shapes Package . . . . . . . . . . . . . . . . . . . . . 94
2.4 The use Statement . . . . . . . . . . . . . . . . . . . . . . 103
Operator Rebinding . . . . . . . . . . . . . . . . . . . . . 106
Contents • v

2.5 Modeling Objects . . . . . . . . . . . . . . . . . . . . . . . 108


Priority Queues . . . . . . . . . . . . . . . . . . . . . . . . 111
An Object-oriented Shapes Package . . . . . . . . . . . . 115
2.6 Interfaces and Implementations . . . . . . . . . . . . . . . 117
Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Generic Graph Algorithms . . . . . . . . . . . . . . . . . . 124
Quotient Fields . . . . . . . . . . . . . . . . . . . . . . . . 129
A Generic Group Implementation . . . . . . . . . . . . . . 138
2.7 Extended Example: A Search Engine . . . . . . . . . . . . 159
Introduction to Searching . . . . . . . . . . . . . . . . . . 159
Inverted Term Occurrence Indexing . . . . . . . . . . . . . 161
The Vector Space Model . . . . . . . . . . . . . . . . . . . 164
Term Weighting . . . . . . . . . . . . . . . . . . . . . . . . 167
Building a Search Engine Package . . . . . . . . . . . . . 168
Latent Semantic Analysis . . . . . . . . . . . . . . . . . . 172
The Search Engine Package . . . . . . . . . . . . . . . . . 173
Using the Package . . . . . . . . . . . . . . . . . . . . . . 180
2.8 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . 184

3 Input and Output 185


In This Chapter . . . . . . . . . . . . . . . . . . . . . . . 185
3.1 A Tutorial Example . . . . . . . . . . . . . . . . . . . . . 186
3.2 File Types and Modes . . . . . . . . . . . . . . . . . . . . 190
Buffered Files versus Unbuffered Files . . . . . . . . . . . 190
Text Files versus Binary Files . . . . . . . . . . . . . . . . 190
Read Mode versus Write Mode . . . . . . . . . . . . . . . 191
The default and terminal Files . . . . . . . . . . . . . . 191
3.3 File Descriptors versus File Names . . . . . . . . . . . . . 192
3.4 File Manipulation Commands . . . . . . . . . . . . . . . . 193
Opening and Closing Files . . . . . . . . . . . . . . . . . . 193
Position Determination and Adjustment . . . . . . . . . . 194
Detecting the End of a File . . . . . . . . . . . . . . . . . 195
Determining File Status . . . . . . . . . . . . . . . . . . . 195
Removing Files . . . . . . . . . . . . . . . . . . . . . . . . 196
3.5 Input Commands . . . . . . . . . . . . . . . . . . . . . . . 197
Reading Text Lines from a File . . . . . . . . . . . . . . . 197
Reading Arbitrary Bytes from a File . . . . . . . . . . . . 197
Formatted Input . . . . . . . . . . . . . . . . . . . . . . . 198
Reading Maple Statements . . . . . . . . . . . . . . . . . 204
Reading Tabular Data . . . . . . . . . . . . . . . . . . . . 204
3.6 Output Commands . . . . . . . . . . . . . . . . . . . . . . 206
vi • Contents

Configuring Output Parameters Using the interface Com-


mand . . . . . . . . . . . . . . . . . . . . . . . . . 206
One-Dimensional Expression Output . . . . . . . . . . . . 206
Two-Dimensional Expression Output . . . . . . . . . . . . 207
Writing Maple Strings to a File . . . . . . . . . . . . . . . 210
Writing Bytes to a File . . . . . . . . . . . . . . . . . . . . 210
Formatted Output . . . . . . . . . . . . . . . . . . . . . . 211
Writing Tabular Data . . . . . . . . . . . . . . . . . . . . 215
Flushing a Buffered File . . . . . . . . . . . . . . . . . . . 216
Redirecting the default Output Stream . . . . . . . . . . 217
3.7 Conversion Commands . . . . . . . . . . . . . . . . . . . . 218
Conversion between Strings and Lists of Integers . . . . . 218
Parsing Maple Expressions and Statements . . . . . . . . 218
Formatted Conversion to and from Strings . . . . . . . . . 220
3.8 Notes to C Programmers . . . . . . . . . . . . . . . . . . . 221
3.9 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . 221

4 Numerical Programming in Maple 223


Floating-Point Calculations . . . . . . . . . . . . . . . . . 223
In This Chapter . . . . . . . . . . . . . . . . . . . . . . . 223
Why Use Numerical Computations . . . . . . . . . . . . . 223
4.1 The Basics of evalf . . . . . . . . . . . . . . . . . . . . . 224
4.2 Hardware Floating-Point Numbers . . . . . . . . . . . . . 227
Newton’s Method . . . . . . . . . . . . . . . . . . . . . . . 230
Computing with Arrays of Numbers . . . . . . . . . . . . 232
4.3 Floating-Point Models in Maple . . . . . . . . . . . . . . . 235
Software Floats . . . . . . . . . . . . . . . . . . . . . . . . 235
Roundoff Error . . . . . . . . . . . . . . . . . . . . . . . . 236
4.4 Extending the evalf Command . . . . . . . . . . . . . . . 238
Defining New Constants . . . . . . . . . . . . . . . . . . . 238
Defining New Functions . . . . . . . . . . . . . . . . . . . 240
4.5 Using the Matlab Package . . . . . . . . . . . . . . . . . . 243
4.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . 244

5 Programming with Maple Graphics 245


Maple Plots . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Creating Plotting Procedures . . . . . . . . . . . . . . . . 245
In This Chapter . . . . . . . . . . . . . . . . . . . . . . . 245
5.1 Basic Plotting Procedures . . . . . . . . . . . . . . . . . . 246
Altering a Plot . . . . . . . . . . . . . . . . . . . . . . . . 248
5.2 Programming with Plotting Library Procedures . . . . . . 249
Contents • vii

Plotting a Loop . . . . . . . . . . . . . . . . . . . . . . . . 249


Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
A Ribbon Plot Procedure . . . . . . . . . . . . . . . . . . 251
5.3 Maple Plot Data Structures . . . . . . . . . . . . . . . . . 254
The PLOT Data Structure . . . . . . . . . . . . . . . . . . 256
Arguments Inside a PLOT Structure . . . . . . . . . . . . . 257
A Sum Plot . . . . . . . . . . . . . . . . . . . . . . . . . . 259
The PLOT3D Data Structure . . . . . . . . . . . . . . . . . 262
Objects Inside a PLOT3D Data Structure . . . . . . . . . . 264
5.4 Programming with Plot Data Structures . . . . . . . . . . 266
Writing Graphic Primitives . . . . . . . . . . . . . . . . . 266
Plotting Gears . . . . . . . . . . . . . . . . . . . . . . . . 268
Polygon Meshes . . . . . . . . . . . . . . . . . . . . . . . . 272
5.5 Programming with the plottools Package . . . . . . . . 273
A Pie Chart . . . . . . . . . . . . . . . . . . . . . . . . . . 275
A Dropshadow Procedure . . . . . . . . . . . . . . . . . . 276
Creating a Tiling . . . . . . . . . . . . . . . . . . . . . . . 278
A Smith Chart . . . . . . . . . . . . . . . . . . . . . . . . 280
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
Modifying Polygon Meshes . . . . . . . . . . . . . . . . . 281
5.6 Vector Field Plots . . . . . . . . . . . . . . . . . . . . . . 286
Drawing a Vector . . . . . . . . . . . . . . . . . . . . . . . 286
Generating a Vector Plot Field . . . . . . . . . . . . . . . 288
5.7 Generating Grids of Points . . . . . . . . . . . . . . . . . 296
5.8 Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
Animation in Static Form . . . . . . . . . . . . . . . . . . 302
Graphical Object as Input . . . . . . . . . . . . . . . . . . 302
Methods for Creating Animations . . . . . . . . . . . . . . 303
Two and Three Dimensions . . . . . . . . . . . . . . . . . 305
Demonstrating Physical Objects in Motion . . . . . . . . 306
5.9 Programming with Color . . . . . . . . . . . . . . . . . . . 308
Generating Color Tables . . . . . . . . . . . . . . . . . . . 309
Using Animation . . . . . . . . . . . . . . . . . . . . . . . 310
Adding Color Information to Plots . . . . . . . . . . . . . 312
Creating A Chess Board Plot . . . . . . . . . . . . . . . . 315
5.10 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . 316

6 Advanced Connectivity 319


In This Chapter . . . . . . . . . . . . . . . . . . . . . . . 319
Code Generation . . . . . . . . . . . . . . . . . . . . . . . 319
External Calling: Using Compiled Code in Maple . . . . . 319
viii • Contents

OpenMaple: Using Maple in Compiled Code . . . . . . . . 319


6.1 Code Generation . . . . . . . . . . . . . . . . . . . . . . . 319
The CodeGeneration Package . . . . . . . . . . . . . . . . 319
Calling CodeGeneration Functions . . . . . . . . . . . . . 320
Translation Process . . . . . . . . . . . . . . . . . . . . . . 321
Extending the CodeGeneration Translation Facilities . . . 324
Defining a Custom Translator . . . . . . . . . . . . . . . . 325
6.2 External Calling: Using Compiled Code in Maple . . . . . 330
Method 1: Calling External Functions . . . . . . . . . . . 332
External Definition . . . . . . . . . . . . . . . . . . . . . . 334
Type Specification . . . . . . . . . . . . . . . . . . . . . . 335
Scalar Data Formats . . . . . . . . . . . . . . . . . . . . . 336
Structured Data Formats . . . . . . . . . . . . . . . . . . 336
Specifying Argument Passing Conventions . . . . . . . . . 338
Method 2: Generating Wrappers . . . . . . . . . . . . . . 338
Additional Types and Options . . . . . . . . . . . . . . . 339
Structured Data Formats . . . . . . . . . . . . . . . . . . 339
Enumerated Types . . . . . . . . . . . . . . . . . . . . . . 339
Procedure Call Formats . . . . . . . . . . . . . . . . . . . 340
Call by Reference . . . . . . . . . . . . . . . . . . . . . . . 340
Array Options . . . . . . . . . . . . . . . . . . . . . . . . 340
Non-passed Arguments . . . . . . . . . . . . . . . . . . . . 341
Argument Checking and Efficiency Considerations . . . . 342
Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . 342
Compiler Options . . . . . . . . . . . . . . . . . . . . . . . 344
Evaluation Rules . . . . . . . . . . . . . . . . . . . . . . . 348
Method 3: Customizing Wrappers . . . . . . . . . . . . . . 350
External Function Entry Point . . . . . . . . . . . . . . . 350
Inspecting Automatically Generated Wrappers . . . . . . 352
External API . . . . . . . . . . . . . . . . . . . . . . . . . 356
System Integrity . . . . . . . . . . . . . . . . . . . . . . . 374
6.3 OpenMaple: Using Maple in Compiled Code . . . . . . . . 374
Interface Overview . . . . . . . . . . . . . . . . . . . . . . 375
Call-back Functions . . . . . . . . . . . . . . . . . . . . . 380
Maple Online Help Database . . . . . . . . . . . . . . . . 386
Technical Issues . . . . . . . . . . . . . . . . . . . . . . . . 389
File Structure . . . . . . . . . . . . . . . . . . . . . . . . . 389
Building the Sample Program . . . . . . . . . . . . . . . . 390
6.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . 392

A Internal Representation and Manipulation 397


Contents • ix

A.1 Internal Organization . . . . . . . . . . . . . . . . . . . . 397


Components . . . . . . . . . . . . . . . . . . . . . . . . . . 398
Internal Functions . . . . . . . . . . . . . . . . . . . . . . 398
Flow of Control . . . . . . . . . . . . . . . . . . . . . . . . 399
A.2 Internal Representations of Data Types . . . . . . . . . . 400
Logical AND . . . . . . . . . . . . . . . . . . . . . . . . . 401
Assignment Statement . . . . . . . . . . . . . . . . . . . . 401
Binary Object . . . . . . . . . . . . . . . . . . . . . . . . . 401
Break Statement . . . . . . . . . . . . . . . . . . . . . . . 401
Name Concatenation . . . . . . . . . . . . . . . . . . . . . 402
Complex Value . . . . . . . . . . . . . . . . . . . . . . . . 402
Communications Control Structure . . . . . . . . . . . . . 402
Type Specification or Test . . . . . . . . . . . . . . . . . . 403
Debug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
Equation or Test for Equality . . . . . . . . . . . . . . . . 403
Error Statement . . . . . . . . . . . . . . . . . . . . . . . 403
Expression Sequence . . . . . . . . . . . . . . . . . . . . . 404
Floating-Point Number . . . . . . . . . . . . . . . . . . . . 404
For/While Loop Statement . . . . . . . . . . . . . . . . . 404
Foreign Data . . . . . . . . . . . . . . . . . . . . . . . . . 405
Function Call . . . . . . . . . . . . . . . . . . . . . . . . . 406
Garbage . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
Hardware Float . . . . . . . . . . . . . . . . . . . . . . . . 406
If Statement . . . . . . . . . . . . . . . . . . . . . . . . . . 407
Logical IMPLIES . . . . . . . . . . . . . . . . . . . . . . . 407
Not Equal or Test for Inequality . . . . . . . . . . . . . . 407
Negative Integer . . . . . . . . . . . . . . . . . . . . . . . 407
Positive Integer . . . . . . . . . . . . . . . . . . . . . . . . 408
Less Than or Equal . . . . . . . . . . . . . . . . . . . . . . 409
Less Than . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
Lexically Scoped Variable within an Expression . . . . . . 409
List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
Local Variable within an Expression . . . . . . . . . . . . 410
Member . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
Module Definition . . . . . . . . . . . . . . . . . . . . . . 410
Module Instance . . . . . . . . . . . . . . . . . . . . . . . 412
Identifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
Next Statement . . . . . . . . . . . . . . . . . . . . . . . . 413
Logical NOT . . . . . . . . . . . . . . . . . . . . . . . . . 413
Logical OR . . . . . . . . . . . . . . . . . . . . . . . . . . 413
Procedure Parameter within an Expression . . . . . . . . 413
x • Contents

Power . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
Procedure Definition . . . . . . . . . . . . . . . . . . . . . 414
Product, Quotient, Power . . . . . . . . . . . . . . . . . . 416
Range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
Rational . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
Read Statement . . . . . . . . . . . . . . . . . . . . . . . . 417
Return Statement . . . . . . . . . . . . . . . . . . . . . . 417
Rectangular Table . . . . . . . . . . . . . . . . . . . . . . 417
Save Statement . . . . . . . . . . . . . . . . . . . . . . . . 419
Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
Statement Sequence . . . . . . . . . . . . . . . . . . . . . 420
Stop Maple . . . . . . . . . . . . . . . . . . . . . . . . . . 420
String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
Sum, Difference . . . . . . . . . . . . . . . . . . . . . . . . 421
Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
Table Reference . . . . . . . . . . . . . . . . . . . . . . . . 421
Try Statement . . . . . . . . . . . . . . . . . . . . . . . . 422
Unevaluated Expression . . . . . . . . . . . . . . . . . . . 422
Use Statement . . . . . . . . . . . . . . . . . . . . . . . . 422
Logical XOR . . . . . . . . . . . . . . . . . . . . . . . . . 423
Polynomials with Integer Coefficients modulo n . . . . . . 423
A.3 The Use of Hashing in Maple . . . . . . . . . . . . . . . . 424
Basic Hash Tables . . . . . . . . . . . . . . . . . . . . . . 424
Dynamic Hash Tables . . . . . . . . . . . . . . . . . . . . 425
The Simplification Table . . . . . . . . . . . . . . . . . . . 426
The Name Table . . . . . . . . . . . . . . . . . . . . . . . 427
Remember Tables . . . . . . . . . . . . . . . . . . . . . . . 427
Maple Language Arrays and Tables . . . . . . . . . . . . . 428
Maple Language Rectangular Tables . . . . . . . . . . . . 429
A.4 Portability . . . . . . . . . . . . . . . . . . . . . . . . . . . 429

Index 431
Preface

This manual describes advanced MapleTM programming concepts, includ-


ing:

• Variable scope, procedures, modules, and packages

• Advanced input and output

• Numerical programming

• Programming with Maple plots

• Connectivity: translating Maple code to other programming lan-


guages, calling external libraries from Maple, and calling Maple code
from external libraries

• Internal representation and manipulation

Audience
This manual provides information for experienced Maple programmers.
You should be familiar with the following.

• Maple Online Help Introduction

• Example worksheets

• How to use Maple interactively

• The Introductory Programming Guide

1
2 • Preface

Worksheet Graphical Interface


You can access the power of the Maple computation engine through a vari-
ety of user interfaces: the standard worksheet, the command-line1 version,
the classic worksheet (not available on Macintosh­ r
), and custom-built
TM
Maplet applications. The full Maple system is available through all of
these interfaces. In this manual, any references to the graphical Maple
interface refer to the standard worksheet interface. For more information
on the various interface options, refer to the ?versions help page.

Manual Set
There are three other manuals available for Maple users, the Maple Get-
ting Started Guide, the Maple Learning Guide, and the Maple Intro-
ductory Programming Guide.2

• The Maple Getting Started Guide contains an introduction to the


graphical user interface and a tutorial that outlines using Maple to
solve mathematical problems and create technical documents. It also
includes information for new users about the online help system, New
User’s Tour, example worksheets, and the Maplesoft Web site.

• The Maple Learning Guide explains how Maple and the Maple lan-
guage work. It describes the most important commands and uses them
to solve technical problems. User hints for Maplet applications are also
described in this guide.

• The Maple Introductory Programming Guide introduces the basic


Maple programming concepts, such as expressions, data structures,
looping and decision mechanisms, procedures, input and output, de-
bugging, and the Maplet User Interface Customization System.

The Maple software also has an online help system. The Maple help sys-
tem allows you to search in many ways and is always available. There are
also examples that you can copy, paste, and execute immediately.

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.
2
The Student Edition does not include the Maple Introductory Programming Guide
and the Maple Advanced Programming Guide. These programming guides can be pur-
chased from school and specialty bookstores or directly from Maplesoft.
Conventions • 3

Conventions
This manual uses the following typographical conventions.

• courier font - Maple command, package name, and option name

• bold roman font - dialog, menu, and text field

• italics - new or important concept, option name in a list, and manual


titles

• Note - additional information relevant to the section

• Important - information that must be read and followed

Customer Feedback
Maplesoft welcomes your feedback. For suggestions and comments related
to this and other manuals, email [email protected].
4 • Preface
1 Procedures, Variables,
and Extending Maple

Prerequisite Knowledge
Before reading this chapter, you must have an understanding of Maple
evaluation rules for variables and parameters as described in chapter 6 of
the Introductory Programming Guide.

In This Chapter
Nested Procedures You can define a Maple procedure within another
Maple procedure.

Procedures That Return Procedures You can create procedures that


return procedures by using Maple evaluation rules.

Local Variables Local variables can exist after the procedure which cre-
ated them has exited. This feature allows a procedure to return a proce-
dure. The new procedure requires a unique place to store information.

Interactive Input You can write interactive procedures, querying the


user for missing information or creating an interactive tutorial or a test.

Extending Maple The Maple software includes useful mechanisms for


extending Maple functionality, which reduce the need to write special-
purpose procedures. Several Maple commands can be extended.

1.1 Nested Procedures


You can define a Maple procedure inside another Maple procedure. Some
Maple commands are very useful inside a procedure. In the worksheet

5
6 • Chapter 1: Procedures, Variables, and Extending Maple

environment, the map command is used to apply an operation to the


elements of a structure. For example, you can divide each element of a
list by a number, such as 8.
> lst := [8, 4, 2, 16]:
> map( x->x/8, lst);

1 1
[1, , , 2]
2 4

Consider a variation on the map command, which appears in the fol-


lowing procedure.

Example This new procedure divides each element of a list by the first
element of that list.
> nest := proc(x::list)
> local v;
> v := x[1];
> map( y -> y/v, x );
> end proc:
> nest(lst);

1 1
[1, , , 2]
2 4

The procedure nest contains a second procedure, map, which in this


case is the Maple command map. Maple applies its lexical scoping rules,
which declare the v within the call to map as the same v as in the outer
procedure, nest.

Scoping Rules
This section explains Maple scoping rules. You will learn how Maple de-
termines which variables are local to a procedure and which are global.
You must have a basic understanding of Maple evaluation rules for pa-
rameters, and for local and global variables. For more information, refer
to chapter 6 of the Introductory Programming Guide.

Local Versus Global Variables


In general, when writing a procedure, you should explicitly declare which
variables are global and which are local. Declaring the scope of the vari-
ables makes your procedure easier to read and debug. However, sometimes
declaring the variables is not the best method. In the previous nest pro-
cedure, the variable in the map command is defined by the surrounding
1.1 Nested Procedures • 7

procedure. What happens if you define this variable, v, as local to the


invocation of the procedure within map?
> nest2 := proc(x::list)
> local v;
> v := x[1];
> map( proc(y) local v; y/v; end, x );
> end proc:
> nest2(lst);

8 4 2 16
[ , , , ]
v v v v

The nest2 procedure produces different results. When the variables


are declared in the inner procedure, the proper values from the enclosing
procedure are not used. Either a variable is local to a procedure and
certain procedures that are completely within it, or it is global to the
entire Maple session.

Rule Maple determines whether a variable is local or global, from the


inside procedure to the outside procedure. The name of the variable is
searched for among:

1. Parameters of the inner procedure

2. Local declarations and global declarations of the inner procedure

3. Parameters of the outside procedure

4. Local and global declarations of the outside procedure

5. Implicitly declared local variables of any surrounding procedure(s)

If found, that specifies the binding of the variable.

If, using the above rule, Maple cannot determine whether a variable
is global or local, the following default decisions are made.

• If a variable appears on the left side of an explicit assignment or as


the controlling variable of a for loop, Maple regards the variable as
local.

• Otherwise, Maple regards the variable as global to the whole session.


In particular, Maple assumes by default that the variables you pass as
arguments to other procedures, which may set their values, are global.
8 • Chapter 1: Procedures, Variables, and Extending Maple

The Quick-Sort Algorithm


Sorting a few numbers is quick using any method, but sorting large
amounts of data can be very time consuming; thus, finding efficient meth-
ods is important.
The following quick-sort algorithm is a classic algorithm. The key to
understanding this algorithm is to understand the operation of partition-
ing. This involves choosing any one number from the array that you are
about to sort. Then, you reposition the numbers in the array that are less
than the number that you chose to one end of the array and reposition
numbers that are greater to the other end. Lastly, you insert the chosen
number between these two groups.
At the end of the partitioning, you have not yet entirely sorted the
array, because the numbers less than or greater than the one you chose
may still be in their original order. This procedure divides the array into
two smaller arrays which are easier to sort than the original larger one.
The partitioning operation has thus made the work of sorting much eas-
ier. You can bring the array one step closer in the sorting process by
partitioning each of the two smaller arrays. This operation produces four
smaller arrays. You sort the entire array by repeatedly partitioning the
smaller arrays.

Example
The partition procedure uses an array to store the list because you can
change the elements of an array directly. Thus, you can sort the array in
place and not waste any space generating extra copies.
The quicksort procedure is easier to understand if you look at the
procedure partition in isolation first. This procedure accepts an array
of numbers and two integers. The two integers are element numbers of the
array, indicating the portion of the array to partition. While you could
possibly choose any of the numbers in the array to partition around, this
procedure chooses the last element of the section of the array for that
purpose, namely A[n]. The intentional omission of global and local
statements shows which variables Maple recognizes as local and which
are global by default. It is recommended, however, that you not make
this omission in your procedures.
> partition := proc(A::array(1, numeric),
> m::posint, n::posint)
> i := m;
> j := n;
> x := A[j];
> while i<j do
> if A[i]>x then
1.1 Nested Procedures • 9

> A[j] := A[i];


> j := j-1;
> A[i] := A[j];
> else
> i := i+1;
> end if;
> end do;
> A[j] := x;
> eval(A);
> end proc:
Warning, ‘i‘ is implicitly declared local to procedure
‘partition‘
Warning, ‘j‘ is implicitly declared local to procedure
‘partition‘
Warning, ‘x‘ is implicitly declared local to procedure
‘partition‘

Maple declares i, j, and x local because the partition procedure con-


tains explicit assignments to those variables. The partition procedure
also assigns explicitly to A, but A is a parameter, not a local variable.
Because you do not assign to the name eval, Maple makes it the global
name which refers to the eval command.
After partitioning the array a in the following, all the elements less
than 3 precede 3 but they are in no particular order; similarly, the elements
larger than 3 come after 3.
> a := array( [2,4,1,5,3] );

a := [2, 4, 1, 5, 3]

> partition( a, 1, 5);

[2, 1, 3, 5, 4]

The partition procedure modifies its first argument, changing a.


> eval(a);

[2, 1, 3, 5, 4]

The final step in assembling the quicksort procedure is to insert


the partition procedure within an outer procedure. The outer proce-
dure first defines the partition subprocedure, then partitions the array.
In general, avoid inserting one procedure in another. However, you will
10 • Chapter 1: Procedures, Variables, and Extending Maple

encounter situations in following sections of this chapter in which it is nec-


essary to nest procedures. Since the next step is to partition each of the
two subarrays by calling quicksort recursively, partition must return
the location of the element which divides the partition.

Example This example illustrates the role of nested procedures. The


outer procedure, quicksort, contains the inner procedure, partition.
> quicksort := proc(A::array(1, numeric),
> m::integer, n::integer)
> local partition, p;
>
> partition := proc(m,n)
> i := m;
> j := n;
> x := A[j];
> while i<j do
> if A[i]>x then
> A[j] := A[i];
> j := j-1;
> A[i] := A[j];
> else
> i := i+1;
> end if;
> end do;
> A[j] := x;
> p := j;
> end proc:
>
> if m<n then # if m>=n there is nothing to do
> p:=partition(m, n);
> quicksort(A, m, p-1);
> quicksort(A, p+1, n);
> end if;
>
> eval(A);
> end proc:

Warning, ‘i‘ is implicitly declared local to procedure


‘partition‘
Warning, ‘j‘ is implicitly declared local to procedure
‘partition‘
Warning, ‘x‘ is implicitly declared local to procedure
‘partition‘

> a := array( [2,4,1,5,3] );

a := [2, 4, 1, 5, 3]
1.1 Nested Procedures • 11

> quicksort( a, 1, 5);

[1, 2, 3, 4, 5]

> eval(a);

[1, 2, 3, 4, 5]

Maple determines that the A and p variables in the partition sub-


procedure are defined by the parameter and local variable (respectively)
from the outer quicksort procedure and everything works as planned.
The variable A can be passed as a parameter to the partition subproce-
dure (as in the stand-alone partition procedure). However, A does not
need to be passed because, by using Maple scoping rules, it is available
to the inner procedure.

Creating a Uniform Random Number Generator


If you want to use Maple to simulate physical experiments, you likely
need a random number generator. The uniform distribution is particu-
larly simple: any real number in a given range is equally likely. Thus, a
uniform random number generator is a procedure that returns a ran-
dom floating-point number within a certain range. This section develops
the procedure, uniform, which creates uniform random number genera-
tors.
The rand command generates a procedure which returns random in-
tegers. For example, rand(4..7) generates a procedure that returns ran-
dom integers between 4 and 7, inclusive.
> f := rand(4..7):
> seq( f(), i=1..20 );

5, 6, 5, 7, 4, 6, 5, 4, 5, 5, 7, 7, 5, 4, 6, 5, 4, 5, 7, 5

The uniform procedure is similar to rand but returns floating-point


numbers rather than integers. You can use rand to generate random
floating-point numbers between 4 and 7 by multiplying and dividing by
10^Digits.
> f := rand( 4*10^Digits..7*10^Digits ) / 10^Digits:
> f();
12 • Chapter 1: Procedures, Variables, and Extending Maple
12210706011
2000000000

The procedure f returns fractions rather than floating-point numbers


so you must compose it with evalf; that is, use evalf(f()). Alterna-
tively, you can perform this operation by using the Maple composition
operator, @.
> (evalf @ f)();

6.648630719

The following uniform procedure uses evalf to evaluate the constants


in the range specification, r, to floating-point numbers, the map command
to multiply both endpoints of the range by 10^Digits, and round to
round the results to integers.
> uniform := proc( r::constant..constant )
> local intrange, f;
> intrange := map( x -> round(x*10^Digits), evalf(r) );
> f := rand( intrange );
> (evalf @ eval(f)) / 10^Digits;
> end proc:

You can now generate random floating-point numbers between 4


and 7.
> U := uniform(4..7):
> seq( U(), i=1..20 );

4.559076346, 4.939267370, 5.542851096, 4.260060897,


4.976009937, 5.598293374, 4.547350944,
5.647078832, 5.133877918, 5.249590037,
4.120953928, 6.836344299, 5.374608653,
4.586266491, 5.481365622, 5.384244382,
5.190575456, 5.207535837, 5.553710879,
4.163815544
The uniform procedure has a serious flaw: uniform uses the current
value of Digits to construct intrange; thus, U depends on the value of
Digits when uniform creates it. On the other hand, the evalf command
within U uses the value of Digits that is current when you invoke U. These
two values are not always identical.
1.1 Nested Procedures • 13

> U := uniform( cos(2)..sin(1) ):


> Digits := 15:
> seq( U(), i=1..8 );

0.828316845400000, −0.328875163100000,
0.790988967100000, 0.624953401700000,
0.362773633800000, 0.679519822000000,
−0.0465278542000000, −0.291055180800000
The proper design choice here is that U should depend only on the
value of Digits when you invoke U. The following version of uniform
accomplishes this by placing the entire computation inside the procedure
that uniform returns.
> uniform := proc( r::constant..constant )
>
> proc()
> local intrange, f;
> intrange := map( x -> round(x*10^Digits),
> evalf(r) );
> f := rand( intrange );
> evalf( f()/10^Digits );
> end proc;
> end proc:

The r within the inner proc is not declared as local or global, so it


becomes the same r as the parameter to the outer proc.
The procedure that uniform generates is now independent of the value
of Digits at the time you invoke uniform.
> U := uniform( cos(2)..sin(1) ):
> Digits := 15:
> seq( U(), i=1..8 );

0.476383408581006, 0.554836962987261,
0.147655743361511, 0.273247304736175,
0.148172828708797, −0.258115633420094,
0.558246581434993, 0.518084711267009
Note: The interface variable displayprecision controls the number of
decimal places to be displayed. The default value is −1, representing full
precision as determined by the Digits environment variable. This sim-
plifies display without introducing round-off error. For more information,
refer to ?interface.
14 • Chapter 1: Procedures, Variables, and Extending Maple

Summary This section introduced:

• Rules Maple uses to distinguish global and local variables

• Principal implications of these rules

• Tools available for writing nested procedures

1.2 Procedures That Return Procedures


Some of the standard Maple commands return procedures. For example,
rand returns a procedure which in turn produces randomly chosen inte-
gers from a specified range. The dsolve function with the type=numeric
option returns a procedure which supplies a numeric estimate of the so-
lution to a differential equation.
You can write procedures that return procedures. This section dis-
cusses how values are passed from the outer procedure to the inner pro-
cedure.

Conveying Values
The following example demonstrates how locating the roots of a function
by using Newton’s method can be implemented in a procedure.

Creating a Newton Iteration


Use Newton’s method to find the roots of a function.

1. Choose a point on the x-axis that you think might be close to a root.

2. Find the slope of the curve at the point you chose.

3. Draw the tangent to the curve at that point and observe where the
tangent intersects the x-axis. For most functions, this second point is
closer to the real root than your initial guess. To find the root, use
the new point as a new guess and keep drawing tangents and finding
new points.
1.2 Procedures That Return Procedures • 15

2
1.5
1
0.5
x0 x1
0 1 2 3 4 5 6 7 8
–0.5 x

–1

To find a numerical solution to the equation f (x) = 0, guess an ap-


proximate solution, x0 , and then generate a sequence of approximations
using:

1. Newton’s method

2. The following formulation of the previous process

f (xk )
xk+1 = xk −
f 0 (xk )

You can implement this algorithm on a computer in a number of ways.

Example 1
The following procedure takes a function and creates a new procedure,
which takes an initial guess and, for that particular function, generates
the next guess. The new procedure does not work for other functions. To
find the roots of a new function, use MakeIteration to generate a new
guess-generating procedure. The unapply command turns an expression
into a procedure.
> MakeIteration := proc( expr::algebraic, x::name )
> local iteration;
> iteration := x - expr/diff(expr, x);
> unapply(iteration, x);
> end proc:

The procedure returned by the MakeIteration procedure maps the


name x to the expression assigned to the iteration.

Test the procedure on the expression x − 2 x.
> expr := x - 2*sqrt(x);
16 • Chapter 1: Procedures, Variables, and Extending Maple

expr := x − 2 x

> Newton := MakeIteration( expr, x);



x−2 x
Newton := x → x −
1
1− √
x

Newton returns the solution, x = 4 after a few iterations.


> x0 := 2.0;

x0 := 2.0

> to 4 do x0 := Newton(x0); end do;

x0 := 4.828427124

x0 := 4.032533198
x0 := 4.000065353
x0 := 4.000000000

Example 2
The MakeIteration procedure requires its first argument to be an al-
gebraic expression. You can also write a version of MakeIteration that
works on functions. Since the following MakeIteration procedure recog-
nizes the parameter f as a procedure, you must use the eval command
to evaluate it fully.
> MakeIteration := proc( f::procedure )
> (x->x) - eval(f) / D(eval(f));
> end proc:
> g := x -> x - cos(x);

g := x → x − cos(x)

> SirIsaac := MakeIteration( g );

x → x − cos(x)
SirIsaac := (x → x) −
x → 1 + sin(x)
1.2 Procedures That Return Procedures • 17

Note that SirIsaac is independent of the name g. Thus, you can


change g without breaking SirIsaac. You can find a good approximate
solution to x − cos(x) = 0 in a few iterations.
> x0 := 1.0;

x0 := 1.0

> to 4 do x0 := SirIsaac(x0) end do;

x0 := 0.7503638679

x0 := 0.7391128909
x0 := 0.7390851334
x0 := 0.7390851332

A Shift Operator
Consider the problem of writing a procedure that takes a function, f , as
input and returns a function, g, such that g(x) = f (x + 1). You can write
such a procedure in the following manner.
> shift := (f::procedure) -> ( x->f(x+1) ):

Try performing a shift on sin(x).


> shift(sin);

x → sin(x + 1)

Maple lexical scoping rules declare the f within the inner procedure
to be the same f as the parameter within the outer procedure. Therefore,
the shift command works as written.
The previous example of shift works with univariate functions but
it does not work with functions of two or more variables.
> h := (x,y) -> x*y;

h := (x, y) → x y

> hh := shift(h);
18 • Chapter 1: Procedures, Variables, and Extending Maple

hh := x → h(x + 1)

> hh(x,y);

Error, (in h) h uses a 2nd argument, y, which is


missing

Multivariate Functions To modify shift to work with multivariate


functions, rewrite it to accept the additional parameters.
In a procedure, args is the sequence of actual parameters, and
args[2..-1] is the sequence of actual parameters except the first one.
For more information on the selection operation ([ ]), refer to chapter 4
of the Introductory Programming Guide. It follows that the procedure
x->f(x+1,args[2..-1]) passes all its arguments except the first directly
to f .
> shift := (f::procedure) -> ( x->f(x+1, args[2..-1]) ):

> hh := shift(h);

hh := x → h(x + 1, args2..−1 )

> hh(x,y);

(x + 1) y

The function hh depends on h; if you change h, you implicitly change


hh;
> h := (x,y,z) -> y*z^2/x;

y z2
h := (x, y, z) →
x

> hh(x,y,z);

y z2
x+1
1.3 Local Variables and Invoking Procedures • 19

1.3 Local Variables and Invoking Procedures


Local variables are local to a procedure and to an invocation of that
procedure. Calling a procedure creates and uses new local variables each
time. If you invoke the same procedure twice, the local variables it uses
the second time are distinct from those it used the first time.
Local variables do not necessarily disappear when the procedure exits.
You can write procedures which return a local variable, either explicitly or
implicitly, to the interactive session, where it can exist indefinitely. These
variables are called escaped local variables. This concept can be confusing,
particularly since they can have the same name as global variables, or local
variables which another procedure or a different call to the same procedure
created. You can create many distinct variables with the same name.

Example 1
The following procedure creates a new local variable, a, and then returns
this new variable.
> make_a := proc()
> local a;
> a;
> end proc;

make_a := proc() local a; a end proc

By using local variables, you can produce displays that Maple would
otherwise simplify. For example, in Maple, a set contains unique elements.
The following demonstrates that each variable a that make_a returns is
unique.
> test := { a, a, a };

test := {a}

> test := test union { make_a() };

test := {a, a}

> test := test union { ’make_a’()$5 };

test := {a, a, a, a, a, a, a}
20 • Chapter 1: Procedures, Variables, and Extending Maple

This demonstrates that Maple identities consist of more than names.

Important: Independent of the number of variables you create with


the same name, when you type a name in an interactive session, Maple
interprets that name to be a global variable . You can easily find the
global a in the previous set test.
> seq( evalb(i=a), i=test);

true, false, false, false, false, false, false

Example 2
You can display expressions that Maple would ordinarily simplify au-
tomatically. For example, Maple automatically simplifies the expression
a + a to 2a. It is difficult to display the equation a + a = 2a. To display
such an equation, use the procedure make_a from Example 1.
> a + make_a() = 2*a;

a + a = 2a

When you type a name in an interactive session, the Maple program


interprets it as the global variable. While this prevents you from using
the assignment statement to directly assign a value to an escaped local
variable, it does not prevent you from using the assign command. You
must write a Maple expression which extracts the variable. For example,
in the previous equation, you can extract the local variable a by removing
the global a from the left side of the equation.
> eqn := %;

eqn := a + a = 2 a

> another_a := remove( x->evalb(x=a), lhs(eqn) );

another _a := a

You can then assign the global name a to this extracted variable and
verify the equation.
1.3 Local Variables and Invoking Procedures • 21

> assign(another_a = a);


> eqn;

2a = 2a

> evalb(%);

true

Assume Facility For complicated expressions, you must use the assume
command to extract the desired variable. You may have encountered this
situation before without realizing it, when you were using the assume
facility to remove an assumption. The assume facility attaches various
definitions to the variable you specify, with one result being that the
name subsequently appears as a local name with an appended tilde. No
relationship exists between the local variable b with an assumption, which
is displayed as b~, and the global variable name containing a tilde b~.
> assume(b>0);
> x := b + 1;

x := b~ + 1

> subs( ‘b~‘=c, x);

b~ + 1

When you clear the definition of the named variable, the association
between the name and the local name with the tilde is lost, but expressions
created with the local name still contain it.
> b := evaln(b);

b := b

> x;

b~ + 1

To reuse the expression, you must either perform a substitution before


removing the assumption or perform some manipulations of the expres-
sions similar to those used for the equation eqn.
22 • Chapter 1: Procedures, Variables, and Extending Maple

Procedure as a Returned Object


An important use for returning local objects arises when the returned
object is a procedure. When you write a procedure, which returns a pro-
cedure, you will often find it useful to have the procedure create a variable
that holds information pertinent only to the returned procedure. This al-
lows different procedures (or different invocations of the same procedure)
to pass information among themselves. The following examples illustrate
how different procedures pass information.

Example 3
Creating the Cartesian Product of a Sequence of Sets When you pass
a sequence of sets to the procedure, it constructs a new procedure. The
new procedure returns the next term in the Cartesian product each time
you invoke it. Local variables from the outer procedure are used to keep
track of which term to return next.
The Cartesian product of a sequence of sets is the set of all lists
in which the ith entry is an element of the ith set. Thus, the Cartesian
product of {α, β, γ} and {x, y} is
{α, β, γ} × {x, y} = {[α, x], [β, x], [γ, x], [α, y], [β, y], [γ, y]}.
The number of elements in the Cartesian product of a sequence of sets
grows very rapidly as the number of sets or size of the sets increases. It
therefore requires a large amount of memory to store all the elements of
the Cartesian product.

Solution You must write a procedure that returns a new element of the
Cartesian product each time you call it. By calling such a procedure re-
peatedly, you can process every element in the Cartesian product without
storing all its elements at once.
The following procedure returns the next element of the Cartesian
product of the list of sets s. It uses an array, c, of counters to determine
the next element. For example, c[1]=3 and c[2]=1 correspond to the
third element of the first set and the first element of the second set.
> s := [ {alpha, beta, gamma}, {x, y} ];

s := [{γ, α, β}, {x, y}]

> c := array( 1..2, [3, 1] );

c := [3, 1]
1.3 Local Variables and Invoking Procedures • 23

> [ seq( s[j][c[j]], j=1..2 ) ];

[β, x]

Before you call the element procedure you must initialize all the coun-
ters to 1, except the first one, which must be 0.
> c := array( [0, 1] );

c := [0, 1]

In following procedure element, nops(s) is the number of sets and


nops(s[i]) is the number of elements in the ith set. When you have seen
all the elements, the procedure re-initializes the array of counters and
returns FAIL. Therefore, you can repeatedly trace the Cartesian product
by calling element.
> element := proc(s::list(set), c::array(1, nonnegint))
> local i, j;
> for i to nops(s) do
> c[i] := c[i] + 1;
> if c[i] <= nops( s[i] ) then
> return [ seq(s[j][c[j]], j=1..nops(s)) ] ;
> end if;
> c[i] := 1;
> end do;
> c[1] := 0;
> FAIL;
> end proc:

> element(s, c); element(s, c); element(s, c);

[γ, x]

[α, x]
[β, x]

> element(s, c); element(s, c); element(s, c);

[γ, y]

[α, y]
[β, y]
24 • Chapter 1: Procedures, Variables, and Extending Maple

> element(s, c);

FAIL

> element(s, c);

[γ, x]

Example 4
Instead of writing a new procedure for each Cartesian product you study,
you can write a procedure, CartesianProduct, that returns such a pro-
cedure. CartesianProduct creates a list, s, of its arguments, which must
be sets, and then initializes the array, c, of counters and defines the sub-
procedure element. Finally, the element subprocedure is invoked inside
a proc structure.
> CartesianProduct := proc()
> local s, c, element;
> s := [args];
> if not type(s, list(set)) then
> error "expected a sequence of sets, but received",
> args ;
> end if;
> c := array( [0, 1$(nops(s)-1)] );
>
> element := proc(s::list(set), c::array(1, nonnegint))
> local i, j;
> for i to nops(s) do
> c[i] := c[i] + 1;
> if c[i] <= nops( s[i] ) then
> return [ seq(s[j][c[j]], j=1..nops(s)) ] ;
> end if;
> c[i] := 1;
> end do;
> c[1] := 0;
> FAIL;
> end proc;
>
> proc()
> element(s, c);
> end proc;
> end proc:

Again, you can find all six elements of {α, β, γ} × {x, y}.
> f := CartesianProduct( {alpha, beta, gamma}, {x,y} );
1.3 Local Variables and Invoking Procedures • 25

f := proc() element (s, c) end proc

> to 7 do f() end do;

[γ, x]

[α, x]
[β, x]
[γ, y]
[α, y]
[β, y]
FAIL

You can use CartesianProduct to study several products simultane-


ously.
> g := CartesianProduct( {x, y}, {N, Z, R},
> {56, 23, 68, 92} );

g := proc() element (s, c) end proc

The following are the first few elements of {x, y} × {N, Z, R} ×


{56, 23, 68, 92}.
> to 5 do g() end do;

[x, N, 23]

[y, N, 23]
[x, Z, 23]
[y, Z, 23]
[x, R, 23]

The variables s in f and g are local variables to CartesianProduct,


so they are not shared by different invocations of CartesianProduct.
Similarly, the variable c in f and g is not shared. You can see that the
two arrays of counters are different by invoking f and g a few more times.
26 • Chapter 1: Procedures, Variables, and Extending Maple

> to 5 do f(), g() end do;

[γ, x], [y, R, 23]

[α, x], [x, N, 56]


[β, x], [y, N, 56]
[γ, y], [x, Z, 56]
[α, y], [y, Z, 56]

The element procedure in g is also local to CartesianProduct. There-


fore, you can change the value of the global variable element without
breaking g.
> element := 45;

element := 45

> g();

[x, R, 56]

Summary The previous examples demonstrate that local variables can


escape the bounds of the procedures which create them, and that escaped
variables allow you to write procedures which create specialized proce-
dures.

Exercises
1. The procedure that CartesianProduct generates does not work if one
of the sets is empty.
> f := CartesianProduct( {}, {x,y} );

f := proc() element (s, c) end proc

> f();

Error, (in element) invalid subscript selector


1.4 Interactive Input • 27

Improve the type-checking in CartesianProduct so that it generates


an informative error message in each such case.
2. A partition of a positive integer, n, is a list of positive integers whose
sum is n. The same integer can appear several times in the partition
but the order of the integers in the partition is irrelevant. Thus, the
following are all the partitions of 5:

[1, 1, 1, 1, 1], [1, 1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 4], [2, 3], [5].

Write a procedure that generates a procedure that returns a new


partition of n each time you call it.

1.4 Interactive Input


Normally you pass input to Maple procedures as parameters. Sometimes,
however, you need a procedure to request input directly from the user.
For example, you can write a procedure that tests students on some topic
by generating random problems and verifying the students’ answers. The
input can be the value of a parameter, or the answer to a question such as
whether a parameter is positive. The two commands in Maple for reading
input from the terminal are the readline command and the readstat
command.

Reading Strings from the Terminal


The readline command reads one line of text from a file or the keyboard.
Use the readline command as follows.

readline( filename )

If filename is the special name terminal, then readline reads a line


of text from the keyboard. The readline command returns the text as a
string.
> s := readline( terminal );

Maplesoft

s := “Maplesoft”
28 • Chapter 1: Procedures, Variables, and Extending Maple

Example 1
The following application prompts the user for an answer to a question.
> DetermineSign := proc(a::algebraic) local s;
> printf("Is the sign of %a positive? Answer yes or no: ",a);
> s := readline(terminal);
> evalb( s="yes" or s = "y" );
> end proc:

> DetermineSign(u-1);

Is the sign of u-1 positive? Answer yes or no: y

true

Information: For more details on the readline command, see Read-


ing Text Lines from a File on page 197.

Reading Expressions from the Terminal


You can write procedures that interpret user input as a Maple expression
rather than a string. The readstat command reads one expression from
the keyboard.

readstat( prompt )

The prompt is an optional string.


> readstat("Enter degree: ");

Enter degree: n-1;

n−1

The user input for a readstat command must have a terminating semi-
colon or colon, or an error is raised.

Advantages Unlike the readline command, which only reads one line,
the readstat allows you to break a large expression across multiple lines.
Another advantage of using the readstat command is that if there is
an error in the input, the readstat command automatically repeats the
prompt for user input.
1.4 Interactive Input • 29

> readstat("Enter a number: ");

Enter a number: 5^^8;


syntax error, ‘^‘ unexpected:
5^^8;
^

Enter a number: 5^8;

390625

Example 2
The following is an application of the readstat command that imple-
ments an interface to the limit command. The procedure, given the
function f (x), assumes x is the variable if only one variable is present.
Otherwise, the user is asked for the variable and the limit point.
> GetLimitInput := proc(f::algebraic)
> local x, a, K;
> # choose all variables in f
> K := select(type, indets(f), name);
>
> if nops(K) = 1 then
> x := K[1];
> else
> x := readstat("Input limit variable: ");
> while not type(x, name) do
> printf("A variable is required: received %a\n", x);
> x := readstat("Please re-input limit variable: ");
> end do;
> end if;
> a := readstat("Input limit point: ");
> x = a;
> end proc:

The expression sin(x)/x depends only on one variable, so GetLimitInput


does not prompt for a limit variable.
> GetLimitInput( sin(x)/x );

Input limit point: 0;

x=0
30 • Chapter 1: Procedures, Variables, and Extending Maple

In the following output, the user first tries to use the number 1 as the
limit variable. Because 1 is not a name, GetLimitInput requests another
limit variable.
> GetLimitInput( exp(u*x) );

Input limit variable: 1;


A variable is required: received 1

Please re-input limit variable: x;

Input limit point: infinity;

x=∞

Information: You can specify a number of options to readstat. For


more information, see Reading Maple Statements on page 204.

Converting Strings to Expressions


For greater control of how and when Maple evaluates user input to a pro-
cedure, use the readline command instead of readstat. The readline
command reads the input as a string, and the parse command converts
the string to an expression. The string must represent a complete expres-
sion.
> s := "a*x^2 + 1";

s := “a*x^2 + 1”

> y := parse( s );

y := a x2 + 1

When you parse the string s you get an expression. In this case, you
get a sum.
> type(s, string), type(y, ‘+‘);

true, true
Exploring the Variety of Random
Documents with Different Content
“Go. Washington.

“Mr. Jefferson.”

Dr. Rittenhouse executed this high trust with great ability and
unimpeachable integrity, during three years; at the expiration of
which he resigned it, on the 30th of June, 1795. He had, long before,
expressed his anxious wish to retire from this station; but continued
in office until that time, on the solicitation of the President and at the
earnest desire of Mr. Jefferson.

As he was the first person appointed to that office, after the


institution of the Mint under the present federal government of the
Union, the duties that devolved upon him, in conducting it, were
arduous and complicated. He directed the construction of the
machinery; made arrangements for providing the necessary
apparatus; and, in daily visits to the Mint, whenever his health
permitted, personally superintended, with the most sedulous fidelity,
not only the general economy of the institution, but its operations in
the various departments;—duties, which his love of system and
order, his extensive knowledge, and his practical skill in mechanicks,
eminently qualified him to perform with peculiar correctness. At those
times when he was prevented, by indisposition, from attending at the
Mint in person, reports were made to him by the proper officers,
either verbally or in writing, of the state of the institution and the
progress of its business; and those officers received from him, on
such occasions, the instructions requisite for their several
departments.

In conducting the affairs of the Mint, Dr. Rittenhouse was


seconded by capable and trusty officers; among whom was Mr.
Voight, the Chief Coiner, with whose ingenuity and skill, as an
operative mechanic, he was well acquainted, having long before
employed him in that capacity, while he was engaged in constructing
one of his Orreries and carrying on other branches of his
professional business. Dr. Nicholas Way, a physician of some
eminence, officiated at the same time as Treasurer of the Mint; and
that respectable co-adjutor of the then Head of this important
institution in the national economy, has borne testimony to his
scrupulous attention to the public interests, in its direction:—“I have
been informed by his colleague in office, Dr. Way,”—says Dr.
Benjamin Rush,[269] who succeeded that gentleman in the
Treasurership of the Mint,—“that, in several instances, he,”
(speaking of the Director) “paid for work done at the Mint out of his
salary,[270] where he thought the charges for it would be deemed
extravagant by the United States.[271]

When Dr. Rittenhouse resigned the Directorship of the Mint, in


June 1792, he was succeeded in that office by Henry William De
Saussure, Esq. of South Carolina, a gentleman of distinguished
talents and respectability. But Mr. De Saussure did not long hold the
appointment: Some invidious and illiberal, as well as ill-founded
insinuations, were soon cast upon the establishment and the manner
in which it was conducted, by certain persons in the government,
who had very early evinced an hostility to the institution itself; and it
is not improbable, that some of this description were also influenced
in their inimical views towards it, by personal considerations. Mr. De
Saussure, disgusted with such unworthy conduct, retired from the
Directorship, after having held that office only a few months; during
which short period, he executed his trust in such a manner, as to
obtain the approbation of President Washington, and entitle him to
the public esteem.

The following letter, which was addressed by Mr. De Saussure to


the editors of the Charleston City Gazette, and published in that
paper, soon after his resignation, will serve to elucidate this subject:
as a vindication of that gentleman, and also of his predecessor, from
the injurious aspersions so unjustly thrown out against the institution
of the Mint by its enemies, that publication is entitled to a place in the
Memoirs of Rittenhouse; it shall now close the narrative of Dr.
Rittenhouse’s connexion with the Mint.
“Messrs. Freneau and Payne,

“I was filled with no less indignation than surprise, on reading the


debates in the house of representatives of the United States, on
Tuesday the 19th of January, respecting the Mint, to find that a good
deal of censure had been thrown out by some of the members
against the management of that establishment, in such general and
indiscriminating terms as might be deemed to implicate me, during
the short time I was in the Directorship.

“Several members spoke in hasty and unguarded terms; and one


member, whose name the printer had not given, passed all the
bounds of moderation. He is represented as having said, “that the
institution is a bad one, and is badly conducted: it had been most
scandalously carried on, and with very little advantage to the public.
If the institution is not better carried on than it has been, it ought to
be thrown aside.”—If I could tamely endure these imputations, which
in their generality may be supposed to reach me, I should be
unworthy the esteem of my fellow-citizens.

“It ought, perhaps, to be sufficient for me to produce to the public


eye the entire approbation which the President of the United States
was pleased to express of my conduct, when quitting the office of the
Director. I laid before him a full and exact state of the situation of the
Mint, and of the coinage prior to, and during my being in office. His
approbation is contained in a letter which he wrote me at the
moment of my leaving Philadelphia,—dated the 1st of Nov. 1795;
from which these words are an extract—“I cannot, at this moment of
your departure, but express my regret, that it was not accordant with
your views to remain in the Directorship of the Mint: Permit me to
add thereto, that your conduct therein gave entire satisfaction; and to
wish you a pleasant voyage, and a happy meeting with your friends
in South Carolina.”

“To those who know the President of the United States well,—who
know the caution with which he is accustomed to speak, and that he
possesses the talent of correctly estimating, as well as vigorously
overcoming, the difficulties which present themselves in every
circumstance of business,—this would rescue any character from the
unqualified censure of the members of the house of representatives.
But I will go further, and will shew the grounds on which the
President formed his judgment, so that every man may form his own
opinion.”

The Writer then proceeds with some details, respecting the


condition of the Mint on his coming into office, and at the time he left
it; in the course of which he states some difficulties, and unavoidable
obstructions to the progress of the coinage, which existed in the time
of his predecessor, and some of which could not be obviated while
he remained in the direction: and to this statement he annexes a
table, exhibiting an account of the gold and silver coinage at the
Mint, from its establishment to the close of October, 1795; at the foot
of which he remarks, that “there never was any period at which the
Mint was supplied with bullion, in a state for coinage, sufficient to
keep it regularly and fully employed for any considerable time;
except,” continues the writer, “near the close of my direction; to wit,
from the 1st to the 24th of October.” Mr. De Saussure thus concludes
his very satisfactory letter on this subject:

“Whilst I am vindicating myself from the censure, indiscriminately


thrown upon the management of the Mint, I do by no means concede
that the censure is justly applicable to my respectable predecessor.
The solid talents of Mr. Rittenhouse will be remembered with pride,
and his mild virtue recollected with tenderness, by his countrymen,
when many of his censors will be forgotten in the silent dust. His lofty
and correct mind, capable alike of ascending to the sublimest
heights of science, and of condescending to regulate the minute
movements of mechanical machinery, organized the Mint, and
created the workmen and the apparatus; amidst the complicated
difficulties from which the most persevering minds might have shrunk
without dishonour. A very long and debilitating state of ill health
prevented him from giving the establishment all the activity of which
it was susceptible; and he long wished to retire before he was
permitted. His country suffered him to retire, without remembering,
that it was the duty of a liberal nation to provide an independent
retreat in his old age, for one of the noblest of her Philosophers; and
to this neglect, it is attempted to add unmerited obloquy.

“I quit the ungrateful theme with disgust. I am consoled by the


approbation of him, by whom to be approved, will gladden the heart
through a long life. I rejoice that I quitted an office which subjects its
holder to such unjust censure, by the advice of my friends, who in
prophetic spirit told me, ‘that such offices were suited to men who
could bear up against censure, though they did not deserve it,’ which
they did not believe me formed to endure.”

“Henry Wm. De Saussure.

Charleston, S. C. Feb. 5. 1796.”

A national coin having been always considered as a proper, if not


an absolutely necessary, attribute of the sovereignty of a state,[272]
the establishment of a Mint, for the United States, was pretty early
contemplated. A plan for that purpose was brought into the view of
congress, in the last year of the war; although no national coinage
was instituted until ten years afterwards. The early part of the year
1780 was extremely disastrous to the affairs of the United States.
The fall of Charleston, S. C. depressed the spirits of the country: and
the almost total failure of public credit, accompanied by a want of
money, and other means of carrying on the war, about that period,
paralyzed the measures of the government. Such was the apathy of
the public mind, in regard to the perilous condition of the country at
that crisis, that many members of the general assembly of
Pennsylvania, which was convened on the 10th of May, in that year,
came thither with petitions from their constituents, praying to be
exempt from the payment of taxes.

But while this assembly were in session, a letter was received


from General Washington by the Supreme Executive Council of the
state, and by them confidentially communicated to the legislative
body, in which the distressed condition of the army was faithfully
described. Among other things the General stated, that,
notwithstanding his confidence in the attachment of the army to the
cause of their country, the distresses of the soldiery, arising from a
destitution of those necessaries which were indispensable, had
become extreme; insomuch, that appearances of mutiny were so
strongly marked on the countenances of the army, as to occasion in
his mind hourly apprehensions of the event.

This appalling information, and from such a source, elicited some


latent sparks of public spirit. Voluntary contributions were
immediately begun; and Robert Morris, Esq. a merchant of the
highest credit—as well as a man whose patriotism, talents and
enterprize, inspired confidence—contributed two hundred pounds,
Pennsylvania currency, in (what was then called) hard money. This
subscription commenced the 8th of June, 1780: but it amounted, in
the whole to only 200l. hard money, and 101,360l. in the public bills
of credit, or paper-money, denominated continental.

On the 17th of the same month, however, a meeting of the


contributors to this fund (which was intended as a donation, towards
carrying on the recruiting service,) and of others, was convened in
Philadelphia: with a view to promote the object more extensively. At
this meeting it was resolved—“to open a security-subscription, to the
amount of 300,000l. in real money; the subscribers to execute bonds
to the amount of their subscription, and to form a Bank thereon, for
supplying the army.”

This was the origin of the “Bank of North-America,” which thus


took its rise from an association of “a number of patriotic persons” in
the city of Philadelphia. The plan they formed for the purpose was
communicated to congress by the secretary at war, on the 20th of
June; and the next day they were honoured with a vote of thanks.

On the 20th of February, 1781, Mr. Morris was unanimously


elected by congress to the office of Superintendant of Finance, then
first created. This gentleman arranged, in the spring following[273], the
system of the present Bank of North-America; whereupon, many of
the subscribers to the first-formed bank transferred their
subscriptions to this institution. These were incorporated by an
ordinance of congress[274], passed the 31st of December, 1781; and
in the beginning of the succeeding year, this Bank commenced its
operations in Philadelphia. By the incorporating ordinance, the
following gentlemen were nominated by congress to be the president
and directors of the institution, until a choice of a new direction
should be made by the stockholders; namely, Thomas Willing,
Thomas Fitzsimons, John Maxwell Nesbitt, James Wilson, Henry
Hill, Samuel Osgood, Cadwalader Morris, Andrew Caldwell, Samuel
Inglis, Samuel Meredith, William Bingham, and Timothy Matlack,
Esquires. Mr. Willing, a merchant of high credit and respectability,
was president of the board.

Some doubts having arisen, respecting the right of congress,


under the then existing confederation, to exercise the power of
erecting any corporate body, an act was passed by the general
assembly of Pennsylvania, the 1st of April, 1782, to incorporate this
Bank, in order to obviate such doubts. That act was repealed, the
13th of September, 1785; but on the 18th of March, 1787, the charter
was renewed for the term of fourteen years, and has been since
further continued.

It was by means of this establishment, that Mr. Morris, the


superintendant of the finances, was enabled to support the public
credit, and, in the words of Dr. Gordon, “to keep things in motion,” at
a most critical period of the American affairs, and when the national
credit was in the lowest possible state of depression.[275]

The establishment of a Mint seems to be a necessary appendage


to that of a national Bank. Accordingly, Mr. Morris, in his capacity of
superintendant of the finances, addressed a letter to congress, on
the 15th of January 1782, “touching the establishment of a Mint.” On
the 21st of the succeeding month, they approved his proposal,—
directing him, at the same time, “to prepare and report to congress a
plan:” But nothing further appears to have been done in this
business, until the 16th of October 1786, when congress passed “An
Ordinance for the establishment of the Mint of the United States,” &c.

About two years, however, after the commencement of the present


federal government (viz. March 3. 1791,) a resolution of congress
was passed, concerning the establishing of a Mint, under such
regulations as should be directed by law. Previously to this, the late
Alexander Hamilton, Esq. had communicated to the house of
representatives, by their order, the result of his enquiries and
reflexions on the subject, in a diffuse and masterly official report. In
his report, this able financier, alike distinguished as a statesman and
a soldier,[276] remarked, that “the unequal values allowed in different
parts of the Union to coins of the same intrinsic worth; the defective
species of them, which embarrass the circulation of them in some of
the states; and the dissimilarity in their several monies of account,
are inconveniences, which if not to be ascribed to the want of a
national coinage, will at least be most effectually remedied by the
establishment of one; a measure that will at the same time give
additional security against impositions, by counterfeit as well as by
base currencies.”—“It was with great reason, therefore,” continues
the Secretary, “that the attention of congress, under the late
confederation, was repeatedly drawn to the establishment of a Mint;
and it is with equal reason that the subject has been resumed; now
that the favourable change which has taken place in the situation of
public affairs, admits of its being carried into execution.”

The Mint has been continued in Philadelphia, ever since its


establishment,—a great commercial city being very properly
considered the most suitable situation for such an institution; its
operations have been conducted, for many years past, with activity;
and there are few coins superior in beauty, to those of the American
Mint.

In less than a year after Dr. Rittenhouse had engaged himself in


the duties appertaining to the Directorship of the Mint, he was again
called upon to assist his countrymen, by the aid of his talents, in
effecting an important water-communication, inland, which was then
contemplated. An association, called “The Conewago-Canal
Company,” was formed in Philadelphia, in pursuance of a law
enacted the 13th of April, 1791; by which the sum of fourteen
thousand dollars was appropriated, for the purpose of improving the
navigation of the river Susquehanna, between Wright’s Ferry (now
the thriving town of Columbia) and the mouth of the Swatara. This
company consisted of seventeen members, of whom Dr. Rittenhouse
was one: and they were incorporated by an act of assembly, passed
the 10th of April, 1793.

Just about this period, an occurrence took place at Philadelphia,


then the seat of the national government, which excited much public
feeling at the time, and—contrary to the expectations of some good
men of sanguine dispositions—became the source of many political
evils, afterwards. This was the formation of what was called the
Democratic Society; a political association, produced by the
effervescences of the French revolution, while that all-important
event was yet viewed in a favourable light by free nations: and of this
society, Dr. Rittenhouse was elected President.

That Dr. Rittenhouse should have been selected as the President


of the Democratic Society, and chosen for that station, can be readily
accounted for. This gentleman had evinced, from the
commencement of the troubles between the American colonies of
Great-Britain and the parent country, an ardent attachment to the
cause of his native land. The benevolence of his disposition
rendered him the well-wisher of all mankind: hence every thing that,
in his view, bore the semblance of oppression, was odious to him.
But the wrongs which the country of his nativity, more particularly,
experienced, from the unconstitutional claims of the British
Parliament, roused those feelings of patriotism, with which his
virtuous breast was animated, at the beginning of the American
discontents: he was, therefore, an early and decided Whig; and the
same principles that induced him to become such, continued to
actuate him throughout the contest between the two countries.
The benignity of his temper must, nevertheless, have induced him
to be truly rejoiced at the return of peace. When that happy event
took place, he had too much goodness of heart to remember past
injuries, too much understanding to be influenced by unworthy and
mischievous prejudices; he had not a particle of malignity in his
nature. At the period of the Declaration of American Independence
by Congress, he believed, with a great majority of his countrymen,
that necessity justified the separation: and from that epocha, he was
heartily disposed to hold the mother-country, as his compatriots then
declared they did the rest of mankind,—“enemies in war, in peace
friends.”

When the French revolution commenced, the benevolence of his


feelings led him to believe, as almost every American then did, that it
would meliorate the condition of a great nation, whose inhabitants
constituted a large portion of the population of the European world;—
a nation, which, by the rigourous policy of its government, under a
long succession of ambitious and arbitrary monarchs, anterior to the
one then on the tottering throne of that ill-fated country, had become
extremely corrupt among the higher orders of the people; and in
which, the inferior classes were subjected to great oppression. The
American people having, on their separation from the mother-
country, instituted for themselves, as an independent nation, a
constitution wholly republican; they were disposed to attribute the
vices of the French government, before the revolution, to the
circumstance of its being a monarchy, and the sufferings of the
people of France, as necessarily resulting from the monarchial
system of rule over them. When, therefore, a republican form of
government was erected in France on the ruins of the throne; the
excesses, and even the atrocities of the people, which attended the
demolition of the ancient government of that country, and the
establishment of political institutions entirely new to its inhabitants,
found palliatives in the dispositions of most good men among us:
they were ascribed to the strong conflicting passions naturally
produced between the great body of the people, on the one part, and
their rulers on the other; excited by the long sufferings of the former,
and an unwillingness to part with power, in the latter. Great
enormities were considered as the inevitable consequences of these
opposite interests, when brought into action amidst a population of
many millions of men, whose national characteristic is that of levity of
temper and vehement passions; and a conflict, wherein all the
malign dispositions of the most depraved characters, actuated by
motives the most flagitious, intermingled themselves with the
designs of those who meant well. Such men, freed from all the
restraints of government and law, and utterly disregarding all the
obligations of either religious or moral duties, had then an
opportunity of giving a full vent to their views, whether of ambition,
avarice or personal resentments; and they did not fail to embrace it.
While, on the one hand, demagogues fanned the popular flame by
the vilest artifices; put on the semblance of patriotism, and by
practising the most detestable hypocrisy, professed themselves to be
the friends of the people, whom they were deluding into
premeditated ruin. Even virtuous Frenchmen, and many of them
possessing no inconsiderable share of discernment, soon fell victims
to the machiavelian policy of these pretended patriots. These, in their
turn, were sacrificed under the denunciations of their compeers, or
other aspiring villains; and thus, others still in succession: until,
finally, a fortunate military usurper, restored the monarchy in his own
person, with absolute sway; and by substituting an horrible military
despotism, in the place of a most sanguinary anarchy, confounded
all ranks of his subjects in one vast mass of miserable slaves; who
have been since employed in destroying the peace, freedom and
happiness of their fellow-men, in other countries. Such have been,
hitherto, the fruits of the French revolution; from which, at its
commencement, myriads of good men fondly anticipated an issue
precisely the reverse.[277]

Notwithstanding the criminal excesses committed by many of the


French revolutionists, before the institution of their short lived and
turbulent republic, it was hoped by most true Americans, attached by
fidelity as well as principle to that system of government, which was
then the legitimate one in their own country, that its ultimate
establishment in France would produce permanent benefits, to that
country at least, which would infinitely overbalance what were
considered, by zealous republicans, as temporary and partial evils,
such as seemed to be unavoidable, in bringing about a radical
change in the fundamental institutions of a great and powerful
empire. Many Americans were not, indeed, so sanguine in their
expectations: but such were, nevertheless, the prevailing sentiments
of the citizens of the United States,—even among the best-informed
men.

The deliberative and cautionary proceedings (as they purported to


be) of the more prominent revolutionary characters in France, in their
minor popular assemblies, prior to the establishment of their national
constitutional form of government, were judged of, in the United
States, with respect to their objects and utility, as similar assemblies,
under the denominations of councils of safety, committees of safety,
&c. were considered by their own citizens, at the commencement of
the American revolution: they were deemed to be necessary agents
of the people in each country, respectively, during the interregnum
which succeeded the abandonment of their ancient governments.

The Jacobin Club of Paris was one of these political engines of the
French revolution, for some time after its commencement; and,
perhaps, that assembly contained many worthy members, originally,
although it afterwards became notoriously infamous, by the
monstrous enormity of the crimes it countenanced and produced.

Chief Justice Marshall has observed (in his Life of Washington,)


that “soon after the arrival of Mr. Genet,[278] a Democratic Society
was formed in Philadelphia, which seems to have taken for its model
the Jacobin Club of Paris:”—“Its organization,” continues the
historian, “appears to have been completed on the 30th of May,
1793.”

It will nevertheless be recollected, that, about that period, the


shock given to the humane feelings of the American people, by the
murder of Louis XVI. their benefactor during the war in this country,
and by the death and sufferings of his queen and family, had mostly
subsided. The great American public still continued warmly and
sincerely attached to what was then viewed as the cause of the
French people: and therefore, whatever may have been the real
design of setting up a Democratic Society in Philadelphia, at that
point of time—a design only known to its founders,—it is certain, that
many highly estimable and meritorious citizens, and firm friends of
the existing government, were elected members of that society,
without any previous intimation being given to them of such an
intention: some of those persons never attended any of the meetings
of the society; and others soon discontinued their attendance. If it
were actually formed on the model of the Jacobin Club of Paris, by
some of those with whom the scheme originated, it cannot be
rationally presumed that men of great purity of reputation, in public
as well as private life, would either seek admission into such an
assembly, knowing it had any criminal views; nor would they, if
chosen members of it without their knowledge and consent,
participate in its proceedings, should these be found to be
unconstitutional, illegal, or dishonourable. Yet it is a matter of
notoriety, that persons of such characters were in some instances
enrolled among the members of the Democratic Society in
Philadelphia, at its commencement and soon after its organization, in
the spring of 1793.

It may be readily supposed, that such of its members as meant


well, would be desirous of placing at the head of that body, a man of
unimpeachable patriotism and integrity; and it is equally reasonable
to conclude, that, had there been a majority of its members, whose
secret designs were inimical to the true interest of the country or the
well-being of the government,—even these would wish to disguise
their intentions, under the nominal auspices of a character
universally respected and esteemed. Such a man was Dr.
Rittenhouse; and therefore was he selected by the Philadelphia
Democratic Society, as their President. At the time of his election to
that station, he held the highly important office of Director of the Mint,
under a commission from President Washington; for whose public
and private character he always entertained the most exalted
respect, besides the personal regard, which the writer of these
Memoirs knows to have subsisted between them. It is not
presumable, taking all considerations into view, that Dr. Rittenhouse
suffered any serious diminution in the esteem of that virtuous and
discerning statesman, by the circumstance of the Doctor being
placed at the head of the Democratic Society: for he not only
continued to hold the Directorship of the Mint, but, when he offered
his resignation of that high trust, two years afterwards, the
President’s reluctance to accept it yielded only to the Doctor’s urgent
solicitation to decline a further continuance in the office.

Whatever, therefore, may have been the real views and intentions
of some of the members of the Democratic Society which was
formed in Philadelphia, in 1793,—even if those of a majority of their
number were highly unjustifiable,—no imputation, unfavourable to
Dr. Rittenhouse’s character, either as a good citizen or an upright
man, could in the smallest degree be attached to him, by reason of
his having been chosen a President of that body, at the time of its
organization.[279]

That Dr. Rittenhouse was a zealous advocate for the liberties of


mankind, is unquestionable: but, much as he abhorred slavery and
oppression of every kind, did he deprecate turbulence and
licentiousness in the people, and wars of ambition, avarice or
injustice, undertaken by their rulers. He was decidedly friendly to
those measures of civil government, which are best calculated to
maintain order, tranquillity, and safety in the state, on just and
honourable principles. It can scarcely be doubted by any one,
intimately acquainted with his character, that he must have
concurred in sentiments similar to those attributed by the biographer
of Washington to that great man, or this subject,—in the following
observation: “Between a balanced republic and a democracy the
difference is like that between order and chaos. Real liberty, he
thought, was to be secured only by preserving the authority of the
laws, and maintaining the energy of government. Scarcely did
society present two characters which, in his opinion, less resembled
each other, than a patriot and a demagogue.”

Mr. Rittenhouse, it must be rationally supposed, was less


acquainted with mankind, than General Washington was known to
be: he had much fewer and more limited opportunities of studying
human nature; and professions of pretended patriots were, therefore,
more likely to impose on the unsuspecting honesty of his nature. He
may even have been deceived, for a while, and ere the plausible
fallacies of theorists in matters of civil polity, emanating from the
philosophy of the French school, had yet been manifested to the
world. A practical philosopher himself, he must have contemplated
with pity, if not with indignation, the doctrines of the followers of
Pyrrho: with whom it was a fundamental principle, that there is
nothing that can be denominated true or false, right or wrong, honest
or dishonest, just or unjust; or, in other words, that there is no
standard beyond law or custom; and that uncertainty and doubt are
attached to all things. Nevertheless, on these doctrines of the
sceptical philosophers of antiquity are founded that monstrous and
wicked tenet of most of the modern sceptics, that the end justifies
the means!—a principle destructive of all the foundations of religion
and morals. Well might the Abbé le Blanc exclaim, when noticing this
mischievous sect of philosophers, seventy years ago,—“Is it not
surprising, that men should endeavour to acquire the esteem of the
public, by striving to break the most sacred band of all societies; in
declaring their opinion to others, that there is neither virtue nor vice,
truth nor doubt.”—“Our modern philosophers,”[280] says the learned
Abbé in another place, “have been too confident.”

This is certainly correct, in one point of view; although the


assertion seems to imply a contradiction in terms, so far as it applies
to the metaphysical scepticism of many, assuming the honourable
appellation of Philosophers, without being entitled to the true
character. What were the sentiments of Dr. Rittenhouse, concerning
the tenets of men of this description, may be fairly inferred, not only
from the manner in which he has introduced the names of Berkeley
and Hume into the Oration which he pronounced before the
Philosophical Society, in the year 1775, but from other observations
and reflexions contained in that discourse, as well as from the
general tenure of opinions expressed by him on various occasions.
At an early period of the French revolution, a circumstance
occurred, which, from its connexion in some particulars with the life
of our Philosopher, is here entitled to notice.

On the 7th of August 1783, and after peace had been proclaimed,
congress unanimously passed a resolution in the following words
——“Resolved, That an equestrian statue of General Washington be
erected at the place where the residence of Congress shall be
established;—that the statue be of bronze: the General to be
represented in a Roman dress, holding a truncheon in his right hand,
and his head, encircled with a laurel wreath. The Statue to be
supported by a marble pedestal, on which are to be represented, in
basso relievo, the following principal events of the war, in which
General Washington commanded in person: the evacuation of
Boston;—the capture of the Hessions, at Trenton;—the battle of
Princeton;—the action of Monmouth;—and the surrender of York.—
On the upper part of the front of the pedestal, to be engraved as
follows: “The United States in Congress assembled ordered this
Statue to be erected, in the year of our Lord 1783, in honour of
George Washington, the illustrious Commander in Chief of the
Armies of the United States of America, during the war which
vindicated and secured their Liberty, Sovereignty and
Independence.”[281]

This was an honourable testimony of the gratitude and affectionate


respect of the nation, towards the Hero and Patriot, who so
eminently merited both; and it was a sincere effusion of the heart, in
the representatives of the American people, while the transcendent
virtues of a Washington, and his then recent services in his
country’s cause, yet inspired every generous breast with a faithful
remembrance of his worth: It was a laudable proof of the patriotism
that actuated the public mind, at a period, when, in the words of an
enlightened historian,[282] “the glow of expression in which the high
sense universally entertained of his services was conveyed,
manifested a warmth of feeling seldom equalled in the history of
man.”
The fascination which the revolution of France spread over a large
portion of Europe and America, for some time after its
commencement, and during the time it yet bore the semblance of a
virtuous cause,—while it seemed to enchant the true friends of
freedom every where; and the oft-resounded and captivating name
of “Liberty,” produced in men of ardent tempers, and speculative
notions, ideas of its reality of the most extravagant nature, and in
numerous instances of very mischievous tendency.

Among those of the latter description was Joseph Ceracchi, an


Italian artist of celebrity. Mr. Ceracchi was a statuary, of great
eminence in his profession; and to the manners and
accomplishments of a gentleman, he united much genius and taste.
Though born and bred in the dominions of the papal see, he fostered
the principles of a republican. Conceiving that the genius of a free
government comported with these alone, he became an enthusiastic
admirer of the French republic. Finding the turbulent state of France,
at the beginning of her troubles, unfavourable to the exercise of his
art, in that country; and believing as he did, that the tranquil and
prosperous condition of the United States would afford full
employment for his talents, in a manner congenial to his inclinations,
as well as beneficial to his private interest; he arrived, with his wife—
a German lady of some distinction—at Philadelphia, then the seat of
the national government, sometime (it is supposed) in the year 1793.

The great equestrian statue, which congress had, ten years


before, decreed to be erected in honour of General Washington, had
not yet been executed; and Mr. Ceracchi imagined that the gratitude
of the American republic would furnish, besides this primary work,
ample scope for the exercise of his talents, in erecting honorary
memorials of some of the more illustrious characters, which the
American revolution had produced. The aptitude, beauty and
magnificence, which the artist designed to display in some great
public monuments of this kind, were exhibited in models which he
executed, for the purpose of testifying his abilities in the art he
professed: these were universally admired, as the productions of
superior genius, taste and skill. Yet Mr. Ceracchi remained
unemployed: the national council did not, even at that late day, avail
themselves of so favourable an opportunity of engaging him to erect
the statue decreed to Washington,—a work which continues
unexecuted at the present moment[283]! and the talents of that
eminent artist were, not long afterwards, for ever lost to the country.

Among the gentlemen with whom Mr. Ceracchi became


acquainted, in Philadelphia, were some members of the
Philosophical Society in that city; and, on their recommendation of
him, he was, himself, soon associated with this institution.

In this body, as the Writer believes, Dr. Rittenhouse acquired a


knowledge of Mr. Ceracchi’s person and character. Both Dr. and Mrs.
Rittenhouse, from their kind and unceasing attentions to this
gentleman and his wife, appear to have considered them as persons
of merit: the Doctor, particularly, by his friendly deportment towards
the husband, during the time he continued his residence in this
country, testified the esteem he had conceived for this ingenious
foreigner; heightened too, perhaps, by a delicate sensibility towards
him, on account of the disappointment in his expectations of public
patronage in his profession, which he experienced while here. For it
is known to the Memorialist, that when, in consequence of such
disappointment, Mr. Ceracchi became embarrassed in his pecuniary
affairs, Dr. Rittenhouse contributed liberally to his relief.

Some time in the summer of the year 1794 (if the Writer’s
recollection be correct,) our benevolent philosopher having occasion
to view the canal, intended to form a communication between the
waters of the Delaware and the Schuylkill, invited Mr. Ceracchi to
accompany him, for the purpose of examining the quality of the
marble in the great quarries of that material, situated near the margin
of the latter river, in the vicinity of the western end of the canal. The
Memorialist joined in this little excursion, during which, Dr.
Rittenhouse was, as usual, communicative, cheerful and instructive.

On inspecting the quarries just mentioned—so far as time then


permitted an examination of them,—Mr. Ceracchi seemed to think
they contained only laminated strata of stone; not massy blocks,
without fissures or veins, like the marbles of Carrara, and those in
some other parts of Europe: that, although this Schuylkill marble was
generally of a good quality and of a whiteness sufficiently pure, it
could not be obtained in masses thick enough for the larger subjects
of fine statuary. Yet this artist observed, that a large proportion of the
slabs appeared to be of dimensions suitable for various subjects of
sculpture; and more especially, that they furnished an excellent
material for many purposes, ornamental as well as useful, in public
edifices and other structures[284]. No other quarries of marble were
viewed, on this excursion: but it is probable Mr. Ceracchi would have
found the marbles of Hitner’s and Henderson’s quarries—which are
at nearly the same distance from Philadelphia, though not situated
very near the river Schuylkill—much better adapted in every respect,
to the uses he contemplated. This unfortunate man appeared to
have possessed, in addition to genius and fine professional talents,
the exalted virtue of gratitude. Dr. Rittenhouse was his benefactor;
and the Philosophical Society had elected him a member of their
body: a fine bust of the Philosopher in the antique style, was
executed by Ceracchi in white marble, and by him presented to the
Society, on the 6th of February, 1795. It is supposed that he left
America about twelve months after this date; and it is said, that he
afterwards perished on a scaffold, in Paris, in consequence of its
being alleged, that he was engaged in a conspiracy against the life
of Bonaparte.

In the spring of the year 1794, the Earl of Buchan, P. S. S. A. and


James Anderson, LL. D. both distinguished characters in Scotland,
were elected members of the American Philosophical Society, at
Philadelphia: and it appears probable, from a note addressed to Dr.
Rittenhouse by President Washington, that they had been put in
nomination, or, at least, that their election had been advocated by
the former, at the instance of the latter; the note is in these words—

“The President presents his compliments to Mr. Rittenhouse, and


thanks him for the attention he has given to the case of Mr. Anderson
and the Earl of Buchan.
“Sunday afternoon, 20th April, 1794.”

At the commencement of the following year, Lord Buchan[285] wrote


to Dr. Rittenhouse the following letter:

“Dryburgh Abbey, Jan. 12, 1795.

“Sir,

“My worthy friend, Mr. John Miller, son of the eminent professor,
John Miller, of Glasgow, whom I recommend to your attention, has
charged himself with this letter, and will deliver to you a Writing-Box,
which I dedicate to your use, as President of the Philosophical
Society at Philadelphia, and to your successors in office, as a
testimony of my high esteem for your literary character and for that
of the Society over which you preside.

“This Box is made of Yew, of Black Cherry tree, and Acacia and
Barberry, and veneered with Holly; all the growth of my garden at
this place, and joined, fitted and finished, by my own joiner, in this
house.

“On the lid is an authentic picture of Copernicus, and in the inside


thereof is a similar one of Napier. That of Copernicus is from the
accurate copy of the Chancellor Hupazzuoski’s original picture,
which was sent by the learned Dr. Wolf, of Dantzic, to the Royal
Society of London; and this limning of mine is most faithfully
delineated and shaded, from a drawing made by Mr. Thomas Parke,
of Picadilly, formerly a pupil of Valentine Green, engraver at London,
from the picture in the Royal Society, on a scale proportional in all
parts and with great fidelity; so that I can assure you of my limning
being a fac simile, as to the features and countenance. That of
Napier[286] is indeed a most exquisitely beautiful piece, by John
Brown, of Edinburgh, executed with the black-lead pencil, from an
original portrait in the possession of Lord Napier; and, as a drawing
with black-lead, excels, I believe, every thing of the kind now extant:
Mr. Brown having by drawing, during twelve years in Italy, from
statues, obtained a super-eminent accuracy and beauty of design.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like