Docsity

Maple Introductory Programming Guide - Applied Symbolic Computation | CS 300, Assignments of Computer Science

Partial preview of the text

Download Maple Introductory Programming Guide - Applied Symbolic Computation | CS 300 and more Assignments Computer Science in PDF only on Docsity!

Maple

Introductory

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. 2005.

ii •

Maplesoft, Maple, and Maplet are all trademarks of Waterloo Maple Inc.

©cMaplesoft, a division of Waterloo Maple Inc. 2005. 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 except 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-76-X

  • Preface
    • Audience
    • Worksheet Graphical Interface
    • Manual Set
    • Conventions
      • The Maple Programming Language
      • Using This Book
    • Customer Feedback
  • 1 Introduction to Programming in Maple - In This Chapter
    • 1.1 The Maple Software
    • 1.2 Maple Statements
      • Getting Started
      • Maple Statements
      • Getting Help
      • Displaying a Text String
      • Performing an Arithmetic Operation
      • Assigning to a Name
      • Using Maple Library Routines
    • 1.3 Procedures
      • Defining a Simple Procedure
        • Defined Procedures Maple Library Routines, Built-In Routines, and User-
      • ory 1.4 Interrupting Computations and Clearing the Internal Mem-
      • Interrupting a Maple Computation
      • Clearing the Maple Internal Memory
    • 1.5 Troubleshooting
      • Unexpected End of Statement
      • Missing Operator iv • Contents
      • Invalid, Wrong Number or Type of Arguments
      • Unbalanced Parentheses
      • Assignment Versus Equality
    • 1.6 Exercises
    • 1.7 Conclusion
  • 2 Maple Language Elements - In This Chapter
    • 2.1 Character Set
    • 2.2 Tokens
      • Reserved Words
      • Programming-Language Operators
      • Names
      • Strings
      • Natural Integers
    • 2.3 Using Special Characters
      • Token Separators
      • Blank Spaces, New Lines, Comments, and Continuation
      • Punctuation Marks
      • Escape Characters
    • 2.4 Types and Operands
      • Integers
      • Strings
      • Names
      • Concatenations
    • 2.5 Troubleshooting
      • Attempting to Assign to a Protected Name
      • Invalid Left-Hand Assignment
      • Incorrect Syntax in Parse
      • White Space Characters within a Token
      • Incorrect Use of Double and Single Quotes
    • 2.6 Exercises
    • 2.7 Conclusion
  • 3 Maple Expressions and Statements - In This Chapter
    • 3.1 Syntax and Semantics
      • Syntax
      • Semantics
    • 3.2 Expressions
      • Constants Contents • v
      • Operators
      • Data Structures
      • Functions
    • 3.3 Using Expressions
      • Investigating the Parts of an Expression
      • Evaluating and Simplifying Expressions
      • Unevaluated Expressions
      • Substituting Subexpressions
      • Displaying Large Expressions: Labels
      • Structured Types
    • 3.4 Statements
      • The Assignment Statement
      • Selection Statements
      • Repetition Statements
      • The read and save Statements
      • The break and next Statements
      • The error and return Statements
      • The use Statement
      • The quit Statement
    • 3.5 Troubleshooting
      • Syntax Errors
      • Reserved Word Unexpected
      • Break or Next Not in Loop
    • 3.6 Exercises
    • 3.7 Conclusion
  • 4 Basic Data Structures - In This Chapter
    • 4.1 Sets
      • Manipulating a Set
    • 4.2 Lists
      • Manipulating a List
    • 4.3 Tables
      • An Alternate Method for Generating a Table
      • Table Evaluation Rules
      • Manipulating a Table
    • 4.4 arrays and Arrays
      • Evaluation Rules for arrays
      • Manipulating arrays and Arrays
    • 4.5 Selecting Elements from a Data Structure
      • The Selection Operation [] vi • Contents
      • The op Command
      • The select, remove, and selectremove Commands
    • 4.6 Converting Between Data Structures
      • Converting a Sequence to a Set or a List
      • Converting Other Data Structures
    • 4.7 Other Maple Data Structures
      • Stacks
      • Queues
    • 4.8 Troubleshooting
      • Wrong Number of Parameters in Function
      • Invalid Subscript Selector
      • Requires Range or Initialization List for Building arrays
      • Error in array Bound or Array Index out of Range
    • 4.9 Exercises
    • 4.10 Conclusion
  • 5 Flow Control - In This Chapter
    • 5.1 Selection and Conditional Execution
      • The if Statement
      • The ‘if‘ Operator
    • 5.2 Repetition
      • The for Loop
      • The while Loop
      • Control within Loops
    • 5.3 Looping Commands
      • The map Command
      • The select, remove, and selectremove Commands
      • The zip Command
      • The seq, add, and mul Commands
      • Using Specialized Looping Commands
    • 5.4 Troubleshooting
      • Cannot Evaluate Boolean in if Statement
      • Value in Loop Must Be Numeric or Character
      • Variable Previously Assigned
      • Wrong Parameters in Function $
    • 5.5 Exercises
    • 5.6 Conclusion
  • 6 Maple Procedures
    • In This Chapter Contents • vii
  • 6.1 Defining a Procedure
    • Naming a Procedure
    • Executing a Procedure
  • 6.2 Procedure Components
    • Formal Parameters
    • Variables
    • Procedure Options
    • Procedure Description
    • Procedure Body Statements
  • 6.3 Procedure Interpretation
  • 6.4 Procedure Return Values
    • Explicit Returns
    • Error Returns
    • Returning Values through Parameters
    • Returning Unevaluated
  • 6.5 Documenting Your Procedures
    • Indicating Copyright
    • Formatting Code for Readability
    • Adding Comments
    • Including a Procedure Description
    • Creating Help Pages
  • 6.6 Saving and Retrieving Procedures
  • 6.7 Viewing Maple Library Source Code
    • Special Evaluation Rules for Procedures
    • Displaying Maple Library Source Code
  • 6.8 Alternate Methods for Defining a Procedure
    • Functional Operators: Mapping Notation
    • The unapply Command
    • Unnamed Procedures and the map Command
    • Building a List of Arguments
  • 6.9 The Procedure Object
    • The procedure Type
    • Procedure Operands
  • 6.10 Using Data Structures to Solve Problems
    • Computing an Average
    • Testing for Membership
    • Performing a Binary Search
    • Plotting the Roots of a Polynomial
    • Connected Graphs
  • 6.11 Troubleshooting - Missing Argument viii • Contents - Incorrect Argument Type - Implicitly Declared Local Variable - Understanding Names, Functions, and Remember Tables
    • 6.12 Exercises
    • 6.13 Conclusion
  • 7 Input and Output - In This Chapter
    • 7.1 Screen and Keyboard I/O
      • Printing Output to the Screen
      • Interactive Input
    • 7.2 Standard Disk I/O
      • Readable File Formats in Maple
      • Using Filenames in Maple Statements
      • Reading and Saving Data in Maple
      • Importing Data from Files
      • Exporting Data to Files
    • 7.3 Troubleshooting
      • Syntax Error in readstat
      • Extra Characters at End of Parsed String
      • Unable to Read Filename
    • 7.4 Exercises
    • 7.5 Conclusion
  • 8 Debugging and Efficiency - In This Chapter
    • 8.1 A Tutorial Example
      • Numbering the Procedure Statements I
      • Invoking the Debugger I
        • ging I Controlling the Execution of a Procedure During Debug-
      • Invoking the Debugger II
    • 8.2 Maple Debugger Commands
      • Numbering the Procedure Statements II
      • Invoking the Debugger III
        • ging II Controlling the Execution of a Procedure During Debug-
      • Changing the State of a Procedure During Debugging
      • Examining the State of a Procedure During Debugging
      • Using Top-Level Commands at the Debugger Prompt
    • Restrictions Contents • ix
  • 8.3 Detecting Errors
    • Tracing a Procedure
    • Using Assertions
    • Handling Exceptions
    • Checking Syntax
  • 8.4 Creating Efficient Programs
    • Displaying Time and Memory Statistics
    • Profiling a Procedure
  • 8.5 Managing Resources
    • Setting a Time Limit on Computations
    • Garbage Collection
    • Communicating with the Kernel
  • 8.6 Exercises
  • 8.7 Conclusion
  • System 9 Introduction to the Maplet User Interface Customization
    • In This Chapter
  • 9.1 Uses of Maplet Applications
    • Custom Maple Calculators
    • Interfaces to Maple Packages and Routines
    • Queries
    • Messages
  • 9.2 The Maplets Package
    • Elements
    • Examples
    • Tools
    • Display
  • 9.3 Terminology
  • 9.4 Elements
    • Window Body Elements
    • Layout Elements
    • MenuBar Elements
    • ToolBar Elements
    • Command Elements
    • Dialog Elements
    • Other Elements
    • Reference Options
  • 9.5 Example Maplet Applications
    • Linear Algebra Subpackage
      • Using the Example Maplet Applications x • Contents
    • 9.6 Tools
      • Maplet System Global Variables
    • 9.7 Running a Maplet Application
    • 9.8 Writing a Maplet Application
      • Defining a Maplet Application
      • Maplet Application Programming Style Guidelines
    • 9.9 After Reading This Chapter
    • 9.10 Conclusion
  • Index

Preface

This manual introduces the basic MapleTM^ programming concepts, such as expressions, data structures, looping and decision mechanisms, proce- dures, input and output, debugging, and Maplets.

Audience

As a Maple user, you may have only used Maple interactively, written Maple programs, or programmed in another computer language. You should be familiar with the following:

  • Maple online help introduction
  • Example worksheets
  • How to use Maple interactively
  • The Maple User Manual

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-line^1 version, the classic worksheet (not available on Macintosh ©r), and custom-built MapletTM^ applications. The full Maple system is available through all of these interfaces. In this manual, any references to the graphical Maple

(^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.

Conventions • 3

  • Note - additional information relevant to the section
  • Important - information that must be read and followed

The Maple Programming Language

Writing a Maple program can be very simple. It can be as straightforward as placing proc() and end proc around a group of Maple commands. However, using the Maple programming language, you can write Maple procedures that perform complex operations. Writing code in Maple does not require expert programming skills. Because Maple has a large library of routines, writing useful programs from these powerful building blocks is easy. Unlike traditional program- ming languages, with the Maple programming language you can perform complicated tasks by using a single Maple library routine. In addition, you can use the Maple programming language to automate long or repetitive sets of instructions. Ninety percent of the thousands of routines in the Maple language are Maple programs. You can examine these Maple programs and modify them to suit your needs, or extend them so that Maple can solve new types of problems. You can learn the fundamentals of the Maple programming language and write useful Maple programs in a few hours, rather than the days or weeks that it often takes to learn other languages. This efficiency is partly a result of the fact that Maple is interactive. This interaction makes it easier to test and correct programs.

Using This Book

Examples Perform the examples shown in the manual as you read. To strengthen your knowledge, try variations or refer to the related online help page(s).

Troubleshooting At the end of most chapters, there is a Troubleshoot- ing section that lists common errors encountered while performing the examples in the chapter. See this section if you receive an error that you do not understand.

Exercises Develop solutions to the problems posed in the Exercises at the end of each chapter. This consolidates and extends your learning.

4 • Preface

Customer Feedback

Maplesoft welcomes your feedback. For suggestions and comments related to this and other manuals, email [email protected].

6 • Chapter 1: Introduction to Programming in Maple

The user interface handles the input of mathematical expressions and commands, the display of output, and the control of the Maple work- sheet environment options.^1 The basic Maple system, the kernel, is a relatively small collection of compiled C code. When a Maple session is started, the entire kernel is loaded. It contains the essential facilities required to run Maple and per- form basic mathematical operations. The components include the Maple programming language interpreter, arithmetic and simplification routines, print routines, memory management facilities, and a collection of funda- mental functions. Its small size ensures that the Maple system is compact, portable, and efficient. In this guide, the kernel routines are referred to as built-in routines. The library contains the majority of the Maple routines. It includes functionality related to calculus, linear algebra, statistics, graphics, and many other topics. The Maple library consists of individual routines and packages of routines. These routines are accessed and interpreted by the Maple system as required. As a result of this modularity, the computer consumes resources proportional to only the facilities that are used, en- hancing the efficiency of the system. All library routines, which are im- plemented in the high-level Maple programming language, can be viewed and modified by users. Therefore, it is useful to learn the Maple program- ming language so that you can modify existing Maple code to produce customized routines.

1.2 Maple Statements

Getting Started

The Maple software runs on many different platforms. Depending on the platform, you use its specialized worksheet interface or command-line in- terface. In both cases, when a Maple session is started, the Maple prompt character (>) is displayed.

This prompt character indicates that Maple is waiting to receive input in the form of a Maple statement.^2

(^1) For more information about the Maple user interface and worksheets, refer to the Maple Getting Started Guide or Maple User Manual. (^2) Throughout this book, the Maple notation (or one-dimensional) input format is

1.2 Maple Statements • 7

Maple Statements

There are many types of valid statements. Examples include statements that request help on a particular topic, display a text string, perform an arithmetic operation, use a Maple library routine, or define a procedure.^3 Most Maple statements must have a trailing semicolon (;) or colon (:). If you enter a statement with a trailing semicolon, for most statements, the result is displayed. However, if you enter a statement with a trailing colon, the result is computed but not displayed.

(^) 2 + 3;

5

(^) 2 + 3:

Getting Help

To view an online help page for a particular topic, enter a question mark (?) followed by the corresponding topic name. For example, ?procedure displays a help page that describes how to write a Maple procedure.^4 This type of Maple statement does not have a trailing colon or semicolon.

Displaying a Text String

The following statement returns a string. The text that forms the string is enclosed in double quotes, and the result (the text string) is displayed because the statement has a trailing semicolon. In the second example, no result is displayed because the statement has a trailing colon.^5

(^) "Hello World";

“Hello World”

(^) "Hello World":

used to enter Maple statements. For more information on starting a Maple session, toggling between Maple notation (the default on most platforms) and standard math notation, and managing your files, refer to the Maple Getting Started Guide and Maple User Manual or enter ?managing at the Maple prompt. (^3) For more information about statements in Maple, see chapter 3. (^4) For more information about getting help in Maple, refer to ?help and ?HelpGuide. (^5) For more information about strings in Maple, see chapter 2 or refer to ?string.

1.3 Procedures • 9 103993 16551

Using Maple Library Routines

Once a value is assigned to a name, for example, the value assigned pre- viously to a, you can use the name as if it were the assigned object. For example, you can use the Maple library routine evalf to compute a floating-point (decimal) approximation to 103993/33102 divided by 2 by entering the following statement.

(^) evalf(a/2);

  1. 570796326

You can use the Maple library of routines, introduced on page 6, for many purposes. For example, you can find the derivative of an expression by using the diff command.^9

(^) diff(x^2 + x + 1/x, x);

2 x + 1 −

x^2

1.3 Procedures

This section formally introduces the concept of procedures in Maple. For more information about procedures, see chapter 6.

Defining a Simple Procedure

A Maple procedure (a type of program) is a prearranged group of state- ments processed together. The easiest way to create a Maple procedure is to encapsulate a sequence of commands, which can be used to per- form a computation interactively, between the proc(...) and end proc statements.

(^9) For more information about the Maple library routines, refer to the Maple User Manual or the online help.

10 • Chapter 1: Introduction to Programming in Maple

Entering a Procedure Definition The following procedure generates the string “Hello World‘. Enter this procedure in a Maple session by entering its definition on one line.

(^) hello := proc() "Hello World"; end proc;

hello := proc() “Hello World” end proc

For improved readability, enter the procedure on multiple lines: hold Shift and press Enter at the end of each line.^10 Indent lines in the procedure by using the spacebar. When you enter the last line, which contains end proc, press Enter.

(^) hello := proc() (^) "Hello World"; (^) end proc;

hello := proc() “Hello World” end proc

To run this procedure, enter its name followed by a set of parentheses and a semicolon. Enclose any input to the procedure—in this case none— between the parentheses and delimited (separated) by commas (,).

(^) hello();

“Hello World”

The next example is a procedure that uses the evalf command.

(^) half := proc(x) (^) evalf(x/2); (^) end proc;

half := proc(x) evalf(1/ 2 ∗ x) end proc

This procedure requires one input, x. The procedure computes the approximation of the value of x divided by 2. A Maple procedure re- turns the result of the last executed statement. Since evalf(x/2) is the last calculation performed in the procedure half (in fact, it is the only calculation), the approximation of x/2 is returned.

(^10) For more information, see Unexpected End of Statement on page 17.