Introduction to Programming With Mathpiper V

140
v.95b - 08/01/10 Introduction To Programming With MathPiper 1/140 Introduction To Programming With MathPiper And MathPiperIDE by Ted Kosan Copyright © 2010 by Ted Kosan This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/

Transcript of Introduction to Programming With Mathpiper V

Page 1: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 1/140

Introduction To Programming With

MathPiper And MathPiperIDE

by Ted Kosan

Copyright © 2010 by Ted Kosan

This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 License. To view a copy of

this license, visit http://creativecommons.org/licenses/by-sa/3.0/

Page 2: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 2/140

Table of Contents1 Preface.................................................................................................................9

1.1 Dedication......................................................................................................91.2 Acknowledgments..........................................................................................91.3 Website And Support Email List....................................................................91.4 Recommended Weekly Sequence When Teaching A Class With This Book. .9

2 Introduction........................................................................................................10

2.1 What Is A Mathematics Computing Environment?.....................................102.2 What Is MathPiperIDE?...............................................................................112.3 What Inspired The Creation Of MathPiperIDE?..........................................12

3 Downloading And Installing MathPiperIDE.......................................................13

3.1 Installing Sun's Java Implementation..........................................................133.1.1 Installing Java On A Windows PC.........................................................13

3.1.1.1 The 64 Bit Version Of Windows Needs The 64 Bit Version Of Java....................................................................................................................13

3.1.2 Installing Java On A Macintosh.............................................................133.1.3 Installing Java On A Linux PC...............................................................13

3.2 Downloading And Extracting.......................................................................133.2.1 Extracting The Archive File For Windows Users..................................143.2.2 Extracting The Archive File For Unix Users.........................................15

3.3 MathPiperIDE's Directory Structure & Execution Instructions..................153.3.1 Executing MathPiperIDE On Windows Systems...................................163.3.2 Executing MathPiperIDE On Unix Systems..........................................16

3.3.2.1 MacOS X.........................................................................................16

4 The Graphical User Interface.............................................................................17

4.1 Buffers And Text Areas................................................................................174.2 The Gutter...................................................................................................174.3 Menus..........................................................................................................17

4.3.1 File........................................................................................................184.3.2 Edit........................................................................................................184.3.3 Search...................................................................................................184.3.4 Markers, Folding, and View..................................................................194.3.5 Utilities.................................................................................................194.3.6 Macros..................................................................................................194.3.7 Plugins..................................................................................................194.3.8 Help.......................................................................................................19

4.4 The Toolbar..................................................................................................194.4.1 Undo And Redo.....................................................................................20

Page 3: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 3/140

5 MathPiper: A Computer Algebra System For Beginners...................................21

5.1 Numeric Vs. Symbolic Computations..........................................................215.2 Using The MathPiper Console As A Numeric (Scientific) Calculator..........22

5.2.1 Functions..............................................................................................235.2.1.1 The Sqrt() Square Root Function...................................................245.2.1.2 The IsEven() Function....................................................................24

5.2.2 Accessing Previous Input And Results..................................................255.3 Saving And Restoring A Console Session....................................................25

5.3.1 Syntax Errors........................................................................................265.4 Using The MathPiper Console As A Symbolic Calculator...........................26

5.4.1 Variables...............................................................................................275.4.1.1 Calculating With Unbound Variables.............................................285.4.1.2 Variable And Function Names Are Case Sensitive........................295.4.1.3 Using More Than One Variable......................................................30

5.5 Exercises......................................................................................................315.5.1 Exercise 1.............................................................................................315.5.2 Exercise 2.............................................................................................315.5.3 Exercise 3.............................................................................................315.5.4 Exercise 4.............................................................................................315.5.5 Exercise 5.............................................................................................32

6 The MathPiper Documentation Plugin...............................................................33

6.1 Function List................................................................................................336.2 Mini Web Browser Interface........................................................................336.3 Exercises......................................................................................................34

6.3.1 Exercise 1.............................................................................................346.3.2 Exercise 2.............................................................................................34

7 Using MathPiperIDE As A Programmer's Text Editor.......................................35

7.1 Creating, Opening, Saving, And Closing Text Files.....................................357.2 Editing Files.................................................................................................357.3 File Modes...................................................................................................367.4 Learning How To Type Properly Is An Excellent Investment Of Your Time367.5 Exercises......................................................................................................36

7.5.1 Exercise 1.............................................................................................36

8 MathPiperIDE Worksheet Files..........................................................................37

8.1 Code Folds...................................................................................................378.1.1 The title Attribute.................................................................................38

8.2 Automatically Inserting Folds & Removing Unpreserved Folds.................388.3 Placing Text Outside Of A Fold....................................................................398.4 Exercises......................................................................................................39

8.4.1 Exercise 1.............................................................................................408.4.2 Exercise 2.............................................................................................40

Page 4: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 4/140

8.4.3 Exercise 3.............................................................................................408.4.4 Exercise 4.............................................................................................40

9 MathPiper Programming Fundamentals............................................................41

9.1 Values and Expressions...............................................................................419.2 Operators.....................................................................................................419.3 Operator Precedence...................................................................................429.4 Changing The Order Of Operations In An Expression................................439.5 Functions & Function Names......................................................................449.6 Functions That Produce Side Effects..........................................................45

9.6.1 Printing Related Functions: Echo(), Write(), And Newline()................459.6.1.1 Echo().............................................................................................459.6.1.2 Echo Functions Are Useful For "Debugging" Programs................479.6.1.3 Write()............................................................................................489.6.1.4 NewLine().......................................................................................48

9.7 Expressions Are Separated By Semicolons.................................................499.7.1 Placing More Than One Expression On A Line In A Fold.....................499.7.2 Placing Multiple Expressions In A Code Block.....................................50

9.7.2.1 Automatic Bracket, Parentheses, And Brace Match Indicating.....519.8 Strings.........................................................................................................52

9.8.1 The MathPiper Console and MathPiper Folds Can Access The Same Variables........................................................................................................529.8.2 Using Strings To Make Echo's Output Easier To Read.........................53

9.8.2.1 Combining Strings With The : Operator........................................539.8.2.2 WriteString()..................................................................................539.8.2.3 Nl().................................................................................................549.8.2.4 Space()...........................................................................................54

9.8.3 Accessing The Individual Letters In A String.......................................549.8.3.1 Indexing Before The Beginning Of A String Or Past The End Of A String..........................................................................................................55

9.9 Comments....................................................................................................569.10 How To Tell If MathPiper Has Crashed And What To Do If It Has............579.11 Exercises....................................................................................................57

9.11.1 Exercise 1...........................................................................................589.11.2 Exercise 2...........................................................................................589.11.3 Exercise 3...........................................................................................589.11.4 Exercise 4...........................................................................................589.11.5 Exercise 5...........................................................................................599.11.6 Exercise 6...........................................................................................599.11.7 Exercise 7...........................................................................................59

10 Rectangular Selection Mode And Text Area Splitting......................................61

10.1 Rectangular Selection Mode.....................................................................61

Page 5: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 5/140

10.2 Text area splitting......................................................................................6110.3 Exercises....................................................................................................61

10.3.1 Exercise 1...........................................................................................62

11 Working With Random Integers.......................................................................63

11.1 Obtaining Random Integers With The RandomInteger() Function...........6311.2 Simulating The Rolling Of Dice.................................................................6411.3 Exercises....................................................................................................65

11.3.1 Exercise 1...........................................................................................65

12 Making Decisions.............................................................................................66

12.1 Conditional Operators...............................................................................6612.2 Predicate Expressions...............................................................................6912.3 Exercises....................................................................................................69

12.3.1 Exercise 1...........................................................................................6912.3.2 Exercise 2...........................................................................................7012.3.3 Exercise 3...........................................................................................70

12.4 Making Decisions With The If() Function & Predicate Expressions.........7012.4.1 If() Functions Which Include An "Else" Parameter.............................72

12.5 Exercises....................................................................................................7212.5.1 Exercise 1...........................................................................................7312.5.2 Exercise 2...........................................................................................73

12.6 The And(), Or(), & Not() Boolean Functions & Infix Notation..................7312.6.1 And()...................................................................................................7312.6.2 Or()......................................................................................................7512.6.3 Not() & Prefix Notation......................................................................76

12.7 Exercises....................................................................................................7712.7.1 Exercise 1...........................................................................................7812.7.2 Exercise 2...........................................................................................7812.7.3 Exercise 3...........................................................................................78

13 The While() Looping Function & Bodied Notation...........................................80

13.1 Printing The Integers From 1 to 10...........................................................8013.2 Printing The Integers From 1 to 100.........................................................8213.3 Printing The Odd Integers From 1 To 99..................................................8213.4 Printing The Integers From 1 To 100 In Reverse Order...........................8313.5 Expressions Inside Of Code Blocks Are Indented.....................................8413.6 Long-Running Loops, Infinite Loops, & Interrupting Execution...............8413.7 A Program That Simulates Rolling Two Dice 50 Times.............................8513.8 Exercises....................................................................................................87

13.8.1 Exercise 1...........................................................................................8813.8.2 Exercise 2...........................................................................................8813.8.3 Exercise 3...........................................................................................8813.8.4 Exercise 4...........................................................................................88

Page 6: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 6/140

14 Predicate Functions.........................................................................................89

14.1 Finding Prime Numbers With A Loop........................................................9014.2 Finding The Length Of A String With The Length() Function...................9214.3 Converting Numbers To Strings With The ToString() Function...............9314.4 Finding Prime Numbers Which End With 7 (And Multi-line Function Calls)...........................................................................................................................9314.5 Exercises....................................................................................................94

14.5.1 Exercise 1...........................................................................................9514.5.2 Exercise 2...........................................................................................95

15 Lists: Values That Hold Sequences Of Expressions.........................................96

15.1 Append() & Nondestructive List Operations.............................................9715.2 Using While Loops With Lists ...................................................................98

15.2.1 Using A While Loop And Append() To Place Values Into A List........10015.3 Exercises..................................................................................................101

15.3.1 Exercise 1.........................................................................................10115.3.2 Exercise 2.........................................................................................10115.3.3 Exercise 3.........................................................................................101

15.4 The ForEach() Looping Function.............................................................10215.5 Print All The Values In A List Using A ForEach() function......................10215.6 Calculate The Sum Of The Numbers In A List Using ForEach().............10315.7 The .. Range Operator.............................................................................10415.8 Using ForEach() With The Range Operator To Print The Prime Numbers Between 1 And 100..........................................................................................105

15.8.1 Using ForEach() And The Range Operator To Place The Prime Numbers Between 1 And 50 Into A List......................................................10615.8.2 Exercises...........................................................................................10715.8.3 Exercise 1.........................................................................................10715.8.4 Exercise 2.........................................................................................10715.8.5 Exercise 3.........................................................................................10715.8.6 Exercise 4.........................................................................................108

16 Functions & Operators Which Loop Internally..............................................109

16.1 Functions & Operators Which Loop Internally To Process Lists.............10916.1.1 TableForm().......................................................................................10916.1.2 Contains()..........................................................................................10916.1.3 Find()................................................................................................11016.1.4 Count()..............................................................................................11016.1.5 Select()..............................................................................................11116.1.6 The Nth() Function & The [] Operator..............................................11116.1.7 The : Prepend/Append Operator.......................................................11216.1.8 Concat()............................................................................................11216.1.9 Insert(), Delete(), & Replace()..........................................................112

Page 7: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 7/140

16.1.10 Take() .............................................................................................11316.1.11 Drop()..............................................................................................11416.1.12 FillList()..........................................................................................11416.1.13 RemoveDuplicates()........................................................................11516.1.14 Reverse().........................................................................................11516.1.15 Partition()........................................................................................11516.1.16 Table() ............................................................................................11616.1.17 HeapSort()......................................................................................117

16.2 Functions That Work With Integers........................................................11716.2.1 RandomIntegerList().........................................................................11716.2.2 Maximum() & Minimum().................................................................11816.2.3 Quotient() & Modulo()......................................................................11816.2.4 Gcd().................................................................................................11916.2.5 Lcm().................................................................................................11916.2.6 Sum().................................................................................................12016.2.7 Product()...........................................................................................120

16.3 Exercises..................................................................................................12016.3.1 Exercise 1.........................................................................................12116.3.2 Exercise 2.........................................................................................12116.3.3 Exercise 3.........................................................................................12116.3.4 Exercise 4.........................................................................................12116.3.5 Exercise 5.........................................................................................122

17 Nested Loops..................................................................................................123

17.1 Generate All The Combinations That Can Be Entered Into A Two Digit Wheel Lock Using A Nested Loop...................................................................12317.2 Exercises..................................................................................................124

17.2.1 Exercise 1.........................................................................................125

18 User Defined Functions..................................................................................126

18.1 Global Variables, Local Variables, & Local()...........................................12818.2 Exercises..................................................................................................130

18.2.1 Exercise 1.........................................................................................13018.2.2 Exercise 2.........................................................................................130

19 Miscellaneous topics......................................................................................132

19.1 Incrementing And Decrementing Variables With The ++ And -- Operators.........................................................................................................................132

19.1.1 Incrementing Variables With The ++ Operator...............................13219.1.2 Decrementing Variables With The -- Operator.................................13319.1.3 The Break() Function........................................................................13419.1.4 The Continue() Function...................................................................13519.1.5 The Repeat() Function......................................................................13519.1.6 The EchoTime() Function.................................................................137

Page 8: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 8/140

19.2 Exercises..................................................................................................13919.2.1 Exercise 1.........................................................................................13919.2.2 Exercise 2.........................................................................................13919.2.3 Exercise 3.........................................................................................14019.2.4 Exercise 4.........................................................................................14019.2.5 Exercise 5.........................................................................................140

Page 9: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 9/140

1 Preface

1.1 Dedication

This book is dedicated to Steve Yegge and his blog entries "Math Every Day" (http://steve.yegge.googlepages.com/math-every-day) and "Math For Programmers" (http://steve-yegge.blogspot.com/2006/03/math-for-programmers.html).

1.2 Acknowledgments

The following people have provided feedback on this book (if I forgot to include your name on this list, please email me at ted.kosan at gmail.com):

Sherm Ostrowsky

Susan Addington

Matthew Moelter

1.3 Website And Support Email List

The website for MathPiper and MathPiperIDE is http://mathpiper.org.

The support email list for this book is called [email protected] and you can subscribe to it at http://groups.google.com/group/mathpiper-user

1.4 Recommended Weekly Sequence When Teaching A Class With This Book

• Week 1: Sections 1 - 6.

• Week 2: Sections 7 - 9.

• Week 3: Sections 10 - 13.

• Week 4: Sections 14 - 15.

• Week 5: Sections 16 - 19.

• Week 6: Exam

1

2

3456

7

89

10

11

12

13

14

151617

1819

20

21

22

23

24

25

Page 10: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 10/140

2 IntroductionMathPiperIDE is an open source mathematics computing environment for performing numeric and symbolic computations (the difference between numeric and symbolic computations are discussed in a later section). Mathematics computing environments are complex and it takes a significant amount of time and effort to become proficient at using one. The amount of power that these environments make available to a user, however, is well worth the effort needed to learn one. It will take a beginner a while to become an expert at using MathPiperIDE, but fortunately one does not need to be a MathPiperIDE expert in order to begin using it to solve problems.

2.1 What Is A Mathematics Computing Environment?

A Mathematics Computing Environment is a set of computer programs that 1) automatically execute a wide range of numeric and symbolic mathematics calculation algorithms and 2) provide a user interface which enables the user to access these calculation algorithms and manipulate the mathematical objects they create (An algorithm is a step-by-step sequence of instructions for solving a problem and we will be learning about algorithms later in the book).

Standard and graphing scientific calculator users interact with these devices using buttons and a small LCD display. In contrast to this, users interact with MathPiperIDE using a rich graphical user interface which is driven by a computer keyboard and mouse. Almost any personal computer can be used to run MathPiperIDE, including the latest subnotebook computers.

Calculation algorithms exist for many areas of mathematics and new algorithms are constantly being developed. Software that contains these kind of algorithms is commonly referred to as "Computer Algebra Systems (CAS)". A significant number of computer algebra systems have been created since the 1960s and the following list contains some of the more popular ones:

http://en.wikipedia.org/wiki/Comparison_of_computer_algebra_systems

Some environments are highly specialized and some are general purpose. Some allow mathematics to be entered and displayed in traditional form (which is what is found in most math textbooks). Some are able to display traditional form mathematics but need to have it input as text and some are only able to have mathematics displayed and entered as text.

As an example of the difference between traditional mathematics form and text form, here is a formula which is displayed in traditional form:

a=x24hx37

26

272829303132333435

36

373839404142

4344454647

4849505152

53

5455565758

5960

Page 11: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 11/140

and here is the same formula in text form:

a = x^2 + 4*h*x + 3/7

Most computer algebra systems contain a mathematics-oriented programming language. This allows programs to be developed which have access to the mathematics algorithms which are included in the system. Some mathematics-oriented programming languages were created specifically for the system they work in while others were built on top of an existing programming language.

Some mathematics computing environments are proprietary and need to be purchased while others are open source and available for free. Both kinds of systems possess similar core capabilities, but they usually differ in other areas.

Proprietary systems tend to be more polished than open source systems and they often have graphical user interfaces that make inputting and manipulating mathematics in traditional form relatively easy. However, proprietary environments also have drawbacks. One drawback is that there is always a chance that the company that owns it may go out of business and this may make the environment unavailable for further use. Another drawback is that users are unable to enhance a proprietary environment because the environment's source code is not made available to users.

Some open source computer algebra systems do not have graphical user interfaces, but their user interfaces are adequate for most purposes and the environment's source code will always be available to whomever wants it. This means that people can use the environment for as long as they desire and they can also enhance it.

2.2 What Is MathPiperIDE?

MathPiperIDE is an open source Mathematics Computing Environment which has been designed to help people teach themselves the STEM disciplines (Science, Technology, Engineering, and Mathematics) in an efficient and holistic way. It inputs mathematics in textual form and displays it in either textual form or traditional form.

MathPiperIDE uses MathPiper as its default computer algebra system, BeanShell as its main scripting language, jEdit as its framework (hereafter referred to as the MathPiperIDE framework), and Java as it overall implementation language. One way to determine a person's MathPiperIDE expertise is by their knowledge of these components. (see Table 1)

61

62

6364656667

686970

7172737475767778

7980818283

84

8586878889

9091929394

Page 12: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 12/140

Level Knowledge

MathPiperIDE Developer

Knows Java, BeanShell, and the MathPiperIDE framework at an advanced level. Is able to develop MathPiperIDE plugins.

MathPiperIDE Customizer

Knows Java, BeanShell, and the MathPiperIDE framework at an intermediate level. Is able to develop MathPiperIDE macros.

MathPiperIDE Expert

Knows MathPiper at an advanced level and is skilled at using most aspects of the MathPiperIDE application.

MathPiperIDE Novice

Knows MathPiper at an intermediate level, but has only used MathPiperIDE for a short while.

MathPiperIDE Newbie

Does not know MathPiper but has been exposed to at least one programming language.

Programming Newbie

Does not know how a computer works and has never programmed before but knows how to use a word processor.

Table 1: MathPiperIDE user experience levels.

This book is for MathPiperIDE and Programming Newbies. This book will teach you enough programming to begin solving problems with MathPiperIDE and the language that is used is MathPiper. It will help you to become a MathPiperIDE Novice, but you will need to learn MathPiper from books that are dedicated to it before you can become a MathPiperIDE Expert.

The MathPiperIDE project website (http://MathPiperIDE.org) contains more information about MathPiperIDE along with other MathPiperIDE resources.

2.3 What Inspired The Creation Of MathPiperIDE?

Two of MathPiperIDE's main inspirations are Scott McNeally's concept of "No child held back":

http://weblogs.java.net/blog/turbogeek/archive/2004/09/no_child_held_b_1.html

and Steve Yegge's thoughts on learning mathematics:

1) Math is a lot easier to pick up after you know how to program. In fact, if you're a halfway decent programmer, you'll find it's almost a snap.

2) The right way to learn math is breadth-first, not depth-first. You need to survey the space, learn the names of things, figure out what's what.

http://steve-yegge.blogspot.com/2006/03/math-for-programmers.html

9596979899

100101

102

103104

105

106

107108

109110

111

Page 13: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 13/140

3 Downloading And Installing MathPiperIDE

3.1 Installing Sun's Java Implementation

MathPiperIDE is a Java-based application and therefore a current version of Sun's Java (at least Java 6) must be installed on your computer before MathPiperIDE can be run.

3.1.1 Installing Java On A Windows PCMany Windows PCs will already have a current version of Java installed. You can test to see if you have a current version of Java installed by visiting the following web site:

http://java.com/

This web page contains a link called "Do I have Java?" which will check your Java version and tell you how to update it if necessary.

3.1.1.1 The 64 Bit Version Of Windows Needs The 64 Bit Version Of Java

If you are using the 64 bit version of Windows, then you will need the 64 bit version of Java. The 64 bit version of Java can be obtained here:

https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/ViewProductDetail-Start?ProductRef=jre-6u16-oth-JPR@CDS-CDS_Developer

3.1.2 Installing Java On A MacintoshMacintosh computers have Java pre-installed but you may need to upgrade to a current version of Java (at least Java 6) before running MathPiperIDE. If you need to update your version of Java, visit the following website:

http://developer.apple.com/java.

3.1.3 Installing Java On A Linux PCLocate the Java documentation for your Linux distribution and carefully follow the instructions provided for installing a Java 6 compatible version of Java on your system.

3.2 Downloading And Extracting

One of the many benefits of learning MathPiperIDE is the programming-related

112

113

114115116

117

118119120

121

122123

124

125126

127128129

130

131132133

134

135

136137138

139

140

Page 14: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 14/140

knowledge one gains about how open source software is developed on the Internet. An important enabler of open source software development are websites, such as sourceforge.net (http://sourceforge.net) and java.net (http://java.net) which make software development tools available for free to open source developers.

MathPiperIDE is hosted at Google and the URL for the project website is:

http://code.google.com/p/mathpiper

MathPiperIDE can be obtained by selecting the downloads tab and choosing the correct download file for your computer. Place the download file on your hard drive where you want MathPiperIDE to be located. For Windows users, it is recommended that MathPiperIDE be placed somewhere on c: drive.

The MathPiperIDE download consists of a main directory (or folder) called mathpiperide which contains a number of directories and files. In order to make downloading quicker and sharing easier, the mathpiperide directory (and all of its contents) have been placed into a single compressed file called an archive. For Windows systems, the archive has a .zip extension and the archives for Unix-based systems have a .tar.bz2 extension.

After an archive has been downloaded onto your computer, the directories and files it contains must be extracted from it. The process of extraction uncompresses copies of the directories and files that are in the archive and places them on the hard drive, usually in the same directory as the archive file. After the extraction process is complete, the archive file will still be present on your drive along with the extracted MathPiperIDE directory and its contents.

The archive file can be easily copied to a CD or USB drive if you would like to install MathPiperIDE on another computer or give it to a friend. However, don't try to run MathPiperIDE from a USB drive because it will not work correctly.

(Note: If you already have a version of MathPiperIDE installed and you want to install a new version in the same directory that holds the old version, you must delete the old version first or move it to a separate directory.)

3.2.1 Extracting The Archive File For Windows UsersUsually the easiest way for Windows users to extract the MathPiperIDE archive file is to navigate to the folder which contains the archive file (using the Windows GUI), right click on the archive file (it should appear as a folder with a vertical zipper on it), and select Extract All... from the pop up menu.

After the extraction process is complete, a new folder called MathPiperIDE should be present in the same folder that contains the archive file. (Note: be careful not to double click on the archive file by mistake when you are

141142143144145

146

147

148149150151

152153154155156157

158159160161162163

164165166167

168169170171

172

173174175176

177178179

Page 15: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 15/140

trying to open the MathPiperIDE folder. The Windows operating system will open the archive just like it opens folders and this can fool you into thinking you are opening the MathPiperIDE folder when you are not. You may want to move the archive file to another place on your hard drive after it has been extracted to avoid this potential confusion.)

3.2.2 Extracting The Archive File For Unix UsersOne way Unix users can extract the download file is to open a shell, change to the directory that contains the archive file, and extract it using the following command:

tar -xvjf <name of archive file>

If your desktop environment has GUI-based archive extraction tools, you can use these as an alternative.

3.3 MathPiperIDE's Directory Structure & Execution InstructionsThe top level of MathPiperIDE's directory structure is shown in Illustration 1:

The following is a brief description this top level directory structure:

doc - Contains MathPiperIDE's documentation files.

examples - Contains various example programs, some of which are pre-opened when MathPiperIDE is first executed.

jars - Holds plugins, code libraries, and support scripts.

macros - Contains various scripts that can be executed by the user.

modes - Contains files which tell MathPiperIDE how to do syntax highlighting for various file types.

settings - Contains the application's main settings files.

startup - Contains startup scripts that are executed each time MathPiperIDE launches.

jedit.jar - Holds the core jEdit application which MathPiperIDE builds upon.

Illustration 1: MathPiperIDE's Directory Structure

doc examples jars macros modes settings startup jedit.jar unix_run.sh win_run.bat

mathrider

180181182183184

185

186187188

189

190191

192

193

194

195

196197

198

199

200201

202

203204

205

Page 16: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 16/140

unix_run.sh - The script used to execute MathPiperIDE on Unix systems.

win_run.bat - The batch file used to execute MathPiperIDE on Windows systems.

3.3.1 Executing MathPiperIDE On Windows SystemsOpen the MathPiperIDE folder (not the archive file!) and double click on the win_run file.

3.3.2 Executing MathPiperIDE On Unix SystemsOpen a shell, change to the MathPiperIDE folder, and execute the unix_run.sh script by typing the following:

sh unix_run.sh

3.3.2.1 MacOS X

Make a note of where you put the MathPiperIDE application (for example /Applications/MathPiperIDE). Run Terminal (which is in /Applications/Utilities). Change to that directory (folder) by typing:

cd /Applications/MathPiperIDE

Run MathPiperIDE by typing:

sh unix_run.sh

206

207208

209

210211

212

213214

215

216

217218219

220

221

222

Page 17: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 17/140

4 The Graphical User InterfaceMathPiperIDE is built on top of jEdit (http://jedit.org) so it has the "heart" of a programmer's text editor. Programmer's text editors are similar to standard text editors (like NotePad and WordPad) and word processors (like MS Word and OpenOffice) in a number of ways so getting started with MathPiperIDE should be relatively easy for anyone who has used a text editor or a word processor. However, programmer's text editors are more challenging to use than a standard text editor or a word processor because programmer's text editors have capabilities that are far more advanced than these two types of applications.

Most software is developed with a programmer's text editor (or environments which contain one) and so learning how to use a programmer's text editor is one of the many skills that MathPiperIDE provides which can be used in other areas. The MathPiperIDE series of books are designed so that these capabilities are revealed to the reader over time.

In the following sections, the main parts of MathPiperIDE's graphical user interface are briefly covered. Some of these parts are covered in more depth later in the book and some are covered in other books.

As you read through the following sections, I encourage you to explore each part of MathPiperIDE that is being discussed using your own copy of MathPiperIDE.

4.1 Buffers And Text Areas

In MathPiperIDE, open files are called buffers and they are viewed through one or more text areas. Each text area has a tab at its upper-left corner which displays the name of the buffer it is working on along with an indicator which shows whether the buffer has been saved or not. The user is able to select a text area by clicking its tab and double clicking on the tab will close the text area. Tabs can also be rearranged by dragging them to a new position with the mouse.

4.2 The Gutter

The gutter is the vertical gray area that is on the left side of the main window. It can contain line numbers, buffer manipulation controls, and context-dependent information about the text in the buffer.

4.3 Menus

The main menu bar is at the top of the application and it provides access to a significant portion of MathPiperIDE's capabilities. The commands (or actions) in these menus all exist separately from the menus themselves and they can be executed in alternate ways (such as keyboard shortcuts). The menu items (and

223

224225226227228229230231

232233234235236

237238239

240241242

243

244245246247248249

250

251252253

254

255256257258

Page 18: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 18/140

even the menus themselves) can all be customized, but the following sections describe the default configuration.

4.3.1 FileThe File menu contains actions which are typically found in normal text editors and word processors. The actions to create new files, save files, and open existing files are all present along with variations on these actions.

Actions for opening recent files, configuring the page setup, and printing are also present.

4.3.2 EditThe Edit menu also contains actions which are typically found in normal text editors and word processors (such as Undo, Redo, Cut, Copy, and Paste). However, there are also a number of more sophisticated actions available which are of use to programmers. For beginners, though, the typical actions will be sufficient for most editing needs.

4.3.3 SearchThe actions in the Search menu are used heavily, even by beginners. A good way to get your mind around the search actions is to open the Search dialog window by selecting the Find... action (which is the first actions in the Search menu). A Search And Replace dialog window will then appear which contains access to most of the search actions.

At the top of this dialog window is a text area labeled Search for which allows the user to enter text they would like to find. Immediately below it is a text area labeled Replace with which is for entering optional text that can be used to replace text which is found during a search.

The column of radio buttons labeled Search in allows the user to search in a Selection of text (which is text which has been highlighted), the Current Buffer (which is the one that is currently active), All buffers (which means all opened files), or a whole Directory of files. The default is for a search to be conducted in the current buffer and this is the mode that is used most often.

The column of check boxes labeled Settings allows the user to either Keep or hide the Search dialog window after a search is performed, Ignore the case of searched text, use an advanced search technique called a Regular expression search (which is covered in another book), and to perform a HyperSearch (which collects multiple search results in a text area).

The Find button performs a normal find operation. Replace & Find will replace the previously found text with the contents of the Replace with text area and perform another find operation. Replace All will find all occurrences of the

259260

261

262263264

265266

267

268269270271272

273

274275276277278

279280281282

283284285286287

288289290291292

293294295

Page 19: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 19/140

contents of the Search for text area and replace them with the contents of the Replace with text area.

4.3.4 Markers, Folding, and ViewThese are advanced menus and they are described in later sections.

4.3.5 UtilitiesThe utilities menu contains a significant number of actions, some that are useful to beginners and others that are meant for experts. The two actions that are most useful to beginners are the Buffer Options actions and the Global Options actions. The Buffer Options actions allows the currently selected buffer to be customized and the Global Options actions brings up a rich dialog window that allows numerous aspects of the MathPiperIDE application to be configured.

Feel free to explore these two actions in order to learn more about what they do.

4.3.6 MacrosThis is an advanced menu and it is described in a later sections.

4.3.7 PluginsPlugins are component-like pieces of software that are designed to provide an application with extended capabilities and they are similar in concept to physical world components. The tabs on the right side of the application which are labeled "GeoGebra", "Jung', "MathPiper", "MathPiperDocs", etc. are all plugins and they can be opened and closed by clicking on their tabs. Feel free to close any of these plugins which may be opened if you are not currently using them. MathPiperIDE pPlugins are covered in more depth in a later section.

4.3.8 HelpThe most important action in the Help menu is the MathPiperIDE Help action. This action brings up a dialog window with contains documentation for the core MathPiperIDE application along with documentation for each installed plugin.

4.4 The Toolbar

The Toolbar is located just beneath the menus near the top of the main window and it contains a number of icon-based buttons. These buttons allow the user to access the same actions which are accessible through the menus just by clicking on them. There is not room on the toolbar for all the actions in the menus to be

296297

298

299

300

301302303304305306307

308

309

310

311

312313314315316317318

319

320321322

323

324325326327

Page 20: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 20/140

displayed, but the most common actions are present. The user also has the option of customizing the toolbar by using the Utilities->Global Options->Tool Bar dialog.

4.4.1 Undo And RedoThe Undo button on the toolbar is able to undo any text was entered since the current session of MathPiperIDE was launched. This is very handy for undoing mistakes or getting back text which was deleted. The Redo button can be used if you have selected Undo too many times and you need to "undo" one ore more Undo operations.

328329330

331

332333334335336

Page 21: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 21/140

5 MathPiper: A Computer Algebra System For BeginnersComputer algebra systems are extremely powerful and very useful for solving STEM-related problems. In fact, one of the reasons for creating MathPiperIDE was to provide a vehicle for delivering a computer algebra system to as many people as possible. If you like using a scientific calculator, you should love using a computer algebra system!

At this point you may be asking yourself "if computer algebra systems are so wonderful, why aren't more people using them?" One reason is that most computer algebra systems are complex and difficult to learn. Another reason is that proprietary systems are very expensive and therefore beyond the reach of most people. Luckily, there are some open source computer algebra systems that are powerful enough to keep most people engaged for years, and yet simple enough that even a beginner can start using them. MathPiper (which is based on a CAS called Yacas) is one of these simpler computer algebra systems and it is the computer algebra system which is included by default with MathPiperIDE.

A significant part of this book is devoted to learning MathPiper and a good way to start is by discussing the difference between numeric and symbolic computations.

5.1 Numeric Vs. Symbolic Computations

A Computer Algebra System (CAS) is software which is capable of performing both numeric and symbolic computations. Numeric computations are performed exclusively with numerals and these are the type of computations that are performed by typical hand-held calculators.

Symbolic computations (which also called algebraic computations) relate "...to the use of machines, such as computers, to manipulate mathematical equations and expressions in symbolic form, as opposed to manipulating the approximations of specific numerical quantities represented by those symbols." (http://en.wikipedia.org/wiki/Symbolic_mathematics).

Since most people who read this document will probably be familiar with performing numeric calculations as done on a scientific calculator, the next section shows how to use MathPiper as a scientific calculator. The section after that then shows how to use MathPiper as a symbolic calculator. Both sections use the console interface to MathPiper. In MathPiperIDE, a console interface to any plugin or application is a text-only shell or command line interface to it. This means that you type on the keyboard to send information to the console and it prints text to send you information.

337

338339340341342

343344345346347348349350351

352353354

355

356357358359

360361362363364

365366367368369370371372

Page 22: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 22/140

5.2 Using The MathPiper Console As A Numeric (Scientific) Calculator

Open the MathPiper plugin by selecting the MathPiper tab in the lower left part of the MathPiperIDE application and place it into "Code Result" mode. The MathPiper console interface is a text area which is inside this plugin. Feel free to increase or decrease the size of the console text area if you would like by dragging on the dotted lines which are at the top side and right side of the console window.

When the MathPiper console is first launched, it prints a welcome message and then provides In> as an input prompt:

MathPiper version ".80?".

In>

Click to the right of the prompt in order to place the cursor there then type 2+2 followed by <enter> (or <return> on a Macintosh):

In> 2+2Result> 4

In>

When <enter> was pressed, 2+2 was read into MathPiper for evaluation and Result> was printed followed by the result 4. Another input prompt was then displayed so that further input could be entered. This input, evaluation, output process will continue as long as the console is running and it is sometimes called a Read, Eval, Print Loop or REPL. In further examples, the last In> prompt will not be shown to save space.

In addition to addition, MathPiper can also do subtraction, multiplication, exponents, and division:

In> 5-2Result> 3

In> 3*4Result> 12

In> 2^3Result> 8

In> 12/6Result> 2

Notice that the multiplication symbol is an asterisk (*), the exponent symbol is a caret (^), and the division symbol is a forward slash (/). These symbols (along

373

374375376377378379

380381

382

383

384385

386387

388

389390391392393394

395396

397398

399400

401402

403404

405406

Page 23: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 23/140

with addtion (+) , subtraction (−), and ones we will talk about later) are called operators because they tell MathPiper to perform an operation such as addition or division.

MathPiper can also work with decimal numbers:

In> .5+1.2Result> 1.7

In> 3.7-2.6Result> 1.1

In> 2.2*3.9Result> 8.58

In> 2.2^3Result> 10.648

In> 1/2Result> 1/2

In the last example, MathPiper returned the fraction unevaluated. This sometimes happens due to MathPiper's symbolic nature, but a result in numeric form can be obtained by using the N() function (which is discussed in the next section):

In> N(1/2)Result> 0.5

As can be seen here, when a result is given in numeric form, it means that it is given as a decimal number. A numeric result could also be obtained by using a decimal point either after the 1 or the 2 (or both of them):

In> 1./2Result> 0.5

In> 1/2.Result> 0.5

In> 1./2.Result> 0.5

When one or more decimal numbers are used in a calculation, MathPiper will usually return a numeric result.

5.2.1 FunctionsN() is an example of a function. A function can be thought of as a "black box"

407408409

410

411412

413414

415416

417418

419420

421422423424

425426

427428429

430431

432433

434435

436437

438

439

Page 24: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 24/140

which accepts input, processes the input, and returns a result. Each function has a name and in this case, the name of the function is N which stands for "numeric". To the right of a function's name there is always a set of parentheses and information that is sent to the function is placed inside of them. The purpose of the N() function is to make sure that the information that is sent to it is processed numerically instead of symbolically. Functions are used by evaluating them and this happens when <enter> is pressed. Another name for evaluating a function is calling it.

5.2.1.1 The Sqrt() Square Root Function

The following example show the N() function being used with the square root function Sqrt():

In> Sqrt(9)Result: 3

In> Sqrt(8)Result: Sqrt(8)

In> N(Sqrt(8))Result: 2.828427125

Notice that Sqrt(9) returned 3 as expected but Sqrt(8) returned Sqrt(8). We needed to use the N() function to force the square root function to return a numeric result. The reason that Sqrt(8) does not appear to have done anything is because computer algebra systems like to work with expressions that are as exact as possible. In this case the symbolic value Sqrt(8) represents the number that is the square root of 8 more accurately than any decimal number can.

For example, the following four decimal numbers all represent 8 , but none of them represent it more accurately than Sqrt(8) does:

2.828427125

2.82842712474619

2.82842712474619009760337744842

2.8284271247461900976033774484193961571393437507539

Whenever MathPiper returns a symbolic result and a numeric result is desired, simply use the N() function to obtain one. The ability to work with symbolic values are one of the things that make computer algebra systems so powerful and they are discussed in more depth in later sections.

5.2.1.2 The IsEven() Function

Another often used function is IsEven(). The IsEven() function takes a number

440441442443444445446447

448

449450

451452

453454

455456

457458459460461462

463464

465

466

467

468

469470471472

473

474

Page 25: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 25/140

as input and returns True if the number is even and False if it is not even:

In> IsEven(4)Result> True

In> IsEven(5)Result> False

MathPiper has a large number of functions some of which are described in more depth in the MathPiper Documentation section and the MathPiper Programming Fundamentals section. A complete list of MathPiper's functions is contained in the MathPiperDocs plugin and more of these functions will be discussed soon.

5.2.2 Accessing Previous Input And ResultsThe MathPiper console is like a mini text editor which means you can copy text from it, paste text into it, and edit existing text. You can also reevaluate previous input by simply placing the cursor on the desired In> line and pressing <enter> on it again.

The console also keeps a history of all input lines that have been evaluated. If the cursor is placed on any In> line, pressing <ctrl><up arrow> will display each previous line of input that has been entered.

Finally, MathPiper associates the most recent computation result with the percent (%) character. If you want to use the most recent result in a new calculation, access it with this character:

In> 5*8Result> 40

In> %Result> 40

In> %*2Result> 80

5.3 Saving And Restoring A Console Session

If you need to save the contents of a console session, you can copy and paste it into a MathPiperIDE buffer and then save the buffer. You can also copy a console session out of a previously saved buffer and paste it into the console for further processing. Section 7 Using MathPiperIDE As A Programmer's Text Editor discusses how to use the text editor that is built into MathPiperIDE.

475

476477

478479

480481482483484

485

486487488489

490491492

493494495

496497

498499

500501

502

503504505506507

Page 26: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 26/140

5.3.1 Syntax Errors

An expression's syntax is related to whether it is typed correctly or not. If input is sent to MathPiper which has one or more typing errors in it, MathPiper will return an error message which is meant to be helpful for locating the error. For example, if a backwards slash (\) is entered for division instead of a forward slash (/), MathPiper returns the following error message:

In> 12 \ 6

Exception: Error encountered during initialization or parsing: Expecting ; end of statement in program block, but got \ instead.

To fix this problem, change the \ to a /, and reevaluate the expression.

This section provided a short introduction to using MathPiper as a numeric calculator and the next section contains a short introduction to using MathPiper as a symbolic calculator.

5.4 Using The MathPiper Console As A Symbolic Calculator

MathPiper is good at numeric computation, but it is great at symbolic computation. If you have never used a system that can do symbolic computation, you are in for a treat!

As a first example, lets try adding fractions (which are also called rational

numbers). Add1213 in the MathPiper console:

In> 1/2 + 1/3Result> 5/6

Instead of returning a numeric result like 0.83333333333333333333 (which is what a scientific calculator would return) MathPiper added these two rational

numbers symbolically and returned56 . If you want to work with this result

further, remember that it has also been stored in the % symbol:

In> %Result> 5/6

Lets say that you would like to have MathPiper determine the numerator of this result. This can be done by using (or calling) the Numerator() function:

In> Numerator(%)Result> 5

508

509510511512513

514

515516

517

518519520

521

522523524

525

526

527528

529530

531

532

533534

535536

537538

Page 27: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 27/140

Unfortunately, the % symbol cannot be used to have MathPiper determine the

denominator of 56 because it only holds the result of the most recent

calculation and56 was calculated two steps back.

5.4.1 VariablesWhat would be nice is if MathPiper provided a way to store results (which are also called values) in symbols that we choose instead of ones that it chooses. Fortunately, this is exactly what it does! Symbols that can be associated with values are called variables. Variable names must start with an upper or lower case letter and be followed by zero or more upper case letters, lower case letters, or numbers. Examples of variable names include: 'a', 'b', 'x', 'y', 'answer', 'totalAmount', and 'loop6'.

The process of associating a value with a variable is called assigning or binding the value to the variable and this consists of placing the name of a variable you would like to create on the left side of an assignment operator (:=) and an expression on the right side of this operator. When the expression returns a value, the value is assigned (or bound to) to the variable.

Lets recalculate1213 but this time we will assign the result to the variable 'a':

In> a := 1/2 + 1/3Result> 5/6

In> aResult> 5/6

In> Numerator(a)Result> 5

In> Denominator(a)Result> 6

In this example, the assignment operator (:=) was used to assign the result (or

value)56 to the variable 'a'. When 'a' was evaluated by itself, the value it

was bound to (in this case56 ) was returned. This value will stay bound to

the variable 'a' as long as MathPiper is running unless 'a' is cleared with the Unbind() function or 'a' has another value assigned to it. This is why we were able to determine both the numerator and the denominator of the rational number assigned to 'a' using two functions in turn. (Note: there can be no spaces between the : and the =)

539

540

541

542

543544545546547548549

550551552553554

555

556557

558559

560561

562563

564

565

566

567568569570571

Page 28: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 28/140

5.4.1.1 Calculating With Unbound Variables

Here is an example which shows another value being assigned to 'a':

In> a := 9Result> 9

In> aResult> 9

and the following example shows 'a' being cleared (or unbound) with the Unbind() function:

In> Unbind(a)Result> True

In> aResult> a

Notice that the Unbind() function returns 'True' as a result after it is finished to indicate that the variable that was sent to it was successfully cleared (or unbound). Many functions either return 'True' or 'False' to indicate whether or not the operation they performed succeeded. Also notice that unbound variables return themselves when they are evaluated. In this case, 'a' returned 'a'.

All currently bound variables can be unbound by passing the * symbol to Unbind:

In> a := 1Result: 1

In> b := 2Result: 2

In> aResult: 1

In> bResult: 2

In> Unbind(*)Result: True

In> aResult: a

In> bResult: b

572

573

574575

576577

578579

580581

582583

584585586587588

589590

591592

593594

595596

597598

599600

601602

603604

Page 29: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 29/140

Unbound variables may not appear to be very useful, but they provide the flexibility needed for computer algebra systems to perform symbolic calculations. In order to demonstrate this flexibility, lets first factor some numbers using the Factor() function:

In> Factor(8)Result> 2^3

In> Factor(14)Result> 2*7

In> Factor(2343)Result> 3*11*71

Now lets factor an expression that contains the unbound variable 'x':In> xResult> x

In> IsBound(x)Result> False

In> Factor(x^2 + 24*x + 80)Result> (x+4)*(x+20)

In> Expand(%)Result> x^2+24*x+80

Evaluating 'x' by itself shows that it does not have a value bound to it and this can also be determined by passing 'x' to the IsBound() function. IsBound() returns 'True' if a variable is bound to a value and 'False' if it is not.

What is more interesting, however, are the results returned by Factor() and Expand(). Factor() is able to determine when expressions with unbound variables are sent to it and it uses the rules of algebra to manipulate them into factored form. The Expand() function was then able to take the factored expression x20 x4 and manipulate it until it was expanded. One way to remember what the functions Factor() and Expand() do is to look at the second letters of their names. The 'a' in Factor can be thought of as adding parentheses to an expression and the 'x' in Expand can be thought of xing out or removing parentheses from an expression.

5.4.1.2 Variable And Function Names Are Case Sensitive

MathPiper variables are case sensitive. This means that MathPiper takes into account the case of each letter in a variable name when it is deciding if two or more variable names are the same variable or not. For example, the variable name Box and the variable name box are not the same variable because the first variable name starts with an upper case 'B' and the second variable name starts

605606607608

609610

611612

613614

615616617

618619

620621

622623

624625626

627628629630631632633634635

636

637638639640641

Page 30: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 30/140

with a lower case 'b':

In> Box := 1Result> 1

In> box := 2Result> 2

In> BoxResult> 1

In> boxResult> 2

5.4.1.3 Using More Than One Variable

Programs are able to have more than 1 variable and here is a more sophisticated example which uses 3 variables:

a := 2Result> 2

b := 3Result> 3

a + bResult> 5

answer := a + bResult> 5

answerResult> 5

The part of an expression that is on the right side of an assignment operator is always evaluated first and the result is then assigned to the variable that is on the left side of the operator.

Now that you have seen how to use the MathPiper console as both a symbolic and a numeric calculator, our next step is to take a closer look at the functions which are included with MathPiper. As you will soon discover, MathPiper contains an amazing number of functions which deal with a wide range of mathematics.

642

643644

645646

647648

649650

651

652653

654655

656657

658659

660661

662663

664665666

667668669670671

Page 31: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 31/140

5.5 Exercises

Use the MathPiper console which is at the bottom of the MathPiperIDE application to complete the following exercises.

5.5.1 Exercise 1Carefully read all of section 5. Evaluate each one of the examples in section 5 in the MathPiper console and verify that the results match the ones in the book.

5.5.2 Exercise 2Answer each one of the following questions:

a) What is the purpose of the N() function?

b) What is a variable?

c) Are the variables 'x' and 'X' the same variable?

d) What is the difference between a bound variable and an unbound variable?

e) How can you tell if a variable is bound or not?

f) How can a variable be bound to a value?

g) How can a variable be unbound from a value?

h) What does the % character do?

5.5.3 Exercise 3Perform the following calculation:

1438−716

5.5.4 Exercise 4

a) Assign the variable answer to the result of the calculation 15741516

using the following line of code:

In> answer := 1/5 + 7/4 + 15/16b) Use the Numerator() function to calculate the numerator of answer.c) Use the Denominator() function to calculate the denominator of answer.

672

673674

675676677678

679680

681

682

683

684

685

686

687

688

689690

691

692

693

694

695

696

Page 32: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 32/140

d) Use the N() function to calculate the numeric value of answer.e) Use the Unbind() function to unbind the variable answer and verify that answer is unbound by executing the following code and by using the IsBound() function:

In> answer

5.5.5 Exercise 5

Assign 14

to variable x, 38

to variable y, and 716

to variable z using the := operator. Then perform the following calculations:a)In> x

b)In> y

c)In> z

d)In> x + y

e)In> x + z

f)In> x + y + z

697

698699700

701

702

703

704

705706

707708

709710

711712

713714

715716

Page 33: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 33/140

6 The MathPiper Documentation PluginMathPiper has a significant amount of reference documentation written for it and this documentation has been placed into a plugin called MathPiperDocs in order to make it easier to navigate. The MathPiperDocs plugin is available in a tab called "MathPiperDocs" which is near the right side of the MathPiperIDE application. Click on this tab to open the plugin and click on it again to close it.

The left side of the MathPiperDocs window contains the names of all the functions that come with MathPiper and the right side of the window contains a mini-browser that can be used to navigate the documentation.

6.1 Function List

MathPiper's functions are divided into two main categories called user functions and programmer functions. In general, the user functions are used for solving problems in the MathPiper console or with short programs and the programmer functions are used for longer programs. However, users will often use some of the programmer functions and programmers will use the user functions as needed.

Both the user and programmer function names have been placed into a "tree" on the left side of the MathPiperDocs window to allow for easy navigation. The branches of the function tree can be opened and closed by clicking on the small "circle with a line attached to it" symbol which is to the left of each branch. Both the user and programmer branches have the functions they contain organized into categories and the top category in each branch lists all the functions in the branch in alphabetical order for quick access. Clicking on a function will bring up documentation about it in the browser window and selecting the Collapse button at the top of the plugin will collapse the tree.

Don't be intimidated by the large number of categories and functions that are in the function tree! Most MathPiperIDE beginners will not know what most of them mean, and some will not know what any of them mean. Part of the benefit MathPiperIDE provides is exposing the user to the existence of these categories and functions. The more you use MathPiperIDE, the more you will learn about these categories and functions and someday you may even get to the point where you understand all of them. This book is designed to show newbies how to begin using these functions using a gentle step-by-step approach.

6.2 Mini Web Browser Interface

MathPiper's reference documentation is in HTML (or web page) format and so the right side of the plugin contains a mini web browser that can be used to navigate through these pages. The browser's home page contains links to the

717

718719720721722

723724725

726

727728729730731732

733734735736737738739740741

742743744745746747748749750

751

752753754

Page 34: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 34/140

main parts of the MathPiper documentation. As links are selected, the Back and Forward buttons in the upper right corner of the plugin allow the user to move backward and forward through previously visited pages and the Home button navigates back to the home page.

The function names in the function tree all point to sections in the HTML documentation so the user can access function information either by navigating to it with the browser or jumping directly to it with the function tree.

6.3 Exercises

6.3.1 Exercise 1Carefully read all of section 6. Locate the N(), IsEven(), IsOdd(), Unbind(), IsBound(), Numerator(), Denominator(), and Factor() functions in the All Functions section of the MathPiperDocs plugin and read the information that is available on them. List the one line descriptions which are at the top of the documentation for each of these functions.

6.3.2 Exercise 2Locate the N(), IsEven(), IsOdd(), Unbind(), IsBound(), Numerator(), Denominator(), and Factor() functions in the User Functions section of the MathPiperDocs plugin and list which category each function is contained in. Don't include the Alphabetical or Built In categories in your search. For example, the N() function is in the Numbers (Operations) category.

755756757758

759760761

762

763764765766767768

769770771772773774

Page 35: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 35/140

7 Using MathPiperIDE As A Programmer's Text EditorWe have covered some of MathPiperIDE's mathematics capabilities and this section discusses some of its programming capabilities. As indicated in a previous section, MathPiperIDE is built on top of a programmer's text editor but what wasn't discussed was what an amazing and powerful tool a programmer's text editor is.

Computer programmers are among the most intelligent and productive people in the world and most of their work is done using a programmer's text editor (or something similar to one). Programmers have designed programmer's text editors to be super-tools which can help them maximize their personal productivity and these tools have all kinds of capabilities that most people would not even suspect they contained.

Even though this book only covers a small part of the editing capabilities that MathPiperIDE has, what is covered will enable the user to begin writing useful programs.

7.1 Creating, Opening, Saving, And Closing Text Files

A good way to begin learning how to use MathPiperIDE's text editing capabilities is by creating, opening, and saving text files. A text file can be created either by selecting File->New from the menu bar or by selecting the icon for this operation on the tool bar. When a new file is created, an empty text area is created for it along with a new tab named Untitled.

The file can be saved by selecting File->Save from the menu bar or by selecting the Save icon in the tool bar. The first time a file is saved, MathPiperIDE will ask the user what it should be named and it will also provide a file system navigation window to determine where it should be placed. After the file has been named and saved, its name will be shown in the tab that previously displayed Untitled.

A file can be closed by selecting File->Close from the menu bar and it can be opened by selecting File->Open.

7.2 Editing Files

If you know how to use a word processor, then it should be fairly easy for you to learn how to use MathPiperIDE as a text editor. Text can be selected by dragging the mouse pointer across it and it can be cut or copied by using actions in the Edit menu (or by using <Ctrl>x and <Ctrl>c). Pasting text can be done using the Edit menu actions or by pressing <Ctrl>v.

775

776777778779780

781782783784785786

787788789

790

791792793794795

796797798799800

801802

803

804805806807808

Page 36: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 36/140

7.3 File Modes

Text file names are suppose to have a file extension which indicates what type of file it is. For example, test.txt is a generic text file, test.bat is a Windows batch file, and test.sh is a Unix/Linux shell script (unfortunately, Windows is usually configured to hide file extensions, but viewing a file's properties by right-clicking on it will show this information.).

MathPiperIDE uses a file's extension type to set its text area into a customized mode which highlights various parts of its contents. For example, MathPiperIDE worksheet files have a .mpw extension and MathPiperIDE knows what colors to highlight the various parts of a .mpw file in.

7.4 Learning How To Type Properly Is An Excellent Investment Of Your Time

This is a good place in the document to mention that learning how to type properly is an investment that will pay back dividends throughout your whole life. Almost any work you do on a computer (including programming) will be done much faster and with less errors if you know how to type properly. Here is what Steve Yegge has to say about this subject:

"If you are a programmer, or an IT professional working with computers in any capacity, you need to learn to type! I don't know how to put it any more clearly than that."

A good way to learn how to type is to locate a free "learn how to type" program on the web and use it.

7.5 Exercises

7.5.1 Exercise 1Carefully read all of section 7. Create a text file called "my_text_file.txt" and place a few sentences in it. Save the text file somewhere on your hard drive then close it. Now, open the text file again using File->Open and verify that what you typed is still in the file.

809

810811812813814

815816817818

819820

821822823824825

826827828

829830

831

832833834835836

Page 37: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 37/140

8 MathPiperIDE Worksheet FilesWhile MathPiperIDE's ability to execute code inside a console provides a significant amount of power to the user, most of MathPiperIDE's power is derived from worksheets. MathPiperIDE worksheets are text files which have a .mpw extension and are able to execute multiple types of code in a single text area. The worksheet_demo_1.mpw file (which is preloaded in the MathPiperIDE environment when it is first launched) demonstrates how a worksheet is able to execute multiple types of code in what are called code folds.

8.1 Code Folds

Code folds are named sections inside a MathPiperIDE worksheet which contain source code that can be executed by placing the cursor inside of it and pressing <shift><Enter>. A fold always begins with a start tag, which starts with a percent symbol (%) followed by the name of the fold type (like this: %<foldtype>). The end of a fold is marked by an end tag which looks like %/<foldtype>. The only difference between a fold's start tag and its end tag is that the end tag has a slash (/) after the %.

For example, here is a MathPiper fold which will print the result of 2 + 3 to the MathPiper console (Note: the semicolon ';' which is at the end of the line of code is required):

%mathpiper

2 + 3;

%/mathpiper

The output generated by a fold (called the parent fold) is wrapped in a new fold (called a child fold) which is indented and placed just below the parent. This can be seen when the above fold is executed by pressing <shift><enter> inside of it:

%mathpiper

2 + 3;

%/mathpiper

%output,preserve="false" Result: 5. %/output

The most common type of output fold is %output and by default folds of type

837

838839840841842843844

845

846847848849850851852

853854855

856

857

858

859860861862

863

864

865

866867868

869

Page 38: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 38/140

%output have their preserve property set to false. This tells MathPiperIDE to overwrite the %output fold with a new version during the next execution of its parent. If preserve is set to true, the fold will not be overwritten and a new fold will be created instead.

There are other kinds of child folds, but in the rest of this document they will all be referred to in general as "output" folds.

8.1.1 The title AttributeFolds can also have what is called a "title attribute" placed after the start tag which describes what the fold contains. For example, the following %mathpiper fold has a title attribute which indicates that the fold adds two number together:

%mathpiper,title="Add two numbers together."

2 + 3;

%/mathpiper

The title attribute is added to the start tag of a fold by placing a comma after the fold's type name and then adding the text title="<text>" after the comma. (Note: no spaces can be present before or after the comma (,) or the equals sign (=) ).

8.2 Automatically Inserting Folds & Removing Unpreserved Folds

Typing the top and bottom fold lines (for example:

%mathpiper

%/mathpiper

can be tedious and MathPiperIDE has a way to automatically insert them. Place the cursor at the beginning of a blank line in a .mpw worksheet file where you would like a fold inserted and then press the right mouse button.

A popup menu will be displayed and at the top of this menu are items which read "Insert MathPiper Fold", "Insert Group Fold", etc. If you select one of these menu items, an empty code fold of the proper type will automatically be inserted into the .mpw file at the position of the cursor.

This popup menu also has a menu item called "Remove Unpreserved Folds". If this menu item is selected, all folds which have a "preserve="false"" property will be removed.

870871872873

874875

876

877878879

880

881

882

883884885886

887

888

889

890

891892893

894895896897

898899900

Page 39: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 39/140

8.3 Placing Text Outside Of A Fold

Text can also be placed outside of a fold like the following example shows:

Text can be placed above folds like this.

text text text texttext text text text

%mathpiper,title="Fold 1"

2 + 3;

%/mathpiper

Text can be placed between folds like this.

text text text texttext text text text

%mathpiper,title="Fold 2"

3 + 4;

%/mathpiper

Text can be placed between folds like this.

text text text texttext text text text

Placing text outside a fold is useful for describing what is being done in certain folds and it is also good for saving work that has been done in the MathPiper console.

8.4 Exercises

A MathPiperIDE worksheet file called "newbies_book_examples_1.mpw" is included in the mathpiperide/examples directory and it is opened by default when the software is first launched after it is downloaded. It contains a number of %mathpiper folds which contain code examples from the previous sections of this book. Notice that all of the lines of code have a semicolon (;) placed after them. The reason this is needed is explained in a later section.

Download this worksheet file to your computer from the section on this website that contains the highest revision number and then open it in MathPiperIDE.

901

902

903

904905

906

907

908

909

910911

912

913

914

915

916917

918919920

921

922923924925926927

928929

Page 40: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 40/140

Then, use the worksheet to do the following exercises.

8.4.1 Exercise 1Carefully read all of section 8. Execute folds 1-8 in the top section of the worksheet by placing the cursor inside of the fold and then pressing <shift><enter> on the keyboard.

8.4.2 Exercise 2The code in folds 9 and 10 have errors in them. Fix the errors and then execute the folds again.

8.4.3 Exercise 3Use the empty fold 11 to calculate the expression 100 - 23;

8.4.4 Exercise 4Perform the following calculations by creating new folds at the bottom of the worksheet (using the right-click popup menu) and placing each calculation into its own fold:

a) 2*7 + 3

b) 18/3

c) 234238342 + 2038408203

d) 324802984 * 2308098234

e) Factor the result which was calculated in d).

930

931932933934

935936937

938

939

940941942943

944

945

946

947

948

Page 41: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 41/140

9 MathPiper Programming FundamentalsThe MathPiper language consists of expressions and an expression consists of one or more symbols which represent values, operators, variables, and functions. In this section expressions are explained along with the values, operators, variables, and functions they consist of.

9.1 Values and Expressions

A value is a single symbol or a group of symbols which represent an idea. For example, the value:

3

represents the number three, the value:

0.5

represents the number one half, and the value:

"Mathematics is powerful!"

represents an English sentence.

Expressions can be created by using values and operators as building blocks. The following are examples of simple expressions which have been created this way:

3

2 + 3

5 + 6*21/18 - 2^3

In MathPiper, expressions can be evaluated which means that they can be transformed into a result value by predefined rules. For example, when the expression 2 + 3 is evaluated, the result value that is produced is 5:

In> 2 + 3Result> 5

9.2 Operators

In the above expressions, the characters +, −, *, /, ^ are called operators and their purpose is to tell MathPiper what operations to perform on the values in an expression. For example, in the expression 2 + 3, the addition operator + tells MathPiper to add the integer 2 to the integer 3 and return the result.

The subtraction operator is −, the multiplication operator is *, / is the division operator, % is the remainder operator (which is also used as the

949

950951952953

954

955956

957

958

959

960

961

962

963964965

966

967

968

969970971

972973

974

975976977978

979980

Page 42: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 42/140

"result of the last calculation" symbol), and ^ is the exponent operator. MathPiper has more operators in addition to these and some of them will be covered later.

The following examples show the −, *, /,%, and ^ operators being used:

In> 5 - 2Result> 3

In> 3*4Result> 12

In> 30/3Result> 10

In> 8%5Result> 3

In> 2^3Result> 8

The − character can also be used to indicate a negative number:In> -3Result> -3

Subtracting a negative number results in a positive number (Note: there must be a space between the two negative signs):In> - -3Result> 3

In MathPiper, operators are symbols (or groups of symbols) which are implemented with functions. One can either call the function that an operator represents directly or use the operator to call the function indirectly. However, using operators requires less typing and they often make a program easier to read.

9.3 Operator Precedence

When expressions contain more than one operator, MathPiper uses a set of rules called operator precedence to determine the order in which the operators are applied to the values in the expression. Operator precedence is also referred to as the order of operations. Operators with higher precedence are evaluated before operators with lower precedence. The following table shows a subset of MathPiper's operator precedence rules with higher precedence operators being placed higher in the table:

981982983

984

985986

987988

989990

991992

993994

995996997

99899910001001

10021003100410051006

1007

1008100910101011101210131014

Page 43: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 43/140

^ Exponents are evaluated right to left.

*,%,/ Then multiplication, remainder, and division operations are evaluated left to right.

+, − Finally, addition and subtraction are evaluated left to right.

Lets manually apply these precedence rules to the multi-operator expression we used earlier. Here is the expression in source code form:

5 + 6*21/18 - 2^3

And here it is in traditional form:

56∗2118

−23

According to the precedence rules, this is the order in which MathPiper evaluates the operations in this expression:

5 + 6*21/18 - 2^35 + 6*21/18 - 85 + 126/18 - 85 + 7 - 812 - 84

Starting with the first expression, MathPiper evaluates the ^ operator first which results in the 8 in the expression below it. In the second expression, the * operator is executed next, and so on. The last expression shows that the final result after all of the operators have been evaluated is 4.

9.4 Changing The Order Of Operations In An Expression

The default order of operations for an expression can be changed by grouping various parts of the expression within parentheses (). Parentheses force the code that is placed inside of them to be evaluated before any other operators are evaluated. For example, the expression 2 + 4*5 evaluates to 22 using the default precedence rules:

In> 2 + 4*5Result> 22

If parentheses are placed around 2 + 4, however, the addition operator is forced to be evaluated before the multiplication operator and the result is 30:

1015

10161017

1018

10191020

1021

1022

10231024

102510261027102810291030

1031103210331034

1035

10361037103810391040

10411042

10431044

Page 44: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 44/140

In> (2 + 4)*5Result> 30

Parentheses can also be nested and nested parentheses are evaluated from the most deeply nested parentheses outward:

In> ((2 + 4)*3)*5Result> 90

(Note: precedence adjusting parentheses are different from the parentheses that are used to call functions.)

Since parentheses are evaluated before any other operators, they are placed at the top of the precedence table:

() Parentheses are evaluated from the inside out.

^ Then exponents are evaluated right to left.

*,%,/ Then multiplication, remainder, and division operations are evaluated left to right.

+, − Finally, addition and subtraction are evaluated left to right.

9.5 Functions & Function Names

In programming, functions are named blocks of code that can be executed one or more times by being called from other parts of the same program or called from other programs. Functions can have values passed to them from the calling code and they always return a value back to the calling code when they are finished executing. An example of a function is the IsEven() function which was discussed in an previous section.

Functions are one way that MathPiper enables code to be reused. Most programming languages allow code to be reused in this way, although in other languages these named blocks of code are sometimes called subroutines, procedures, or methods.

The functions that come with MathPiper have names which consist of either a single word (such as Sum()) or multiple words that have been put together to form a compound word (such as IsBound()). All letters in the names of functions which come with MathPiper are lower case except the beginning letter in each word, which are upper case.

10451046

10471048

10491050

10511052

10531054

1055

1056

10571058

1059

1060

106110621063106410651066

1067106810691070

10711072107310741075

Page 45: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 45/140

9.6 Functions That Produce Side Effects

Most functions are executed to obtain the results they produce but some functions are executed in order to have them perform work that is not in the form of a result. Functions that perform work that is not in the form of a result are said to produce side effects. Side effects include many forms of work such as sending information to the user, opening files, and changing values in the computer's memory.

When a function produces a side effect which sends information to the user, this information has the words Side Effects: placed before it in the output instead of the word Result:. The Echo() and Write() functions are examples of functions that produce side effects and they are covered in the next section.

9.6.1 Printing Related Functions: Echo(), Write(), And Newline()The printing related functions send text information to the user and this is usually referred to as "printing" in this document. However, it may also be called "echoing" and "writing".

9.6.1.1 Echo()

The Echo() function takes one expression (or multiple expressions separated by commas) evaluates each expression, and then prints the results as side effect output. The following examples illustrate this:

In> Echo(1)Result> TrueSide Effects>1

In this example, the number 1 was passed to the Echo() function, the number was evaluated (all numbers evaluate to themselves), and the result of the evaluation was then printed as a side effect. Notice that Echo() also returned a result. In MathPiper, all functions return a result, but functions whose main purpose is to produce a side effect usually just return a result of True if the side effect succeeded or False if it failed. In this case, Echo() returned a result of True because it was able to successfully print a 1 as its side effect.

The next example shows multiple expressions being sent to Echo() (notice that the expressions are separated by commas):

In> Echo(1,1+2,2*3)Result> TrueSide Effects>1 3 6

1076

107710781079108010811082

1083108410851086

1087

108810891090

1091

109210931094

1095109610971098

1099110011011102110311041105

11061107

1108110911101111

Page 46: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 46/140

The expressions were each evaluated and their results were returned (separated by spaces) as side effect output. If it is desired that commas be printed between the numbers in the output, simply place three commas between the expressions that are passed to Echo():

In> Echo(1,,,1+2,,,2*3)Result> TrueSide Effects>1 , 3 , 6

Each time an Echo() function is executed, it always forces the display to drop down to the next line after it is finished. This can be seen in the following program which is similar to the previous one except it uses a separate Echo() function to display each expression:

%mathpiper

Echo(1);Echo(1+2);Echo(2*3);%/mathpiper

%output,preserve="false" Result: True Side Effects: 1 3 6. %/output

Notice how the 1, the 3, and the 6 are each on their own line.

Now that we have seen how Echo() works, lets use it to do something useful. If more than one expression is evaluated in a %mathpiper fold, only the result from the last expression that was evaluated (which is usually the bottommost expression) is displayed:

%mathpiper

a := 1;b := 2;c := 3;%/mathpiper

1112111311141115

1116111711181119

1120112111221123

1124

1125

1126

1127

1128

11291130113111321133113411351136

1137

1138113911401141

1142

114311441145

1146

Page 47: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 47/140

%output,preserve="false" Result: 3. %/output

In MathPiper, programs are executed one line at a time, starting at the topmost line of code and working downwards from there. In this example, the line a := 1; is executed first, then the line b := 2; is executed, and so on. Notice, however, that even though we wanted to see what was in all three variables, only the content of the last variable was displayed.

The following example shows how Echo() can be used to display the contents of all three variables:

%mathpiper

a := 1;Echo(a);b := 2;Echo(b);c := 3;Echo(c);%/mathpiper

%output,preserve="false" Result: True Side Effects: 1 2 3. %/output

9.6.1.2 Echo Functions Are Useful For "Debugging" Programs

The errors that are in a program are often called "bugs". This name came from the days when computers were the size of large rooms and were made using electromechanical parts. Periodically, bugs would crawl into the machines and interfere with its moving mechanical parts and this would cause the machine to malfunction. The bugs needed to be located and removed before the machine would run properly again.

Of course, even back then most program errors were produced by programmers entering wrong programs or entering programs wrong, but they liked to say that all of the errors were caused by bugs and not by themselves! The process of fixing errors in a program became known as debugging and the names "bugs"

114711481149

11501151115211531154

11551156

1157

11581159

11601161

11621163

1164

11651166116711681169117011711172

1173

117411751176117711781179

1180118111821183

Page 48: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 48/140

and "debugging" are still used by programmers today.

One of the standard ways to locate bugs in a program is to place Echo() function calls in the code at strategic places which print the contents of variables and display messages. These Echo() functions will enable you to see what your program is doing while it is running. After you have found and fixed the bugs in your program, you can remove the debugging Echo() function calls or comment them out if you think they may be needed later.

9.6.1.3 Write()

The Write() function is similar to the Echo() function except it does not automatically drop the display down to the next line after it finishes executing:

%mathpiper

Write(1,,);Write(1+2,,);Echo(2*3);%/mathpiper

%output,preserve="false" Result: True Side Effects: 1,3,6. %/output

Write() and Echo() have other differences besides the one discussed here and more information about them can be found in the documentation for these functions.

9.6.1.4 NewLine()The NewLine() function simply prints a blank line in the side effects output. It is useful for placing vertical space between printed lines:

%mathpiper

a := 1;Echo(a);NewLine();b := 2;Echo(b);

1184

118511861187118811891190

1191

11921193

1194

1195

1196

1197

1198

119912001201120212031204

120512061207

120812091210

1211

121212131214

12151216

Page 49: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 49/140

NewLine();c := 3;Echo(c);%/mathpiper

%output,preserve="false" Result: True Side Effects: 1

2

3. %/output

9.7 Expressions Are Separated By Semicolons

As discussed earlier, all of the expressions that are inside of a %mathpiper fold must have a semicolon (;) after them. However, the expressions executed in the MathPiper console did not have a semicolon after them. MathPiper actually requires that all expressions end with a semicolon, but one does not need to add a semicolon to an expression which is typed into the MathPiper console because the console adds it automatically when the expression is executed.

9.7.1 Placing More Than One Expression On A Line In A FoldAll the previous code examples have had each of their expressions on a separate line, but multiple expressions can also be placed on a single line because the semicolons tell MathPiper where one expression ends and the next one begins:

%mathpiper

a := 1; Echo(a); b := 2; Echo(b); c := 3; Echo(c);%/mathpiper

%output,preserve="false" Result: True Side Effects: 1 2 3. %/output

1217

12181219

1220

12211222122312241225

1226

12271228

1229

123012311232123312341235

1236

123712381239

1240

1241

1242

12431244124512461247124812491250

Page 50: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 50/140

The spaces that are in the code of this example are used to make the code more readable. Any spaces that are present within any expressions or between them are ignored by MathPiper and if we remove the spaces from the previous code, the output remains the same:

%mathpiper

a:=1;Echo(a);b:=2;Echo(b);c:= 3;Echo(c);%/mathpiper

%output,preserve="false" Result: True Side Effects: 1 2 3. %/output

9.7.2 Placing Multiple Expressions In A Code BlockA code block (which is also called a compound expression) consists of one or more expressions which are separated by semicolons and placed within an open bracket ([) and close bracket (]) pair. When a code block is evaluated, each expression in the block will be executed from left to right. The following example shows expressions being executed within of a code block inside the MathPiper console:

In> [a := 1; Echo(a); b := 2; Echo(b); c := 3; Echo(c);]Result> TrueSide Effects>1 2 3

Notice that all of the expressions were executed and 1-3 was printed as a side effect. Code blocks always return the result of the last expression executed as the result of the whole block. In this case, True was returned as the result because the last Echo(c) function returned True. If we place another expression after the Echo(c) function, however, the block will execute this new expression last and its result will be the one returned by the block:

In> [a := 1; Echo(a); b := 2; Echo(b); c := 3; Echo(c); 2 + 2;]Result> 4Side Effects>1

1251125212531254

1255

1256

1257

12581259126012611262126312641265

1266

126712681269127012711272

127312741275127612771278

127912801281128212831284

1285128612871288

Page 51: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 51/140

2 3

Finally, code blocks can have their contents placed on separate lines if desired:

%mathpiper[ a := 1; Echo(a); b := 2; Echo(b); c := 3; Echo(c);];

%/mathpiper

%output,preserve="false" Result: True Side Effects: 1 2 3. %/output

Code blocks are very powerful and we will be discussing them further in later sections.

9.7.2.1 Automatic Bracket, Parentheses, And Brace Match Indicating

In programming, most open brackets '[' have a close bracket ']', most open parentheses '(' have a close parentheses ')', and most open braces '{' have a close brace '}'. It is often difficult to make sure that each "open" character has a matching "close" character and if any of these characters don't have a match, then an error will be produced.

Thankfully, most programming text editors have a character match indicating tool that will help locate problems. To try this tool, paste the following code into a .mpw file and following the directions that are present in its comments:

%mathpiper

/*

12891290

1291

12921293129412951296129712981299130013011302130313041305

1306

13071308130913101311131213131314

13151316

1317

13181319132013211322

132313241325

1326

1327

Page 52: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 52/140

Copy this code into a .mpw file. Then, place the cursor to the immediate right of any {, }, [, ], (, or ) character. You should notice that the match to this character is indicated by a rectangle being drawing around it.*/

list := {1,2,3};[ Echo("Hello"); Echo(list);];

%/mathpiper

9.8 Strings

A string is a value that is used to hold text-based information. The typical expression that is used to create a string consists of text which is enclosed within double quotes. Strings can be assigned to variables just like numbers can and strings can also be displayed using the Echo() function. The following program assigns a string value to the variable 'a' and then echos it to the user:

%mathpiper

a := "Hello, I am a string.";Echo(a);%/mathpiper

%output,preserve="false" Result: True Side Effects: Hello, I am a string.. %/output

9.8.1 The MathPiper Console and MathPiper Folds Can Access The Same VariablesA useful aspect of using MathPiper inside of MathPiperIDE is that variables that are assigned inside of a %mathpiper fold are accessible inside of the MathPiper console and variables that are assigned inside of the MathPiper console are available inside of %mathpiper folds. For example, after the above fold is executed, the string that has been bound to variable 'a' can be displayed in the MathPiper console:

13281329133013311332

1333

13341335

13361337

1338

1339

13401341134213431344

1345

13461347

1348

134913501351135213531354

13551356

135713581359136013611362

Page 53: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 53/140

In> aResult> "Hello, I am a string."

9.8.2 Using Strings To Make Echo's Output Easier To ReadWhen the Echo() function is used to print the values of multiple variables, it is often helpful to print some information next to each variable so that it is easier to determine which value came from which Echo() function in the code. The following program prints the name of the variable that each value came from next to it in the side effects output:

%mathpiper

a := 1;Echo("Variable a: ", a);b := 2;Echo("Variable b: ", b);c := 3;Echo("Variable c: ", c);%/mathpiper

%output,preserve="false" Result: True Side Effects: Variable a: 1 Variable b: 2 Variable c: 3. %/output

9.8.2.1 Combining Strings With The : Operator

If you need to combine two or more strings into one string, you can use the : operator like this:

In> "A" : "B" : "C"Result: "ABC"

In> "Hello " : "there!"Result: "Hello there!"

9.8.2.2 WriteString()

The WriteString() function prints a string without showing the double quotes

13631364

1365

13661367136813691370

1371

13721373

13741375

13761377

1378

13791380138113821383138413851386

1387

13881389

13901391

13921393

1394

1395

Page 54: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 54/140

that are around it.. For example, here is the Write() function being used to print the string "Hello":

In> Write("Hello")Result: TrueSide Effects:"Hello"

Notice the double quotes? Here is how the WriteString() function prints "Hello":

In> WriteString("Hello")Result: TrueSide Effects:Hello

9.8.2.3 Nl()

The Nl() (New Line) function is used with the : function to place newline characters inside of strings:

In> WriteString("A": Nl() : "B")Result: TrueSide Effects:AB

9.8.2.4 Space()

The Space() function is used to add spaces to printed output:

In> WriteString("A"); Space(5); WriteString("B")Result: TrueSide Effects:A B

In> WriteString("A"); Space(10); WriteString("B")Result: TrueSide Effects:A B

In> WriteString("A"); Space(20); WriteString("B")Result: TrueSide Effects:A B

9.8.3 Accessing The Individual Letters In A StringIndividual letters in a string (which are also called characters) can be accessed by placing the character's position number (also called an index) inside of

13961397

1398139914001401

1402

1403140414051406

1407

14081409

14101411141214131414

1415

1416

1417141814191420

1421142214231424

1425142614271428

1429

14301431

Page 55: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 55/140

brackets [] after the variable it is bound to. A character's position is determined by its distance from the left side of the string starting at 1. For example, in the string "Hello", 'H' is at position 1, 'e' is at position 2, etc. The following code shows individual characters in the above string being accessed:

In> a := "Hello, I am a string."Result> "Hello, I am a string."

In> a[1]Result> "H"

In> a[2]Result> "e"

In> a[3]Result> "l"

In> a[4]Result> "l"

In> a[5]Result> "o"

9.8.3.1 Indexing Before The Beginning Of A String Or Past The End Of A String

Lets see what happens if an index is used that is less than 1 or greater than the length of a given string. First, we will bind the string "Hello" to the variable 'a':

In> a := "Hello"Result: "Hello"

Then, we'll index the character at position 1 and then the character at position 0:

In> a[1]Result: "H"

In> a[0]Result: Exception: In function "StringMidGet" : bad argument number 1(counting from 1) :

The offending argument aindex evaluated to 0 In function: Nth,

Notice that using an index of 0 resulted in an error.

Next, lets access the character at position 5 (which is the 'o'), then the character at position 6 and finally the character at position 7:

1432143314341435

14361437

14381439

14401441

14421443

14441445

14461447

1448

14491450

14511452

1453

14541455

1456145714581459

14601461

1462

14631464

Page 56: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 56/140

In> a[5]Result: "o"

In> a[6]Result: """

In> a[7]Result: Exception: String index out of range: 8

The 'o' at position 5 was returned correctly, but accessing position 6 returned a double quote character (") and accessing position 7 resulted in an error. What you can see in this section is that errors are usually produced if an index is not set to the position of an actual character in a string.

9.9 Comments

Source code can often be difficult to understand and therefore all programming languages provide the ability for comments to be included in the code. Comments are used to explain what the code near them is doing and they are usually meant to be read by humans instead of being processed by a computer. Therefore, comments are ignored by the computer when a program is executed.

There are two ways that MathPiper allows comments to be added to source code. The first way is by placing two forward slashes // to the left of any text that is meant to serve as a comment. The text from the slashes to the end of the line the slashes are on will be treated as a comment. Here is a program that contains comments which use slashes:

%mathpiper//This is a comment.

x := 2; //Set the variable x equal to 2.

%/mathpiper

%output,preserve="false" Result: 2. %/output

When this program is executed, any text that starts with slashes is ignored.

The second way to add comments to a MathPiper program is by enclosing the comments inside of slash-asterisk/asterisk-slash symbols /* */. This option is useful when a comment is too large to fit on one line. Any text between these symbols is ignored by the computer. This program shows a longer comment which has been placed between these symbols:

14651466

14671468

146914701471

1472147314741475

1476

14771478147914801481

14821483148414851486

14871488

1489

1490

149114921493

1494

14951496149714981499

Page 57: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 57/140

%mathpiper

/* This is a longer comment and it uses more than one line. The following code assigns the number 3 to variable x and then returns it as a result.*/

x := 3;%/mathpiper

%output,preserve="false" Result: 3. %/output

9.10 How To Tell If MathPiper Has Crashed And What To Do If It Has

Sometimes code will be evaluated which has one or more unusual errors in it and the errors will cause MathPiper to "crash". Unfortunately, beginners are more likely to crash MathPiper than more experienced programmers are because a beginner's program is more likely to have errors in it. When MathPiper crashes, no harm is done but it will not work correctly after that. The only way to recover from a MathPiper crash is to exit MathPiperIDE and then relaunch it. All the information in your buffers will be saved and preserved but the contents of the console will not be. Be sure to copy the contents of the console into a buffer and then save it before restarting.

The main way to tell if MathPiperIDE has crashed is that it will indicate that there are errors in lines of code that are actually fine. If you are receiving an error in code that looks okay to you, simply restarting MathPiperIDE may fix the problem. If you restart MathPiperIDE and the error is still present, this usually means that there really is an error in the code.

9.11 Exercises

For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_9_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called:

book_1_section_9_exercises_john_smith.mpw.

After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution

1500

150115021503150415051506

1507

1508

150915101511

1512

151315141515151615171518151915201521

15221523152415251526

1527

1528152915301531

1532

153315341535

Page 58: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 58/140

to. The folds you create should look similar to this one:

%mathpiper,title="Exercise 1"

//Sample fold.

%/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved.

9.11.1 Exercise 1Carefully read all of section 9. Evaluate each one of the examples in section 9 in the MathPiper worksheet you created or in the MathPiper console and verify that the results match the ones in the book. Copy all of the console examples you evaluated into your worksheet so they will be saved but do not put them in a fold.

9.11.2 Exercise 2Change the precedence of the following expression using parentheses so that it prints 20 instead of 14:

2 + 3 * 4

9.11.3 Exercise 3Place the following calculations into a fold and then use one Echo() function per variable to print the results of the calculations. Put strings in the Echo() functions which indicate which variable each calculated value is bound to:

a := 1+2+3+4+5;b := 1-2-3-4-5;c := 1*2*3*4*5;d := 1/2/3/4/5;

9.11.4 Exercise 4Place the following calculations into a fold and then use one Echo() function to print the results of all the calculations on a single line (Remember, the Echo() function can print multiple values if they are separated by commas.):

Unbind(x);a := 2*2*2*2*2;b := 2^5;c := x^2 * x^3;d := 2^2 * 2^3;

1536

1537

1538

1539

15401541

154215431544154515461547

154815491550

1551

15521553155415551556

1557155815591560

15611562156315641565

15661567156815691570

Page 59: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 59/140

9.11.5 Exercise 5The following code assigns a string which contains all of the upper case letters of the alphabet to the variable upper. Each of the three Echo() functions prints an index number and the letter that is at that position in the string. Place this code into a fold and then continue the Echo() functions so that all 26 letters and their index numbers are printed

upper := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

Echo(1,upper[1]);Echo(2,upper[2]);Echo(3,upper[3]);

9.11.6 Exercise 6Use Echo() functions to print an index number and the character at this position for the following string (this is similar to what was done in the previous exercise.):

extra := ".!@#$%^&*() _+<>,?/{}[]|\-=;";

Echo(1,extra[1]);Echo(2,extra[2]);Echo(3,extra[3]);

9.11.7 Exercise 7The following program uses strings and index numbers to print a person's name. Create a program which uses the three strings from this program to print the names of three of your favorite musical bands.

%mathpiper/* This program uses strings and index numbers to print a person's name.*/

upper := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";lower := "abcdefghijklmnopqrstuvwxyz";extra := ".!@#$%^&*() _+<>,?/{}[]|\-=";

//Print "Mary Smith.".Echo(upper[13],lower[1],lower[18],lower[25],extra[12],upper[19],lower[13],lower[9],lower[20],lower[8],extra[1]);

%/mathpiper

%output,preserve="false"

157115721573157415751576

1577

157815791580

1581158215831584

1585

158615871588

1589159015911592

15931594159515961597

159815991600

160116021603

1604

1605

Page 60: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 60/140

Result: True Side Effects: Mary Smith.. %/output

16061607160816091610

Page 61: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 61/140

10 Rectangular Selection Mode And Text Area Splitting

10.1 Rectangular Selection Mode

One capability that MathPiperIDE has that a word processor may not have is the ability to select rectangular sections of text. To see how this works, do the following:

1) Type three or four lines of text into a text area.

2) Hold down the <Alt> key then slowly press the backslash key (\) a few times. The bottom of the MathPiperIDE window contains a text field which MathPiperIDE uses to communicate information to the user. As <Alt>\ is repeatedly pressed, messages are displayed which read Rectangular selection is on and Rectangular selection is off.

3) Turn rectangular selection on and then select some text in order to see how this is different than normal selection mode. When you are done experimenting, set rectangular selection mode to off.

Most of the time normal selection mode is what you want to use but in certain situations rectangular selection mode is better.

10.2 Text area splitting

Sometimes it is useful to have two or more text areas open for a single document or multiple documents so that different parts of the documents can be edited at the same time. A situation where this would have been helpful was in the previous section where the output from an exercise in a MathPiperIDE worksheet contained a list of index numbers and letters which was useful for completing a later exercise.

MathPiperIDE has this ability and it is called splitting. If you look just to the right of the toolbar there is an icon which looks like a blank window, an icon to the right of it which looks like a window which was split horizontally, and an icon to the right of the horizontal one which is split vertically. If you let your mouse hover over these icons, a short description will be displayed for each of them.

Select a text area and then experiment with splitting it by pressing the horizontal and vertical splitting buttons. Move around these split text areas with their scroll bars and when you want to unsplit the document, just press the "Unsplit All" icon.

10.3 Exercises

For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_10_exercises_<your first name>_<your last name>.mpw.

1611

1612

161316141615

1616

16171618161916201621

162216231624

16251626

1627

162816291630163116321633

16341635163616371638

1639164016411642

1643

16441645

Page 62: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 62/140

(Note: there are no spaces in this file name). For example, John Smith's worksheet would be called:

book_1_section_10_exercises_john_smith.mpw.

For the following exercises, simply type your answers anywhere in the worksheet.

10.3.1 Exercise 1Carefully read all of section 10 then answer the following questions:

a) Give two examples where rectangular selection mode may be more useful than regular selection mode.

b) How can windows that have been split be unsplit?

16461647

1648

16491650

16511652

16531654

1655

Page 63: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 63/140

11 Working With Random IntegersIt is often useful to use random integers in a program. For example, a program may need to simulate the rolling of dice in a game. In this section, a function for obtaining nonnegative integers is discussed along with how to use it to simulate the rolling of dice.

11.1 Obtaining Random Integers With The RandomInteger() Function

One way that a MathPiper program can generate random integers is with the RandomInteger() function. The RandomInteger() function takes an integer as a parameter and it returns a random integer between 1 and the passed in integer. The following example shows random integers between 1 and 5 inclusive being obtained from RandomInteger(). Inclusive here means that both 1 and 5 are included in the range of random integers that may be returned. If the word exclusive was used instead, this would mean that neither 1 nor 5 would be in the range.

In> RandomInteger(5)Result> 4In> RandomInteger(5)Result> 5In> RandomInteger(5)Result> 4In> RandomInteger(5)Result> 2In> RandomInteger(5)Result> 3In> RandomInteger(5)Result> 5In> RandomInteger(5)Result> 2In> RandomInteger(5)Result> 2In> RandomInteger(5)Result> 1In> RandomInteger(5)Result> 2

Random integers between 1 and 100 can be generated by passing 100 to RandomInteger():

In> RandomInteger(100)Result> 15In> RandomInteger(100)Result> 14

1656

1657165816591660

1661

16621663166416651666166716681669

16701671167216731674167516761677167816791680168116821683168416851686168716881689

16901691

1692169316941695

Page 64: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 64/140

In> RandomInteger(100)Result> 82In> RandomInteger(100)Result> 93In> RandomInteger(100)Result> 32

A range of random integers that does not start with 1 can also be generated by using the two argument version of RandomInteger(). For example, random integers between 25 and 75 can be obtained by passing RandomInteger() the lowest integer in the range and the highest one:

In> RandomInteger(25, 75)Result: 28In> RandomInteger(25, 75)Result: 37In> RandomInteger(25, 75)Result: 58In> RandomInteger(25, 75)Result: 50In> RandomInteger(25, 75)Result: 70

11.2 Simulating The Rolling Of Dice

The following example shows the simulated rolling of a single six sided die using the RandomInteger() function:

In> RandomInteger(6)Result> 5In> RandomInteger(6)Result> 6In> RandomInteger(6)Result> 3In> RandomInteger(6)Result> 2In> RandomInteger(6)Result> 5

Code that simulates the rolling of two 6 sided dice can be evaluated in the MathPiper console by placing it within a code block. The following code outputs the sum of the two simulated dice:

In> [a := RandomInteger(6); b := RandomInteger(6); a + b;]Result> 6In> [a := RandomInteger(6); b := RandomInteger(6); a + b;]Result> 12In> [a := RandomInteger(6); b := RandomInteger(6); a + b;]Result> 6

169616971698169917001701

1702170317041705

1706170717081709171017111712171317141715

1716

17171718

1719172017211722172317241725172617271728

172917301731

173217331734173517361737

Page 65: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 65/140

In> [a := RandomInteger(6); b := RandomInteger(6); a + b;]Result> 4In> [a := RandomInteger(6); b := RandomInteger(6); a + b;]Result> 3In> [a := RandomInteger(6); b := RandomInteger(6); a + b;]Result> 8

Now that we have the ability to simulate the rolling of two 6 sided dice, it would be interesting to determine if some sums of these dice occur more frequently than other sums. What we would like to do is to roll these simulated dice hundreds (or even thousands) of times and then analyze the sums that were produced. We don't have the programming capability to easily do this yet, but after we finish the section on While loops, we will.

11.3 Exercises

For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_11_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called:

book_1_section_11_exercises_john_smith.mpw.

After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:

%mathpiper,title="Exercise 1"

//Sample fold.

%/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

11.3.1 Exercise 1Carefully read all of section 11. Evaluate each one of the examples in section 11 in the MathPiper worksheet you created or in the MathPiper console and verify that the results match the ones in the book. Copy all of the console examples you evaluated into your worksheet so they will be saved but do not put them in a fold.

173817391740174117421743

174417451746174717481749

1750

1751175217531754

1755

1756175717581759

1760

1761

1762

17631764

176517661767176817691770

Page 66: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 66/140

12 Making DecisionsThe simple programs that have been discussed up to this point show some of the power that software makes available to programmers. However, these programs are limited in their problem solving ability because they are unable to make decisions. This section shows how programs which have the ability to make decisions are able to solve a wider range of problems than programs that can't make decisions.

12.1 Conditional Operators

A program's decision making ability is based on a set of special operators which are called conditional operators. A conditional operator is an operator that is used to compare two values. Expressions that contain conditional operators return a boolean value and a boolean value is one that can only be True or False. In case you are curious about the strange name, boolean values come from the area of mathematics called boolean logic. This logic was created by a mathematician named George Boole and this is where the name boolean came from. Table 2 shows the conditional operators that MathPiper uses:

Operator Description

x = y Returns True if the two values are equal and False if they are not equal. Notice that = performs a comparison and not an assignment like := does.

x != y Returns True if the values are not equal and False if they are equal.

x < y Returns True if the left value is less than the right value and False if the left value is not less than the right value.

x <= y Returns True if the left value is less than or equal to the right value and False if the left value is not less than or equal to the right value.

x > y Returns True if the left value is greater than the right value and False if the left value is not greater than the right value.

x >= y Returns True if the left value is greater than or equal to the right value and False if the left value is not greater than or equal to the right value.

Table 2: Conditional Operators

This example shows some of these conditional operators being evaluated in the MathPiper console:

In> 1 < 2Result> True

1771

177217731774177517761777

1778

17791780178117821783178417851786

17871788

17891790

Page 67: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 67/140

In> 4 > 5Result> False

In> 8 >= 8Result> True

In> 5 <= 10Result> True

The following examples show each of the conditional operators in Table 2 being used to compare values that have been assigned to variables x and y:

%mathpiper

// Example 1.x := 2;y := 3; Echo(x, "= ", y, ":", x = y);Echo(x, "!= ", y, ":", x != y);Echo(x, "< ", y, ":", x < y);Echo(x, "<= ", y, ":", x <= y);Echo(x, "> ", y, ":", x > y);Echo(x, ">= ", y, ":", x >= y);%/mathpiper

%output,preserve="false" Result: True Side Effects: 2 = 3 :False 2 != 3 :True 2 < 3 :True 2 <= 3 :True 2 > 3 :False 2 >= 3 :False. %/output

%mathpiper

// Example 2. x := 2; y := 2; Echo(x, "= ", y, ":", x = y); Echo(x, "!= ", y, ":", x != y); Echo(x, "< ", y, ":", x < y); Echo(x, "<= ", y, ":", x <= y); Echo(x, "> ", y, ":", x > y);

17911792

17931794

17951796

17971798

1799

180018011802

180318041805180618071808

1809

18101811181218131814181518161817181818191820

1821

182218231824

18251826182718281829

Page 68: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 68/140

Echo(x, ">= ", y, ":", x >= y);%/mathpiper

%output,preserve="false" Result: True Side Effects: 2 = 2 :True 2 != 2 :False 2 < 2 :False 2 <= 2 :True 2 > 2 :False 2 >= 2 :True. %/output

%mathpiper

// Example 3.x := 3;y := 2; Echo(x, "= ", y, ":", x = y);Echo(x, "!= ", y, ":", x != y);Echo(x, "< ", y, ":", x < y);Echo(x, "<= ", y, ":", x <= y);Echo(x, "> ", y, ":", x > y);Echo(x, ">= ", y, ":", x >= y);%/mathpiper

%output,preserve="false" Result: True Side Effects: 3 = 2 :False 3 != 2 :True 3 < 2 :False 3 <= 2 :False 3 > 2 :True 3 >= 2 :True. %/output

Conditional operators are placed at a lower level of precedence than the other operators we have covered to this point:

() Parentheses are evaluated from the inside out.

^ Then exponents are evaluated right to left.

1830

1831

18321833183418351836183718381839184018411842

1843

184418451846

184718481849185018511852

1853

18541855185618571858185918601861186218631864

18651866

1867

1868

Page 69: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 69/140

*,%,/ Then multiplication, remainder, and division operations are evaluated left to right.

+, − Then addition and subtraction are evaluated left to right.

=,!=,<,<=,>,>= Finally, conditional operators are evaluated.

12.2 Predicate Expressions

Expressions which return either True or False are called "predicate" expressions. By themselves, predicate expressions are not very useful and they only become so when they are used with special decision making functions, like the If() function (which is discussed in the next section).

12.3 Exercises

For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_12a_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called:

book_1_section_12a_exercises_john_smith.mpw.

After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:

%mathpiper,title="Exercise 1"

//Sample fold.

%/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

12.3.1 Exercise 1Carefully read all of section 12 up to this point. Evaluate each one of the examples in the sections you read in the MathPiper worksheet you created or in the MathPiper console and verify that the results match the ones in the book. Copy all of the console examples you evaluated into your worksheet so they will be saved but do not put them in a fold.

18691870

1871

1872

1873

1874187518761877

1878

1879188018811882

1883

1884188518861887

1888

1889

1890

18911892

189318941895189618971898

Page 70: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 70/140

12.3.2 Exercise 2Open a MathPiper session and evaluate the following predicate expressions:

In> 3 = 3

In> 3 = 4

In> 3 < 4

In> 3 != 4

In> -3 < 4

In> 4 >= 4

In> 1/2 < 1/4

In> 15/23 < 122/189

/*In the following two expressions, notice that 1/2 is not considered to be equal to .5 unless it is converted to a numerical value first.*/

In> 1/2 = .5

In> N(1/2) = .5

12.3.3 Exercise 3Come up with 10 predicate expressions of your own and evaluate them in the MathPiper console.

12.4 Making Decisions With The If() Function & Predicate Expressions

All programming languages have the ability to make decisions and the most commonly used function for making decisions in MathPiper is the If() function.

There are two calling formats for the If() function:

If(predicate, then)If(predicate, then, else)

The way the first form of the If() function works is that it evaluates the first expression in its argument list (which is the "predicate" expression) and then looks at the value that is returned. If this value is True, the "then" expression that is listed second in the argument list is executed. If the predicate expression evaluates to False, the "then" expression is not executed. (Note: any function

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

19091910

1911

1912

1913

19141915

1916

19171918

1919

19201921192219231924

Page 71: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 71/140

that accepts a predicate expression as a parameter can also accept the boolean values True and False).

The following program uses an If() function to determine if the value in variable number is greater than 5. If number is greater than 5, the program will echo "Greater" and then "End of program":

%mathpiper

number := 6;If(number > 5, Echo(number, "is greater than 5."));Echo("End of program.");%/mathpiper

%output,preserve="false" Result: True Side Effects: 6 is greater than 5. End of program.. %/output

In this program, number has been set to 6 and therefore the expression number > 5 is True. When the If() functions evaluates the predicate expression and determines it is True, it then executes the first Echo() function. The second Echo() function at the bottom of the program prints "End of program" regardless of what the If() function does. (Note: semicolons cannot be placed after expressions which are in function calls.)

Here is the same program except that number has been set to 4 instead of 6:

%mathpiper

number := 4;If(number > 5, Echo(number, "is greater than 5."));Echo("End of program.");%/mathpiper

%output,preserve="false" Result: True Side Effects: End of program.. %/output

19251926

192719281929

1930

1931

1932

1933

1934

1935193619371938193919401941

194219431944194519461947

1948

1949

1950

1951

1952

1953

195419551956195719581959

Page 72: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 72/140

This time the expression number > 4 returns a value of False which causes the If() function to not execute the "then" expression that was passed to it.

12.4.1 If() Functions Which Include An "Else" ParameterThe second form of the If() function takes a third "else" expression which is executed only if the predicate expression is False. This program is similar to the previous one except an "else" expression has been added to it:

%mathpiper

x := 4;If(x > 5,Echo(x,"is greater than 5."),Echo(x,"is NOT greater than 5."));Echo("End of program.");%/mathpiper

%output,preserve="false" Result: True Side Effects: 4 is NOT greater than 5. End of program.. %/output

12.5 Exercises

For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_12b_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called:

book_1_section_12b_exercises_john_smith.mpw.

After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:

%mathpiper,title="Exercise 1"

//Sample fold.

%/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you

19601961

1962

196319641965

1966

1967

1968

1969

1970

1971197219731974197519761977

1978

1979198019811982

1983

1984198519861987

1988

1989

1990

1991

Page 73: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 73/140

did in the console into the worksheet so it can be saved but do not put it in a fold.

12.5.1 Exercise 1Carefully read all of section 12 starting at the end of the previous exercises and up to this point. Evaluate each one of the examples in the sections you read in the MathPiper worksheet you created or in the MathPiper console and verify that the results match the ones in the book. Copy all of the console examples you evaluated into your worksheet so they will be saved but do not put them in a fold.

12.5.2 Exercise 2Write a program which uses the RandomInteger() function to simulate the flipping of a coin (Hint: you can use 1 to represent a head and 2 to represent a tail.). Use predicate expressions, the If() function, and the Echo() function to print the string "The coin came up heads." or the string "The coin came up tails.", depending on what the simulated coin flip came up as when the code was executed.

12.6 The And(), Or(), & Not() Boolean Functions & Infix Notation

12.6.1 And()Sometimes a programmer needs to check if two or more expressions are all True and one way to do this is with the And() function. The And() function has two calling formats (or notations) and this is the first one:

And(expression1, expression2, expression3, ..., expressionN)

This calling format is able to accept one or more predicate expressions as input. If all of these expressions returns a value of True, the And() function will also return a True. However, if any of the expressions return a False, then the And() function will return a False. This can be seen in the following example:

In> And(True, True)Result> True

In> And(True, False)Result> False

In> And(False, True)Result> False

In> And(True, True, True, True)Result> True

1992

1993199419951996199719981999

2000200120022003200420052006

2007

2008

200920102011

2012201320142015

20162017

20182019

20202021

20222023

Page 74: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 74/140

In> And(True, True, False, True)Result> False

The second format (or notation) that can be used to call the And() function is called infix notation:

expression1 And expression2

With infix notation, an expression is placed on both sides of the And() function name instead of being placed inside of parentheses that are next to it:

In> True And TrueResult> True

In> True And FalseResult> False

In> False And TrueResult> False

In> True And True And True And TrueResult: True

Infix notation can only accept two expressions at a time, but it is often more convenient to use than function calling notation. The following program also demonstrates the infix version of the And() function being used:

%mathpiper

a := 7;b := 9;Echo("1: ", a < 5 And b < 10);Echo("2: ", a > 5 And b > 10);Echo("3: ", a < 5 And b > 10);Echo("4: ", a > 5 And b < 10);If(a > 5 And b < 10, Echo("These expressions are both true."));%/mathpiper

%output,preserve="false" Result: True Side Effects: 1: False 2: False 3: False

20242025

20262027

20282029

20302031

20322033

20342035

20362037

203820392040

2041

20422043

2044204520462047

2048

2049

2050205120522053205420552056

Page 75: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 75/140

4: True These expressions are both true.. %/output

12.6.2 Or()The Or() function is similar to the And() function in that it has both a function calling format and an infix calling format and it only works with predicate expressions. However, instead of requiring that all expressions be True in order to return a True, Or() will return a True if one or more expressions are True.

Here is the function calling format for Or():

Or(expression1, expression2, expression3, ..., expressionN)

and this example shows Or() being used with function calling format:

In> Or(True, False)Result> True

In> Or(False, True)Result> True

In> Or(False, False)Result> False

In> Or(False, False, False, False)Result> False

In> Or(False, True, False, False)Result> True

The infix notation format for Or() is as follows:

expression1 Or expression2

and this example shows infix notation being used:

In> True Or FalseResult> True

In> False Or TrueResult> True

In> False Or False

205720582059

2060

2061206220632064

2065

2066

20672068

20692070

20712072

20732074

20752076

2077

2078

20792080

20812082

2083

Page 76: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 76/140

Result> False

The following program also demonstrates the infix version of the Or() function being used:

%mathpiper

a := 7;b := 9;Echo("1: ", a < 5 Or b < 10);Echo("2: ", a > 5 Or b > 10);Echo("3: ", a > 5 Or b < 10);Echo("4: ", a < 5 Or b > 10);If(a < 5 Or b < 10,Echo("At least one of these expressions is true."));%/mathpiper

%output,preserve="false" Result: True Side Effects: 1: True 2: True 3: True 4: False At least one of these expressions is true.. %/output

12.6.3 Not() & Prefix Notation

The Not() function works with predicate expressions like the And() and Or() functions do, except it can only accept one expression as input. The way Not() works is that it changes a True value to a False value and a False value to a True value. Here is the Not()'s function calling format:

Not(expression)

and this example shows Not() being used with function calling format:

In> Not(True)Result> False

In> Not(False)Result> True

2084

20852086

2087

20882089

2090209120922093

2094

2095

2096209720982099210021012102210321042105

2106

2107210821092110

2111

21122113

21142115

Page 77: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 77/140

Instead of providing an alternative infix calling format like And() and Or() do, Not()'s second calling format uses prefix notation:

Not expression

Prefix notation looks similar to function notation except no parentheses are used:

In> Not TrueResult> False

In> Not FalseResult> True

Finally, here is a program that also uses the prefix version of Not():

%mathpiper

Echo("3 = 3 is ", 3 = 3);Echo("Not 3 = 3 is ", Not 3 = 3);%/mathpiper

%output,preserve="false" Result: True Side Effects: 3 = 3 is True Not 3 = 3 is False. %/output

12.7 Exercises

For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_12c_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called:

book_1_section_12c_exercises_john_smith.mpw.

After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:

%mathpiper,title="Exercise 1"

21162117

2118

21192120

21212122

2123

2124

2125

2126

2127

2128212921302131213221332134

2135

2136213721382139

2140

2141214221432144

2145

Page 78: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 78/140

//Sample fold.

%/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

12.7.1 Exercise 1Carefully read all of section 12 starting at the end of the previous exercises and up to this point. Evaluate each one of the examples in the sections you read in the MathPiper worksheet you created or in the MathPiper console and verify that the results match the ones in the book. Copy all of the console examples you evaluated into your worksheet so they will be saved but do not put them in a fold.

12.7.2 Exercise 2The following program simulates the rolling of two dice and prints a message if both of the two dice come up less than or equal to 3. Create a similar program which simulates the flipping of two coins and print the message "Both coins came up heads." if both coins come up heads.

%mathpiper/* This program simulates the rolling of two dice and prints a message if both of the two dice come up less than or equal to 3.*/

die1 := RandomInteger(6);die2 := RandomInteger(6);

Echo("Die1: ", die1, " Die2: ", die2);NewLine();

If( die1 <= 3 And die2 <= 3, Echo("Both dice came up <= to 3.") );

%/mathpiper

12.7.3 Exercise 3The following program simulates the rolling of two dice and prints a message if either of the two dice come up less than or equal to 3. Create a similar program which simulates the flipping of two coins and print the message "At least one coin came up heads." if at least one coin comes up heads.

%mathpiper/* This program simulates the rolling of two dice and prints a message if either of the two dice come up less than or equal to 3.

2146

2147

21482149

2150215121522153215421552156

21572158215921602161

21622163216421652166

21672168

21692170

2171

2172

217321742175217621772178

2179218021812182

Page 79: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 79/140

*/

die1 := RandomInteger(6);die2 := RandomInteger(6);

Echo("Die1: ", die1, " Die2: ", die2);NewLine();

If( die1 <= 3 Or die2 <= 3, Echo("At least one die came up <= 3.") );

%/mathpiper

2183

21842185

21862187

2188

2189

Page 80: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 80/140

13 The While() Looping Function & Bodied NotationMany kinds of machines, including computers, derive much of their power from the principle of repeated cycling. Repeated cycling in a MathPiper program means to execute one or more expressions over and over again and this process is called "looping". MathPiper provides a number of ways to implement loops in a program and these ways range from straight-forward to subtle.

We will begin discussing looping in MathPiper by starting with the straight-forward While function. The calling format for the While function is as follows:

While(predicate)[ body_expressions];

The While function is similar to the If function except it will repeatedly execute the expressions it contains as long as its "predicate" expression is True. As soon as the predicate expression returns a False, the While() function skips the expressions it contains and execution continues with the expression that immediately follows the While() function (if there is one).

The expressions which are contained in a While() function are called its "body" and all functions which have body expressions are called "bodied" functions. If a body contains more than one expression then these expressions need to be placed within a code block (code blocks were discussed in an earlier section). What a function's body is will become clearer after studying some example programs.

13.1 Printing The Integers From 1 to 10

The following program uses a While() function to print the integers from 1 to 10:

%mathpiper

// This program prints the integers from 1 to 10.

/* Initialize the variable count to 1 outside of the While "loop".*/count := 1;While(count <= 10)[ Echo(count);

2190

21912192219321942195

21962197

2198219922002201

22022203220422052206

220722082209221022112212

2213

2214

2215

2216

22172218221922202221

222222232224

Page 81: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 81/140

count := count + 1; //Increment count by 1.];

%/mathpiper

%output,preserve="false" Result: True Side Effects: 1 2 3 4 5 6 7 8 9 10. %/output

In this program, a single variable called count is created. It is used to tell the Echo() function which integer to print and it is also used in the predicate expression that determines if the While() function should continue to loop or not.

When the program is executed, 1 is placed into count and then the While() function is called. Notice that count is bound to the value 1 above the While loop. Setting a variable to an initial value is called initializing the variable and in this case, count needs to be initialized before it is used in the While() function. The predicate expression count <= 10 becomes 1 <= 10 and, since 1 is indeed less than or equal to 10, a value of True is returned by the predicate expression.

The While() function sees that the predicate expression returned a True and therefore it executes all of the expressions inside of its body from top to bottom.

The Echo() function prints the current contents of count (which is 1) and then the expression count := count + 1 is executed.

The expression count := count + 1 is a standard expression form that is used in many programming languages. Each time an expression in this form is evaluated, it increases the variable it contains by 1. Another way to describe the effect this expression has on count is to say that it increments count by 1.

In this case count contains 1 and, after the expression is evaluated, count contains 2.

After the last expression inside the body of the While() function is executed, the While() function reevaluates its predicate expression to determine whether it should continue looping or not. Since count is 2 at this point, the predicate expression returns True and the code inside the body of the While() function is

222522262227

2228

222922302231223222332234223522362237223822392240224122422243

224422452246

224722482249225022512252

22532254

22552256

2257225822592260

22612262

2263226422652266

Page 82: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 82/140

executed again. This loop will be repeated until count is incremented to 11 and the predicate expression returns False.

13.2 Printing The Integers From 1 to 100

The previous program can be adjusted in a number of ways to achieve different results. For example, the following program prints the integers from 1 to 100 by changing the 10 in the predicate expression to 100. A Write() function is used in this program so that its output is displayed on the same line until it encounters the wrap margin in MathPiperIDE (which can be set in Utilities -> Buffer Options...).

%mathpiper

// Print the integers from 1 to 100.

count := 1;While(count <= 100)[ Write(count,,); count := count + 1; //Increment count by 1.];

%/mathpiper

%output,preserve="false" Result: True Side Effects: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23, 24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43, 44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63, 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83, 84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100. %/output

(Note: In MathPiperIDE, the above numbers will all be on a single line.)

13.3 Printing The Odd Integers From 1 To 99

The following program prints the odd integers from 1 to 99 by changing the increment value in the increment expression from 1 to 2:

%mathpiper

//Print the odd integers from 1 to 99.

22672268

2269

227022712272227322742275

2276

2277

2278

227922802281228222832284

2285

2286228722882289229022912292229322942295

2296

2297

22982299

2300

2301

Page 83: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 83/140

x := 1; While(x <= 100)[ Write(x,,); x := x + 2; //Increment x by 2.];

%/mathpiper

%output,preserve="false" Result: True Side Effects: 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43, 45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83, 85,87,89,91,93,95,97,99. %/output

13.4 Printing The Integers From 1 To 100 In Reverse Order

Finally, the following program prints the integers from 1 to 100 in reverse order:

%mathpiper

//Print the integers from 1 to 100 in reverse order.

x := 100; While(x >= 1)[ Write(x,,); x := x - 1; //Decrement x by 1.];

%/mathpiper

%output,preserve="false" Result: True Side Effects: 100,99,98,97,96,95,94,93,92,91,90,89,88,87,86,85,84,83,82, 81,80,79,78,77,76,75,74,73,72,71,70,69,68,67,66,65,64,63, 62,61,60,59,58,57,56,55,54,53,52,51,50,49,48,47,46,45,44, 43,42,41,40,39,38,37,36,35,34,33,32,31,30,29,28,27,26,25, 24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4, 3,2,1. %/output

2302

23032304230523062307

2308

23092310231123122313231423152316

2317

2318

2319

2320

2321

23222323232423252326

2327

23282329233023312332233323342335233623372338

Page 84: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 84/140

In order to achieve the reverse ordering, this program had to initialize x to 100, check to see if x was greater than or equal to 1 (x >= 1), and decrement x by subtracting 1 from it instead of adding 1 to it.

13.5 Expressions Inside Of Code Blocks Are Indented

In the programs in the previous sections which use While loops, notice that the expressions which are inside of the While() function's code block are indented. These expressions do not need to be indented to execute properly, but doing so makes the program easier to read.

13.6 Long-Running Loops, Infinite Loops, & Interrupting Execution

It is easy to create a loop that will execute a large number of times, or even an infinite number of times, either on purpose or by mistake. When you execute a program that contains an infinite loop, it will run until you tell MathPiper to interrupt its execution. This is done by opening the MathPiper console and then pressing the "Halt Calculation" button which in the upper left corner of the console.

Lets experiment with the Halt Calculation button by executing a program that contains an infinite loop and then stopping it:

%mathpiper

//Infinite loop example program.

x := 1;While(x < 10)[ x := 3; //Oops, x is not being incremented!. ];

%/mathpiper

%output,preserve="false" Processing.... %/output

Since the contents of x is never changed inside the loop, the expression x < 10 always evaluates to True which causes the loop to continue looping. Notice that the %output fold contains the word "Processing..." to indicate that the program is still running the code.

Execute this program now and then interrupt it using the Halt Calculation button. When the program is interrupted, the %output fold will display the message "User interrupted calculation" to indicate that the program was

233923402341

2342

2343234423452346

2347

234823492350235123522353

23542355

2356

2357

23582359236023612362

2363

236423652366

2367236823692370

237123722373

Page 85: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 85/140

interrupted. After a program has been interrupted, the program can be edited and then rerun.

13.7 A Program That Simulates Rolling Two Dice 50 Times

The following program is larger than the previous programs that have been discussed in this book, but it is also more interesting and more useful. It uses a While() loop to simulate the rolling of two dice 50 times and it records how many times each possible sum has been rolled so that this data can be printed. The comments in the code explain what each part of the program does. (Remember, if you copy this program to a MathPiperIDE worksheet, you can use rectangular selection mode to easily remove the line numbers).

%mathpiper/* This program simulates rolling two dice 50 times.*/

/* These variables are used to record how many times a possible sum of two dice has been rolled. They are all initialized to 0 before the simulation begins.*/numberOfTwosRolled := 0;numberOfThreesRolled := 0;numberOfFoursRolled := 0;numberOfFivesRolled := 0;numberOfSixesRolled := 0;numberOfSevensRolled := 0;numberOfEightsRolled := 0;numberOfNinesRolled := 0;numberOfTensRolled := 0;numberOfElevensRolled := 0;numberOfTwelvesRolled := 0;

//This variable keeps track of the number of the current roll.roll := 1;

Echo("These are the rolls:");

/* The simulation is performed inside of this While loop. The number of times the dice will be rolled can be changed by changing the number 50 which is in the While function's predicate expression.*/While(roll <= 50)

23742375

2376

2377237823792380238123822383

2384238523862387

2388238923902391239223932394239523962397239823992400240124022403

24042405

2406

240724082409241024112412

Page 86: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 86/140

[ //Roll the dice. die1 := RandomInteger(6); die2 := RandomInteger(6); //Calculate the sum of the two dice. rollSum := die1 + die2; /* Print the sum that was rolled. Note: if a large number of rolls is going to be performed (say > 1000), it would be best to comment out this Write() function so that it does not put too much text into the output fold. */ Write(rollSum,,); /* These If() functions determine which sum was rolled and then add 1 to the variable which is keeping track of the number of times that sum was rolled. */ If(rollSum = 2, numberOfTwosRolled := numberOfTwosRolled + 1); If(rollSum = 3, numberOfThreesRolled := numberOfThreesRolled + 1); If(rollSum = 4, numberOfFoursRolled := numberOfFoursRolled + 1); If(rollSum = 5, numberOfFivesRolled := numberOfFivesRolled + 1); If(rollSum = 6, numberOfSixesRolled := numberOfSixesRolled + 1); If(rollSum = 7, numberOfSevensRolled := numberOfSevensRolled + 1); If(rollSum = 8, numberOfEightsRolled := numberOfEightsRolled + 1); If(rollSum = 9, numberOfNinesRolled := numberOfNinesRolled + 1); If(rollSum = 10, numberOfTensRolled := numberOfTensRolled + 1); If(rollSum = 11, numberOfElevensRolled := numberOfElevensRolled+1); If(rollSum = 12, numberOfTwelvesRolled := numberOfTwelvesRolled+1); //Increment the roll variable to the next roll number. roll := roll + 1;];

//Print the contents of the sum count variables for visual analysis.NewLine();NewLine();Echo("Number of Twos rolled: ", numberOfTwosRolled);Echo("Number of Threes rolled: ", numberOfThreesRolled);Echo("Number of Fours rolled: ", numberOfFoursRolled);Echo("Number of Fives rolled: ", numberOfFivesRolled);Echo("Number of Sixes rolled: ", numberOfSixesRolled);Echo("Number of Sevens rolled: ", numberOfSevensRolled);Echo("Number of Eights rolled: ", numberOfEightsRolled);

2413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452

2453245424552456245724582459246024612462

Page 87: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 87/140

Echo("Number of Nines rolled: ", numberOfNinesRolled);Echo("Number of Tens rolled: ", numberOfTensRolled);Echo("Number of Elevens rolled: ", numberOfElevensRolled);Echo("Number of Twelves rolled: ", numberOfTwelvesRolled);

%/mathpiper

%output,preserve="false" Result: True Side effects: These are the rolls: 4,8,6,4,6,9,7,11,9,3,11,6,11,7,11,4,7,7,8,7,3,6,7,7,7,12,4,

12,7,8,12,6,8,10,10,5,9,8,4,5,3,5,7,7,4,6,7,7,5,8, Number of Twos rolled: 0 Number of Threes rolled: 3 Number of Fours rolled: 6 Number of Fives rolled: 4 Number of Sixes rolled: 6 Number of Sevens rolled: 13 Number of Eights rolled: 6 Number of Nines rolled: 3 Number of Tens rolled: 2 Number of Elevens rolled: 4 Number of Twelves rolled: 3. %/output

13.8 Exercises

For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_13_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called:

book_1_section_13_exercises_john_smith.mpw.

After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:

%mathpiper,title="Exercise 1"

//Sample fold.

%/mathpiper

2463246424652466

2467

24682469247024712472247324742475247624772478247924802481248224832484248524862487

2488

2489249024912492

2493

2494249524962497

2498

2499

2500

Page 88: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 88/140

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

13.8.1 Exercise 1Carefully read all of section 13 up to this point. Evaluate each one of the examples in the sections you read in the MathPiper worksheet you created or in the MathPiper console and verify that the results match the ones in the book. Copy all of the console examples you evaluated into your worksheet so they will be saved but do not put them in a fold.

13.8.2 Exercise 2Create a program which uses a While loop to print the even integers from 2 to 50 inclusive.

13.8.3 Exercise 3Create a program which prints all the multiples of 5 between 5 and 50 inclusive.

13.8.4 Exercise 4Create a program which simulates the flipping of a single coin 500 times. Print the number of times the coin came up heads and the number of times it came up tails after the loop is finished executing.

25012502

250325042505250625072508

250925102511

251225132514

2515251625172518

Page 89: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 89/140

14 Predicate FunctionsA predicate function is a function that either returns True or False. Most predicate functions in MathPiper have names which begin with "Is". For example, IsEven(), IsOdd(), IsInteger(), etc. The following examples show some of the predicate functions that are in MathPiper:

In> IsEven(4)Result> True

In> IsEven(5)Result> False

In> IsZero(0)Result> True

In> IsZero(1)Result> False

In> IsNegativeInteger(-1)Result> True

In> IsNegativeInteger(1)Result> False

In> IsPrime(7)Result> True

In> IsPrime(100)Result> False

There is also an IsBound() predicate function that can be used to determine whether or not a value is bound to a given variable:

In> aResult> a

In> IsBound(a)Result> False

In> a := 1Result> 1

In> IsBound(a)Result> True

In> Unbind(a)Result> True

2519

2520252125222523

25242525

25262527

25282529

25302531

25322533

25342535

25362537

25382539

25402541

25422543

25442545

25462547

25482549

25502551

Page 90: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 90/140

In> aResult> a

In> IsBound(a)Result> False

The complete list of predicate functions is contained in the User Functions/Predicates node in the MathPiperDocs plugin.

14.1 Finding Prime Numbers With A Loop

Predicate functions are very powerful when they are combined with loops because they can be used to automatically make numerous checks. The following program uses a While loop to pass the integers 1 through 20 (one at a time) to the IsPrime() function in order to determine which integers are prime and which integers are not prime:

%mathpiper

//Determine which numbers between 1 and 20 (inclusive) are prime.

x := 1;While(x <= 20)[ primeStatus := IsPrime(x); Echo(x, "is prime: ", primeStatus); x := x + 1;];

%/mathpiper

%output,preserve="false" Result: True Side Effects: 1 is prime: False 2 is prime: True 3 is prime: True 4 is prime: False 5 is prime: True 6 is prime: False 7 is prime: True 8 is prime: False 9 is prime: False 10 is prime: False 11 is prime: True 12 is prime: False

25522553

25542555

25562557

2558

25592560256125622563

2564

2565

2566

25672568256925702571257225732574

2575

2576257725782579258025812582258325842585258625872588258925902591

Page 91: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 91/140

13 is prime: True 14 is prime: False 15 is prime: False 16 is prime: False 17 is prime: True 18 is prime: False 19 is prime: True 20 is prime: False. %/output

This program worked fairly well, but it is limited because it prints a line for each prime number and also each non-prime number. This means that if large ranges of integers were processed, enormous amounts of output would be produced. The following program solves this problem by using an If() function to only print a number if it is prime:

%mathpiper

//Print the prime numbers between 1 and 50 (inclusive).

x := 1;While(x <= 50)[ primeStatus := IsPrime(x); If(primeStatus = True, Write(x,,) ); x := x + 1;];

%/mathpiper

%output,preserve="false" Result: True Side Effects: 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,. %/output

This program is able to process a much larger range of numbers than the previous one without having its output fill up the text area. However, the program itself can be shortened by moving the IsPrime() function inside of the If() function instead of using the primeStatus variable to communicate with it:

%mathpiper

/*

259225932594259525962597259825992600

26012602260326042605

2606

2607

2608

2609261026112612261326142615

2616

2617

261826192620262126222623

2624262526262627

2628

2629

Page 92: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 92/140

Print the prime numbers between 1 and 50 (inclusive). This is a shorter version which places the IsPrime() function inside of the If() function instead of using a variable.*/

x := 1;While(x <= 50)[

If(IsPrime(x), Write(x,,) ); x := x + 1;];

%/mathpiper

%output,preserve="false" Result: True Side Effects: 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,. %/output

14.2 Finding The Length Of A String With The Length() Function

Strings can contain zero or more characters and the Length() function can be used to determine how many characters a string holds:

In> s := "Red"Result> "Red"

In> Length(s)Result> 3

In this example, the string "Red" is assigned to the variable s and then s is passed to the Length() function. The Length() function returned a 3 which means the string contained 3 characters.

The following example shows that strings can also be passed to functions directly:

In> Length("Red")Result> 3

An empty string is represented by two double quote marks with no space in between them. The length of an empty string is 0:

2630263126322633

2634

26352636

263726382639

2640

2641

264226432644264526462647

2648

26492650

26512652

26532654

265526562657

26582659

26602661

26622663

Page 93: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 93/140

In> Length("")Result> 0

14.3 Converting Numbers To Strings With The ToString() Function

Sometimes it is useful to convert a number to a string so that the individual digits in the number can be analyzed or manipulated. The following example shows a number being converted to a string with the ToString() function so that its leftmost and rightmost digits can be placed into variables:

In> number := 523Result> 523

In> stringNumber := ToString(number)Result> "523"

In> leftmostDigit := stringNumber[1]Result> "5"

In> rightmostDigit := stringNumber[ Length(stringNumber) ]Result> "3"

Notice that the Length() function is used here to determine which character in stringNumber held the rightmost digit. Also, keep in mind that when numbers are in string form, operations such as +, -, *, and / cannot be performed on them.

14.4 Finding Prime Numbers Which End With 7 (And Multi-line Function Calls)

Now that we have covered how to turn a number into a string, lets use this ability inside a loop. The following program finds all the prime numbers between 1 and 500 which have a 7 as their rightmost digit. There are three important things which are shown in this program:

1) Function calls can have their parameters placed on more than one line if the parameters are too long to fit on a single line. In this case, a long code block is being placed inside of an If() function.

2) Code blocks (which are considered to be compound expressions) cannot have a semicolon placed after them if they are in a function call. If a semicolon is placed after this code block, an error will be produced.

3) If() functions can be placed inside of other If() functions in order to make more complex decisions. This is referred to as nesting functions.

When the program is executed, it finds 24 prime numbers which have 7 as their

26642665

2666

2667266826692670

26712672

26732674

26752676

26772678

2679268026812682

26832684

2685268626872688

268926902691

269226932694

26952696

2697

Page 94: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 94/140

rightmost digit:

%mathpiper

/* Find all the prime numbers between 1 and 500 which have a 7 as their rightmost digit.*/

x := 1;While(x <= 500)[ //Notice how function parameters can be put on more than one line. If(IsPrime(x), [ stringVersionOfNumber := ToString(x); stringLength := Length(stringVersionOfNumber); //Notice that If() functions can be placed inside of other // If() functions. If(stringVersionOfNumber[stringLength] = "7", Write(x,,) ); ] //Notice that semicolons cannot be placed after code blocks //which are in function calls. ); //This is the close parentheses for the outer If() function. x := x + 1;];

%/mathpiper

%output,preserve="false" Result: True Side Effects: 7,17,37,47,67,97,107,127,137,157,167,197,227,257,277,307,317, 337,347,367,397,457,467,487,. %/output

It would be nice if we had the ability to store these numbers someplace so that they could be processed further and this is discussed in the next section.

14.5 Exercises

For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_14_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's

2698

2699

2700270127022703

2704

27052706270727082709271027112712271327142715271627172718271927202721272227232724

2725

2726272727282729273027312732

27332734

2735

273627372738

Page 95: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 95/140

worksheet would be called:

book_1_section_14_exercises_john_smith.mpw.

After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:

%mathpiper,title="Exercise 1"

//Sample fold.

%/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

14.5.1 Exercise 1Write a program which uses a While loop to determine how many prime numbers there are between 1 and 1000. You do not need to print the numbers themselves, just how many there are.

14.5.2 Exercise 2Write a program which uses a While loop to print all of the prime numbers between 10 and 99 which contain the digit 3 in either their 1's place or their 10's place.

2739

2740

2741274227432744

2745

2746

2747

27482749

2750275127522753

2754275527562757

Page 96: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 96/140

15 Lists: Values That Hold Sequences Of ExpressionsThe list value type is designed to hold expressions in an ordered collection or sequence. Lists are very flexible and they are one of the most heavily used value types in MathPiper. Lists can hold expressions of any type, they can be made to grow and shrink as needed, and they can be nested. Expressions in a list can be accessed by their position in the list (similar to the way that characters in a string are accessed) and they can also be replaced by other expressions.

One way to create a list is by placing zero or more expressions separated by commas inside of a pair of braces {}. In the following example, a list is created that contains various expressions and then it is assigned to the variable x:

In> exampleList := {7,42,"Hello",1/2,var}Result> {7,42,"Hello",1/2,var}

In> exampleListResult> {7,42,"Hello",1/2,var}

The number of expressions in a list can be determined with the Length() function:

In> Length({7,42,"Hello",1/2,var})Result> 5

A single expression in a list can be accessed by placing a set of brackets [] to the right of the variable that is bound to the list and then putting the expression's position number inside of the brackets (Note: the first expression in the list is at position 1 counting from the left end of the list):

In> exampleList[1]Result> 7

In> exampleList[2]Result> 42

In> exampleList[3]Result> "Hello"

In> exampleList[4]Result> 1/2

In> exampleList[5]Result> var

The 1st and 2nd expressions in this list are integers, the 3rd expression is a

2758

2759276027612762276327642765

276627672768

27692770

27712772

27732774

27752776

2777277827792780

27812782

27832784

27852786

27872788

27892790

2791

Page 97: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 97/140

string, the 4th expression is a rational number and the 5th expression is an unbound variable.

Lists can also hold other lists as shown in the following example:

In> exampleList := {20, 30, {31, 32, 33}, 40}Result> {20,30,{31,32,33},40}

In> exampleList[1]Result> 20

In> exampleList[2]Result> 30

In> exampleList[3]Result> {31,32,33}

In> exampleList[4]Result> 40 The expression in the 3rd position in the list is another list which contains the integers 31, 32, and 33.

An expression in this second list can be accessed by two two sets of brackets:

In> exampleList[3][2]Result> 32

The 3 inside of the first set of brackets accesses the 3rd member of the first list and the 2 inside of the second set of brackets accesses the 2nd member of the second list.

15.1 Append() & Nondestructive List OperationsAppend(list, expression)

The Append() function adds an expression to the end of a list:

In> testList := {21,22,23}Result> {21,22,23}

In> Append(testList, 24)Result> {21,22,23,24}

However, instead of changing the original list, Append() creates a copy of the original list and appends the expression to the copy. This can be confirmed by evaluating the variable testList after the Append() function has been called:

27922793

2794

27952796

27972798

27992800

28012802

28032804280528062807

2808

28092810

281128122813

2814

2815

28162817

28182819

282028212822

Page 98: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 98/140

In> testListResult> {21,22,23}

Notice that the list that is bound to testList was not modified by the Append() function. This is called a nondestructive list operation and most MathPiper functions that manipulate lists do so nondestructively. To have the new list bound to the variable that is being used, the following technique can be employed:

In> testList := {21,22,23}Result> {21,22,23}

In> testList := Append(testList, 24)Result> {21,22,23,24}

In> testListResult> {21,22,23,24}

After this code has been executed, the new list has indeed been bound to testList as desired.

There are some functions, such as DestructiveAppend(), which do change the original list and most of them begin with the word "Destructive". These are called "destructive functions" and they are advanced functions which are not covered in this book.

15.2 Using While Loops With Lists

Functions that loop can be used to select each expression in a list in turn so that an operation can be performed on these expressions. The following program uses a While loop to print each of the expressions in a list:

%mathpiper

//Print each number in the list.

testList := {55,93,40,21,7,24,15,14,82};index := 1;While(index <= Length(testList))[ Echo(index, "- ", testList[index]); index := index + 1;];

%/mathpiper

28232824

28252826282728282829

28302831

28322833

28342835

28362837

2838283928402841

2842

284328442845

2846

2847

2848

2849

285028512852

28532854

2855

Page 99: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 99/140

%output,preserve="false" Result: True Side Effects: 1 - 55 2 - 93 3 - 40 4 - 21 5 - 7 6 - 24 7 - 15 8 - 14 9 - 82. %/output

A loop can also be used to search through a list. The following program uses a While() function and an If() function to search through a list to see if it contains the number 53. If 53 is found in the list, a message is printed:

%mathpiper

//Determine if 53 is in the list.

testList := {18,26,32,42,53,43,54,6,97,41};index := 1;While(index <= Length(testList))[ If(testList[index] = 53, Echo("53 was found in the list at position", index)); index := index + 1;];

%/mathpiper

%output,preserve="false" Result: True Side Effects: 53 was found in the list at position 5. %/output

When this program was executed, it determined that 53 was present in the list at position 5.

28562857285828592860286128622863286428652866286728682869

287028712872

2873

2874

2875

2876

2877287828792880288128822883

2884

288528862887288828892890

28912892

Page 100: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 100/140

15.2.1 Using A While Loop And Append() To Place Values Into A ListIn an earlier section it was mentioned that it would be nice if we could store a set of values for later processing and this can be done with a While loop and the Append() function. The following program creates an empty list and assigned it to the variable primes. The While loop and the IsPrime() function is then used to locate the prime integers between 1 and 50 and the Append() function is used to place them in the list. The last part of the program then prints some information about the numbers that were placed into the list:

%mathpiper

//Place the prime numbers between 1 and 50 (inclusive) into a list.

//Create an empty list.primesList := {};index := 1;While(index <= 50)[ /* If x is prime, append it to the end of the list and then assign the new list that is created to the variable 'primes'. */ If(IsPrime(index), primesList := Append(primesList, index ) ); index := index + 1;];

//Print information about the primes that were found.Echo("Primes ", primesList);Echo("The number of primes in the list = ", Length(primesList) );Echo("The first number in the list = ", primesList[1] );%/mathpiper

%output,preserve="false" Result: True Side Effects: Primes {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47} The number of primes in the list = 15 The first number in the list = 2. %/output

The ability to place values into a list with a loop is very powerful and we will be using this ability throughout the rest of the book.

2893

2894289528962897289828992900

2901

2902

29032904

2905

2906290729082909291029112912291329142915

2916291729182919

2920

29212922292329242925292629272928

29292930

Page 101: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 101/140

15.3 Exercises

For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_15a_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called:

book_1_section_15a_exercises_john_smith.mpw.

After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:

%mathpiper,title="Exercise 1"

//Sample fold.

%/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

15.3.1 Exercise 1Create a program that uses a While loop and an IsOdd() predicate function to analyze the following list and then print the number of odd numbers it contains.

{73,94,80,37,56,94,40,21,7,24,15,14,82,93,32,74,22,68,65,52,85,61,46,86,25}

15.3.2 Exercise 2Create a program that uses a While loop and an IsNegativeNumber() function to copy all of the negative numbers in the following list into a new list. Use the variable negativeNumbersList to hold the new list. Print the contents of the list after it has been created.

{36,-29,-33,-6,14,7,-16,-3,-14,37,-38,-8,-45,-21,-26,6,6,38,-20,33,41,-4,24,37,40,29}

15.3.3 Exercise 3Create one program that uses a single While loop to analyze the following list and then print the following information about it:

1) The largest number in the list.2) The smallest number in the list.3) The sum of all the numbers in the list.

2931

2932293329342935

2936

2937293829392940

2941

2942

2943

29442945

2946294729482949

2950

29512952295329542955

29562957

295829592960

296129622963

Page 102: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 102/140

{73,12,80,37,56,94,40,21,7,24,15,14,82,93,32,74,22,68,65,52,85,61,46,86,25}

Hint: the following program finds the largest number in a list and it can be used as a starting point for solving this exercise.

%mathpiper

/* The variable that keeps track of the largest number encountered so far needs to be initialized to the lowest possible value it may hold. Why?*/

largest := 0;

numbersList := {4,6,7,9,2,1,3};

index := 1;

While(index <= Length(numbersList) )[ Echo("Largest: ", largest); If(numbersList[index] > largest, largest := numbersList[index]); index := index + 1;];

Echo("The largest number in the list is: ", largest);

%/mathpiper

15.4 The ForEach() Looping Function

The ForEach() function uses a loop to index through a list like the While() function does, but it is more flexible and automatic. ForEach() also uses bodied notation like the While() function and here is its calling format:

ForEach(variable, list) body

ForEach() selects each expression in a list in turn, assigns it to the passed-in "variable", and then executes the expressions that are inside of "body". Therefore, body is executed once for each expression in the list.

15.5 Print All The Values In A List Using A ForEach() function

This example shows how ForEach() can be used to print all of the items in a list:

2964

29652966

2967

29682969297029712972

2973

2974

2975

29762977297829792980298129822983

2984

2985

2986

298729882989

299029912992

2993

2994

Page 103: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 103/140

%mathpiper

//Print all values in a list.

ForEach(value, {50,51,52,53,54,55,56,57,58,59})[ Echo(value); ];

%/mathpiper

%output,preserve="false" Result: True Side Effects: 50 51 52 53 54 55 56 57 58 59. %/output

15.6 Calculate The Sum Of The Numbers In A List Using ForEach()

In previous examples, counting code in the form x := x + 1 was used to count how many times a While loop was executed. The following program uses a ForEach() function and a line of code similar to this counter to calculate the sum of the numbers in a list:

%mathpiper

/* This program calculates the sum of the numbers in a list.*/

//This variable is used to accumulate the sum.sum := 0;ForEach(number, {1,2,3,4,5,6,7,8,9,10} )[ /* Add the contents of x to the contents of sum

2995

2996

2997299829993000

3001

300230033004300530063007300830093010301130123013301430153016

3017

3018301930203021

3022

3023302430253026

30273028

3029303030313032

Page 104: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 104/140

and place the result back into sum. */ sum := sum + number; //Print the sum as it is being accumulated. Write(sum,,);];

NewLine(); NewLine();Echo("The sum of the numbers in the list = ", sum);%/mathpiper

%output,preserve="false" Result: True Side Effects: 1,3,6,10,15,21,28,36,45,55, The sum of the numbers in the list = 55. %/output

In the above program, the integers 1 through 10 were manually placed into a list by typing them individually. This method is limited because only a relatively small number of integers can be placed into a list this way. The following section discusses an operator which can be used to automatically place a large number of integers into a list with very little typing.

15.7 The .. Range Operatorfirst .. last

A programmer often needs to create a list which contains consecutive integers and the .. "range" operator can be used to do this. The first integer in the list is placed before the .. operator and the last integer in the list is placed after it (Note: there must be a space immediately to the left of the .. operator and a space immediately to the right of it or an error will be generated.). Here are some examples:

In> 1 .. 10Result> {1,2,3,4,5,6,7,8,9,10}

In> 10 .. 1Result> {10,9,8,7,6,5,4,3,2,1}

In> 1 .. 100Result> {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,

3033303430353036303730383039

3040

3041

3042

30433044304530463047304830493050

30513052305330543055

3056

305730583059306030613062

30633064

30653066

30673068

Page 105: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 105/140

21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100}

In> -10 .. 10Result> {-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10}

As these examples show, the .. operator can generate lists of integers in ascending order and descending order. It can also generate lists that are very large and ones that contain negative integers.

Remember, though, if one or both of the spaces around the .. are omitted, an error is generated:

In> 1..3Result> Error parsing expression, near token .3.

15.8 Using ForEach() With The Range Operator To Print The Prime Numbers Between 1 And 100

The following program shows how to use a ForEach() function instead of a While() function to print the prime numbers between 1 and 100. Notice that loops that are implemented with ForEach() often require less typing than their While() based equivalents:

%mathpiper

/* This program prints the prime integers between 1 and 100 using a ForEach() function instead of a While() function. Notice that the ForEach() version requires less typing than the While() version.*/

ForEach(number, 1 .. 100)[ If(IsPrime(number), Write(number,,) );];

%/mathpiper

%output,preserve="false" Result: True Side Effects: 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71, 73,79,83,89,97,

30693070307130723073

30743075

307630773078

30793080

308130823083

30843085

3086308730883089

3090

309130923093309430953096

3097309830993100

3101

310231033104310531063107

Page 106: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 106/140

. %/output

15.8.1 Using ForEach() And The Range Operator To Place The Prime Numbers Between 1 And 50 Into A ListA ForEach() function can also be used to place values in a list, just the While() function can:

%mathpiper

/* Place the prime numbers between 1 and 50 into a list using a ForEach() function.*/

//Create a new list.primesList := {};ForEach(number, 1 .. 50)[ /* If number is prime, append it to the end of the list and then assign the new list that is created to the variable 'primes'. */ If(IsPrime(number), primesList := Append(primesList, number ) );];

//Print information about the primes that were found.Echo("Primes ", primesList);Echo("The number of primes in the list = ", Length(primesList) );Echo("The first number in the list = ", primesList[1] );%/mathpiper

%output,preserve="false" Result: True Side Effects: Primes {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47} The number of primes in the list = 15 The first number in the list = 2. %/output

As can be seen from the above examples, the ForEach() function and the range operator can do a significant amount of work with very little typing. You will discover in the next section that MathPiper has functions which are even more powerful than these two.

3108

31093110

31113112

3113

3114311531163117

31183119

312031213122312331243125312631273128

3129313031313132

3133

31343135313631373138313931403141

3142314331443145

Page 107: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 107/140

15.8.2 ExercisesFor the following exercises, create a new MathPiperIDE worksheet file called book_1_section_15b_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called:

book_1_section_15b_exercises_john_smith.mpw.

After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:

%mathpiper,title="Exercise 1"

//Sample fold.

%/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

15.8.3 Exercise 1Create a program that uses a ForEach() function and an IsOdd() predicate function to analyze the following list and then print the number of odd numbers it contains.

{73,94,80,37,56,94,40,21,7,24,15,14,82,93,32,74,22,68,65,52,85,61,46,86,25}

15.8.4 Exercise 2Create a program that uses a ForEach() function and an IsNegativeNumber() function to copy all of the negative numbers in the following list into a new list. Use the variable negativeNumbersList to hold the new list. Print the contents of the list after it has been created.

{36,-29,-33,-6,14,7,-16,-3,-14,37,-38,-8,-45,-21,-26,6,6,38,-20,33,41,-4,24,37,40,29}

15.8.5 Exercise 3Create one program that uses a single ForEach() function to analyze the following list and then print the following information about it:

1) The largest number in the list.2) The smallest number in the list.3) The sum of all the numbers in the list.

3146

3147314831493150

3151

3152315331543155

3156

3157

3158

31593160

3161316231633164

3165

31663167316831693170

31713172

317331743175

317631773178

Page 108: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 108/140

{73,94,80,37,56,94,40,21,7,24,15,14,82,93,32,74,22,68,65,52,85,61,46,86,25}

15.8.6 Exercise 4Create one program that does the following: 1) uses a While loop to make a list that contains 1000 random integers between 1 and 100 inclusive. 2) uses a ForEach() function to determine how many integers in the list are prime and use an Echo() function to print this total.

3179

31803181318231833184

Page 109: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 109/140

16 Functions & Operators Which Loop InternallyLooping is such a useful capability that MathPiper has many functions which loop internally. Now that you have some experience with loops, you can use this experience to help you imagine how these functions use loops to process the information that is passed to them.

16.1 Functions & Operators Which Loop Internally To Process Lists

This section discusses a number of functions that use loops to process lists.

16.1.1 TableForm()TableForm(list)

The TableForm() function prints the contents of a list in the form of a table. Each member in the list is printed on its own line and this sometimes makes the contents of the list easier to read:

In> testList := {2,4,6,8,10,12,14,16,18,20}Result> {2,4,6,8,10,12,14,16,18,20}

In> TableForm(testList)Result> TrueSide Effects>2468101214161820

16.1.2 Contains()

The Contains() function searches a list to determine if it contains a given expression. If it finds the expression, it returns True and if it doesn't find the expression, it returns False. Here is the calling format for Contains():

Contains(list, expression)

3185

3186318731883189

3190

3191

3192

319331943195

31963197

3198319932003201320232033204320532063207320832093210

3211

321232133214

Page 110: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 110/140

The following code shows Contains() being used to locate a number in a list:

In> Contains({50,51,52,53,54,55,56,57,58,59}, 53)Result> True

In> Contains({50,51,52,53,54,55,56,57,58,59}, 75)Result> False

The Not() function can also be used with predicate functions like Contains() to change their results to the opposite truth value:

In> Not Contains({50,51,52,53,54,55,56,57,58,59}, 75)Result> True

16.1.3 Find()Find(list, expression)

The Find() function searches a list for the first occurrence of a given expression. If the expression is found, the position of its first occurrence is returned and if it is not found, -1 is returned:

In> Find({23, 15, 67, 98, 64}, 15)Result> 2

In> Find({23, 15, 67, 98, 64}, 8)Result> -1

16.1.4 Count()Count(list, expression)

Count() determines the number of times a given expression occurs in a list:

In> testList := {a,b,b,c,c,c,d,d,d,d,e,e,e,e,e}Result> {a,b,b,c,c,c,d,d,d,d,e,e,e,e,e}

In> Count(testList, c)Result> 3

In> Count(testList, e)Result> 5

In> Count(testList, z)Result> 0

3215

32163217

32183219

32203221

32223223

3224

322532263227

32283229

32303231

3232

3233

32343235

32363237

32383239

32403241

Page 111: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 111/140

16.1.5 Select()Select(list, predicate_function)

Select() returns a list that contains all the expressions in a list which make a given predicate function return True:

In> Select({46,87,59,-27,11,86,-21,-58,-86,-52}, "IsPositiveInteger")Result> {46,87,59,11,86}

In this example, notice that the name of the predicate function is passed to Select() in double quotes. There are other ways to pass a predicate function to Select() but these are covered in a later section.

Here are some further examples which use the Select() function:

In> Select({16,14,82,92,33,74,99,67,65,52}, "IsOdd")Result> {33,99,67,65}

In> Select({16,14,82,92,33,74,99,67,65,52}, "IsEven")Result> {16,14,82,92,74,52}

In> Select(1 .. 75, "IsPrime")Result> {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73}

Notice how the third example uses the .. operator to automatically generate a list of consecutive integers from 1 to 75 for the Select() function to analyze.

16.1.6 The Nth() Function & The [] OperatorNth(list, index)

The Nth() function simply returns the expression which is at a given position in a list. This example shows the third expression in a list being obtained:

In> testList := {a,b,c,d,e,f,g}Result> {a,b,c,d,e,f,g}

In> Nth(testList, 3)Result> c

As discussed earlier, the [] operator can also be used to obtain a single expression from a list:

3242

32433244

32453246

324732483249

3250

32513252

32533254

32553256

32573258

3259

32603261

32623263

32643265

32663267

Page 112: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 112/140

In> testList[3]Result> c

The [] operator can even obtain a single expression directly from a list without needing to use a variable:

In> {a,b,c,d,e,f,g}[3]Result> c

16.1.7 The : Prepend/Append Operatorexpression : list

list : expression

The prepend/append operator is a colon : and it can be used to add an expression to the beginning or end of a list:

In> list := {1,2,3}Result: {1,2,3}

In> abc : listResult: {abc,1,2,3}

In> list : xyzResult: {1,2,3,xyz}

16.1.8 Concat()Concat(list1, list2, ...)

The Concat() function is short for "concatenate" which means to join together sequentially. It takes two or more lists and joins them together into a single larger list:

In> Concat({a,b,c}, {1,2,3}, {x,y,z})Result> {a,b,c,1,2,3,x,y,z}

16.1.9 Insert(), Delete(), & Replace()Insert(list, index, expression)

Delete(list, index)

32683269

32703271

32723273

3274

32753276

32773278

32793280

32813282

3283

328432853286

32873288

3289

Page 113: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 113/140

Replace(list, index, expression)

Insert() inserts an expression into a list at a given index, Delete() deletes an expression from a list at a given index, and Replace() replaces an expression in a list at a given index with another expression:

In> testList := {a,b,c,d,e,f,g}Result> {a,b,c,d,e,f,g}

In> testList := Insert(testList, 4, 123)Result> {a,b,c,123,d,e,f,g}

In> testList := Delete(testList, 4)Result> {a,b,c,d,e,f,g}

In> testList := Replace(testList, 4, xxx)Result> {a,b,c,xxx,e,f,g}

16.1.10 Take() Take(list, amount)Take(list, -amount)Take(list, {begin_index,end_index})

Take() obtains a sublist from the beginning of a list, the end of a list, or the middle of a list. The expressions in the list that are not taken are discarded.

A positive integer passed to Take() indicates how many expressions should be taken from the beginning of a list:

In> testList := {a,b,c,d,e,f,g}Result> {a,b,c,d,e,f,g}

In> Take(testList, 3)Result> {a,b,c}

A negative integer passed to Take() indicates how many expressions should be taken from the end of a list:

In> Take(testList, -3)Result> {e,f,g}

Finally, if a two member list is passed to Take() it indicates the range of expressions that should be taken from the middle of a list. The first value in the

329032913292

32933294

32953296

32973298

32993300

3301

33023303

33043305

33063307

33083309

33103311

33123313

33143315

Page 114: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 114/140

passed-in list specifies the beginning index of the range and the second value specifies its end:

In> Take(testList, {3,5})Result> {c,d,e}

16.1.11 Drop()Drop(list, index)Drop(list, -index)Drop(list, {begin_index,end_index})

Drop() does the opposite of Take() in that it drops expressions from the beginning of a list, the end of a list, or the middle of a list and returns a list which contains the remaining expressions.

A positive integer passed to Drop() indicates how many expressions should be dropped from the beginning of a list:

In> testList := {a,b,c,d,e,f,g}Result> {a,b,c,d,e,f,g}

In> Drop(testList, 3)Result> {d,e,f,g}

A negative integer passed to Drop() indicates how many expressions should be dropped from the end of a list:

In> Drop(testList, -3)Result> {a,b,c,d}

Finally, if a two member list is passed to Drop() it indicates the range of expressions that should be dropped from the middle of a list. The first value in the passed-in list specifies the beginning index of the range and the second value specifies its end:

In> Drop(testList, {3,5})Result> {a,b,f,g}

16.1.12 FillList()FillList(expression, length)

The FillList() function simply creates a list which is of size "length" and fills it

33163317

33183319

3320

332133223323

33243325

33263327

33283329

33303331

33323333

3334333533363337

33383339

3340

3341

Page 115: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 115/140

with "length" copies of the given expression:

In> FillList(a, 5)Result> {a,a,a,a,a}

In> FillList(42,8)Result> {42,42,42,42,42,42,42,42}

16.1.13 RemoveDuplicates()RemoveDuplicates(list)

RemoveDuplicates() removes any duplicate expressions that are contained in a list:

In> testList := {a,a,b,c,c,b,b,a,b,c,c}Result> {a,a,b,c,c,b,b,a,b,c,c}

In> RemoveDuplicates(testList)Result> {a,b,c}

16.1.14 Reverse()Reverse(list)

Reverse() reverses the order of the expressions in a list:

In> testList := {a,b,c,d,e,f,g,h}Result> {a,b,c,d,e,f,g,h}

In> Reverse(testList)Result> {h,g,f,e,d,c,b,a}

16.1.15 Partition()Partition(list, partition_size)

The Partition() function breaks a list into sublists of size "partition_size":

In> testList := {a,b,c,d,e,f,g,h}Result> {a,b,c,d,e,f,g,h}

In> Partition(testList, 2)Result> {{a,b},{c,d},{e,f},{g,h}}

3342

33433344

33453346

3347

33483349

33503351

33523353

3354

3355

33563357

33583359

3360

3361

33623363

33643365

Page 116: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 116/140

If the partition_size does not divide the length of the list evenly, the remaining elements are discarded:

In> Partition(testList, 3)Result> {{a,b,c},{d,e,f}}

The number of elements that Partition() will discard can be calculated by dividing the length of a list by the partition size and obtaining the remainder:

In> Length(testList) % 3Result> 2

Remember that % is the remainder operator. It divides two integers and returns their remainder.

16.1.16 Table() Table(expression, variable, begin_value, end_value, step_amount)

The Table() function creates a list of values by doing the following:

1) Generating a sequence of values between a "begin_value" and an "end_value" with each value being incremented by the "step_amount".

2) Placing each value in the sequence into the specified "variable", one value at a time.

3) Evaluating the defined "expression" (which contains the defined "variable") for each value, one at a time.

4) Placing the result of each "expression" evaluation into the result list.

This example generates a list which contains the integers 1 through 10:

In> Table(x, x, 1, 10, 1)Result> {1,2,3,4,5,6,7,8,9,10}

Notice that the expression in this example is simply the variable 'x' itself with no other operations performed on it.

The following example is similar to the previous one except that its expression multiplies 'x' by 2:

In> Table(x*2, x, 1, 10, 1)Result> {2,4,6,8,10,12,14,16,18,20}

33663367

33683369

33703371

33723373

33743375

3376

3377

33783379

33803381

33823383

3384

3385

33863387

33883389

33903391

33923393

Page 117: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 117/140

Lists which contain decimal values can also be created by setting the "step_amount" to a decimal:

In> Table(x, x, 0, 1, .1)Result> {0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1}

16.1.17 HeapSort()HeapSort(list, compare)

HeapSort() sorts the elements of list into the order indicated by compare with compare typically being the less than operator "<" or the greater than operator ">":

In> HeapSort({4,7,23,53,-2,1}, "<");Result: {-2,1,4,7,23,53}

In> HeapSort({4,7,23,53,-2,1}, ">");Result: {53,23,7,4,1,-2}

In> HeapSort({1/2,3/5,7/8,5/16,3/32}, "<")Result: {3/32,5/16,1/2,3/5,7/8}

In> HeapSort({.5,3/5,.76,5/16,3/32}, "<")Result: {3/32,5/16,.5,3/5,.76}

16.2 Functions That Work With Integers

This section discusses various functions which work with integers. Some of these functions also work with non-integer values and their use with non-integers is discussed in other sections.

16.2.1 RandomIntegerList()RandomIntegerList(length, lowest_possible, highest_possible)

A vector is a list that does not contain other lists. RandomIntegerList() creates a list of size "length" that contains random integers that are no lower than "lowest_possible" and no higher than "highest possible". The following example creates 10 random integers between 1 and 99 inclusive:

In> RandomIntegerList(10, 1, 99)Result> {73,93,80,37,55,93,40,21,7,24}

33943395

33963397

3398

339934003401

34023403

34043405

34063407

34083409

3410

341134123413

3414

3415341634173418

34193420

Page 118: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 118/140

16.2.2 Maximum() & Minimum()Maximum(value1, value2)Maximum(list)

If two values are passed to Maximum(), it determines which one is larger:

In> Maximum(10, 20)Result> 20

If a list of values are passed to Maximum(), it finds the largest value in the list:

In> testList := RandomIntegerList(10, 1, 99)Result> {73,93,80,37,55,93,40,21,7,24}

In> Maximum(testList)Result> 93

The Minimum() function is the opposite of the Maximum() function.

Minimum(value1, value2)Minimum(list)

If two values are passed to Minimum(), it determines which one is smaller:

In> Minimum(10, 20)Result> 10

If a list of values are passed to Minimum(), it finds the smallest value in the list:

In> testList := RandomIntegerList(10, 1, 99)Result> {73,93,80,37,55,93,40,21,7,24}

In> Minimum(testList)Result> 7

16.2.3 Quotient() & Modulo()Quotient(dividend, divisor)Modulo(dividend, divisor)

Quotient() determines the whole number of times a divisor goes into a dividend:

In> Quotient(7, 3)

3421

3422

34233424

3425

34263427

34283429

3430

3431

34323433

3434

34353436

34373438

3439

3440

3441

Page 119: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 119/140

Result> 2

Modulo() determines the remainder that results when a dividend is divided by a divisor:

In> Modulo(7,3)Result> 1

The remainder/modulo operator % can also be used to calculate a remainder:

In> 7 % 2Result> 1

16.2.4 Gcd()Gcd(value1, value2)Gcd(list)

GCD stands for Greatest Common Divisor and the Gcd() function determines the greatest common divisor of the values that are passed to it.

If two integers are passed to Gcd(), it calculates their greatest common divisor:

In> Gcd(21, 56)Result> 7

If a list of integers are passed to Gcd(), it finds the greatest common divisor of all the integers in the list:

In> Gcd({9, 66, 123})Result> 3

16.2.5 Lcm()Lcm(value1, value2)Lcm(list)

LCM stands for Least Common Multiple and the Lcm() function determines the least common multiple of the values that are passed to it.

If two integers are passed to Lcm(), it calculates their least common multiple:

In> Lcm(14, 8)Result> 56

3442

34433444

34453446

3447

34483449

3450

34513452

3453

34543455

34563457

34583459

3460

34613462

3463

34643465

Page 120: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 120/140

If a list of integers are passed to Lcm(), it finds the least common multiple of all the integers in the list:

In> Lcm({3,7,9,11})Result> 693

16.2.6 Sum()Sum(list)

Sum() can find the sum of a list that is passed to it:

In> testList := RandomIntegerList(10,1,99)Result> {73,93,80,37,55,93,40,21,7,24}

In> Sum(testList)Result> 523

In> testList := 1 .. 10Result> {1,2,3,4,5,6,7,8,9,10}

In> Sum(testList)Result> 55

16.2.7 Product()Product(list)

This function has two calling formats, only one of which is discussed here. Product(list) multiplies all the expressions in a list together and returns their product:

In> Product({1,2,3})Result> 6

16.3 Exercises

For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_16_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called:

book_1_section_16_exercises_john_smith.mpw.

After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the

34663467

34683469

3470

3471

34723473

34743475

34763477

34783479

3480

348134823483

34843485

3486

3487348834893490

3491

34923493

Page 121: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 121/140

start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:

%mathpiper,title="Exercise 1"

//Sample fold.

%/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

16.3.1 Exercise 1Create a program that uses RandomIntegerList() to create a 100 member list that contains random integers between 1 and 5 inclusive. Use one Count() call in a loop to determine how many of each digit 1-5 are in the list and then print this information. Hint: you can use the HeapSort() function to sort the generated list to make it easier to check if your program is counting correctly.

Hint: You can use the following code as the starting point for your loop:

ForEach(num, 1 .. 5)[

];

16.3.2 Exercise 2Create a program that uses RandomIntegerList() to create a 100 member list that contains random integers between 1 and 50 inclusive and use Contains() to determine if the number 25 is in the list. Print "25 was in the list." if 25 was found in the list and "25 was not in the list." if it wasn't found.

16.3.3 Exercise 3Create a program that uses RandomIntegerList() to create a 100 member list that contains random integers between 1 and 50 inclusive and use Find() to determine if the number 10 is in the list. Print the position of 10 if it was found in the list and "10 was not in the list." if it wasn't found.

16.3.4 Exercise 4Create a program that uses RandomIntegerList() to create a 100 member list that contains random integers between 0 and 3 inclusive. Use Select() with the IsNonZeroInteger() predicate function to obtain all of the nonzero integers in this list.

34943495

3496

3497

3498

34993500

3501350235033504350535063507

3508

35093510

3511

351235133514351535163517

35183519352035213522

35233524352535263527

Page 122: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 122/140

16.3.5 Exercise 5Create a program that uses Table() to obtain a list which contains the squares of the integers between 1 and 10 inclusive.

352835293530

Page 123: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 123/140

17 Nested LoopsNow that you have seen how to solve problems with single loops, it is time to discuss what can be done when a loop is placed inside of another loop. A loop that is placed inside of another loop it is called a nested loop and this nesting can be extended to numerous levels if needed. This means that loop 1 can have loop 2 placed inside of it, loop 2 can have loop 3 placed inside of it, loop 3 can have loop 4 placed inside of it, and so on.

Nesting loops allows the programmer to accomplish an enormous amount of work with very little typing.

17.1 Generate All The Combinations That Can Be Entered Into A Two Digit Wheel Lock Using A Nested Loop

The following program generates all the combinations that can be entered into a two digit wheel lock. It uses a nested loop to accomplish this with the "inside" nested loop being used to generate one's place digits and the "outside" loop being used to generate ten's place digits.

%mathpiper

/* Generate all the combinations can be entered into a two digit wheel lock.*/

combinationsList := {};ForEach(digit1, 0 .. 9) //This loop is called the "outside" loop.

3531

353235333534353535363537

35383539

35403541

3542354335443545

3546

3547354835493550

3551

3552

Page 124: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 124/140

[ ForEach(digit2, 0 .. 9)//This loop is called the "inside" loop. [ combinationsList := Append(combinationsList, {digit1, digit2}); ];];

Echo(TableForm(combinationsList));%/mathpiper

%output,preserve="false" Result: True Side Effects: {0,0} {0,1} {0,2} {0,3} {0,4} {0,5} {0,6} . . //The middle of the list has not been shown. . {9,3} {9,4} {9,5} {9,6} {9,7} {9,8} {9,9} True. %/output

The relationship between the outside loop and the inside loop is interesting because each time the outside loop cycles once, the inside loop cycles 10 times. Study this program carefully because nested loops can be used to solve a wide range of problems and therefore understanding how they work is important.

17.2 Exercises

For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_17_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called:

book_1_section_17_exercises_john_smith.mpw.

355335543555355635573558

3559

3560

35613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583

35843585358635873588

3589

3590359135923593

3594

Page 125: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 125/140

After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:

%mathpiper,title="Exercise 1"

//Sample fold.

%/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

17.2.1 Exercise 1Create a program that will generate all of the combinations that can be entered into a three digit wheel lock. (Hint: a triple nested loop can be used to accomplish this.)

3595359635973598

3599

3600

3601

36023603

3604360536063607

Page 126: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 126/140

18 User Defined FunctionsIn computer programming, a function is a named section of code that can be called from other sections of code. Values can be sent to a function for processing as part of the call and a function always returns a value as its result. A function can also generate side effects when it is called and side effects have been covered in earlier sections.

The values that are sent to a function when it is called are called arguments or actual parameters and a function can accept 0 or more of them. These arguments are placed within parentheses.

MathPiper has many predefined functions (some of which have been discussed in previous sections) but users can create their own functions too. The following program creates a function called addNums() which takes two numbers as arguments, adds them together, and returns their sum back to the calling code as a result:

In> addNums(num1,num2) := num1 + num2Result> True

This line of code defined a new function called addNums and specified that it will accept two values when it is called. The first value will be placed into the variable num1 and the second value will be placed into the variable num2.

Variables like num1 and num2 which are used in a function to accept values from calling code are called formal parameters. Formal parameter variables are used inside a function to process the values/actual parameters/arguments that were placed into them by the calling code.

The code on the right side of the assignment operator is bound to the function name "addNums" and it is executed each time addNums() is called. The following example shows the new addNums() function being called multiple times with different values being passed to it:

In> addNums(2,3)Result> 5

In> addNums(4,5)Result> 9

In> addNums(9,1)Result> 10

Notice that, unlike the functions that come with MathPiper, we chose to have this function's name start with a lower case letter. We could have had addNums() begin with an upper case letter but it is a convention in MathPiper for user

3608

36093610361136123613

361436153616

36173618361936203621

36223623

362436253626

3627362836293630

3631363236333634

36353636

36373638

36393640

364136423643

Page 127: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 127/140

defined function names to begin with a lower case letter to distinguish them from the functions that come with MathPiper.

The values that are returned from user defined functions can also be assigned to variables. The following example uses a %mathpiper fold to define a function called evenIntegers() and then this function is used in the MathPiper console to assign a list of even integers to the variable "a":

%mathpiper

evenIntegers(endInteger) :=[ resultList := {}; x := 2; While(x <= endInteger) [ resultList := Append(resultList, x); x := x + 2; ]; /*

The result of the last expression which is executed in a function is the result that the function returns to the caller. In this case,resultList is purposely being executed last so that its contents arereturned to the caller.

*/ resultList;];

%/mathpiper

%output,preserve="false" Result: True. %/output

In> a := evenIntegers(10)Result> {2,4,6,8,10}

In> Length(a)Result> 5

The function evenIntegers() returns a list which contains all the even integers from 2 up through the value that was passed into it. The fold was first executed in order to define the evenIntegers() function and make it ready for use. The evenIntegers() function was then called from the MathPiper console and 10 was passed to it.

36443645

3646364736483649

3650

365136523653

36543655365636573658

36593660366136623663366436653666366736683669

3670

367136723673

36743675

36763677

36783679368036813682

Page 128: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 128/140

After the function was finished executing, it returned a list of even integers as a result and this result was assigned to the variable 'a'. We then passed the list that was assigned to 'a' to the Length() function in order to determine its size.

18.1 Global Variables, Local Variables, & Local()

The new evenIntegers() function seems to work well, but there is a problem. The variables 'x' and resultList were defined inside the function as global variables which means they are accessible from anywhere, including from within other functions, within other folds (as shown here):

%mathpiper

Echo(x, ",", resultList);%/mathpiper

%output,preserve="false" Result: True Side Effects: 12 ,{2,4,6,8,10}. %/output

and from within the MathPiper console:

In> xResult> 12

In> resultListResult> {2,4,6,8,10}

Using global variables inside of functions is usually not a good idea because code in other functions and folds might already be using (or will use) the same variable names. Global variables which have the same name are the same variable. When one section of code changes the value of a given global variable, the value is changed everywhere that variable is used and this will eventually cause problems.

In order to prevent errors being caused by global variables having the same name, a function named Local() can be called inside of a function to define what are called local variables. A local variable is only accessible inside the function it has been defined in, even if it has the same name as a global variable. The following example shows a second version of the evenIntegers() function which uses Local() to make 'x' and resultList local variables:

368336843685

3686

3687368836893690

3691

3692

3693

369436953696369736983699

3700

37013702

37033704

370537063707370837093710

371137123713371437153716

Page 129: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 129/140

%mathpiper

/* This version of evenIntegers() uses Local() to make x and resultList local variables*/

evenIntegers(endInteger) :=[ Local(x,resultList); resultList := {}; x := 2; While(x <= endInteger) [ resultList := Append(resultList, x); x := x + 2; ]; /*

The result of the last expression which is executed in a function is the result that the function returns to the caller. In this case,resultList is purposely being executed last so that its contents arereturned to the caller.

*/ resultList;];

%/mathpiper

%output,preserve="false" Result: True. %/output

We can verify that 'x' and resultList are now local variables by first clearing them, calling evenIntegers(), and then seeing what 'x' and resultList contain:

In> Unbind(x, resultList)Result> True

In> evenIntegers(10)Result> {2,4,6,8,10}

In> xResult> x

In> resultList

3717

3718371937203721

37223723372437253726

37273728372937303731

37323733373437353736373737383739374037413742

3743

374437453746

37473748

37493750

37513752

37533754

3755

Page 130: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 130/140

Result> resultList

18.2 Exercises

For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_18_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called:

book_1_section_18_exercises_john_smith.mpw.

After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:

%mathpiper,title="Exercise 1"

//Sample fold.

%/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

18.2.1 Exercise 1Create a function called tenOddIntegers() which returns a list which contains 10 random odd integers between 1 and 99 inclusive.

Hint: You may want to use the RandomIntegerList(), Select(), IsOdd(), and Take() functions.

18.2.2 Exercise 2Create a function called convertStringToList(string) which takes a string as a parameter and returns a list which contains all of the characters in the string. Here is an example of how the function should work:

In> convertStringToList("Hello friend!")Result> {"H","e","l","l","o"," ","f","r","i","e","n","d","!"}

In> convertStringToList("Computer Algebra System")Result> {"C","o","m","p","u","t","e","r"," ","A","l","g","e","b","r","a"," ","S","y","s","t","e","m"}

Hint: Remember, a string can be broken down into individual characters by using an index value inside of brackets [] like this:

3756

3757

3758375937603761

3762

3763376437653766

3767

3768

3769

37703771

377237733774

37753776

3777377837793780

37813782

378337843785

37863787

Page 131: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 131/140

In> string := "Hello"Result: "Hello"

In> string[1]Result: "H"

In> string[2]Result: "e"

In> string[3]Result: "l"

In> string[4]Result: "l"

In> string[5]Result: "o"

Your function should use this indexing technique inside of a loop to append each of these characters to a list.

37883789

37903791

37923793

37943795

37963797

37983799

38003801

Page 132: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 132/140

19 Miscellaneous topics

19.1 Incrementing And Decrementing Variables With The ++ And -- Operators

Up until this point we have been adding 1 to a variable with code in the form of x := x + 1 and subtracting 1 from a variable with code in the form of x := x - 1. Another name for adding 1 to a variable is incrementing it and decrementing a variable means to subtract 1 from it. Now that you have had some experience with these longer forms, it is time to show you shorter versions of them.

19.1.1 Incrementing Variables With The ++ OperatorThe number 1 can be added to a variable by simply placing the ++ operator after it like this:

In> x := 1Result: 1

In> x++;Result: True

In> xResult: 2

Here is a program that uses the ++ operator to increment a loop index variable:

%mathpiper

index := 1;While(index <= 10)[ Echo(index); index++; //The ++ operator increments the index variable.];

%/mathpiper

%output,preserve="false" Result: True Side Effects: 1 2

3802

38033804

38053806380738083809

3810

38113812

38133814

38153816

38173818

3819

3820

3821

382238233824382538263827

3828

382938303831383238333834

Page 133: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 133/140

3 4 5 6 7 8 9 10. %/output

19.1.2 Decrementing Variables With The -- OperatorThe number 1 can be subtracted from a variable by simply placing the -- operator after it like this:

In> x := 1Result: 1

In> x--;Result: True

In> xResult: 0

Here is a program that uses the -- operator to decrement a loop index variable:

%mathpiper

index := 10;While(index >= 1)[ Echo(index); index--; //The -- operator decrements the index variable.];

%/mathpiper

%output,preserve="false" Result: True Side Effects: 10 9 8 7 6 5

383538363837383838393840384138423843

3844

38453846

38473848

38493850

38513852

3853

3854

3855

385638573858385938603861

3862

3863386438653866386738683869387038713872

Page 134: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 134/140

4 3 2 1. %/output

19.1.3 The Break() FunctionThe Break() function is used to end a loop early and here is its calling format:

Break()

The following program has a While loop which is configured to loop 10 times. However, when the loop counter variable index reaches 5, the Break() function is called and this causes the loop to end early:

%mathpiper index := 1; While(index <= 10)[ Echo(index); If(index = 5, Break()); index++;]; %/mathpiper

%output,preserve="false" Result: True Side Effects: 1 2 3 4 5. %/output

When a Break() function is used to end a loop, it is called "breaking out" of the loop. Notice that only the numbers 1-5 are printed in this program.

38733874387538763877

3878

3879

388038813882

38833884388538863887388838893890389138923893389438953896

3897389838993900390139023903390439053906

39073908

Page 135: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 135/140

19.1.4 The Continue() Function

The Continue() function is similar to the Break() function, except that instead of ending the loop, it simply causes it to skip the remainder of the loop for the current loop iteration. Here is the Continue() function's calling format:

Continue()

The following program uses a While loop which is configured to print the integers from 0 to 8. However, the Continue() function is used to skip the execution of the Echo() function when the loop indexing variable index is equal to 5:

%mathpiper index := 0; While(index < 8)[ index++; If(index = 5, Continue()); Echo(index);];

%/mathpiper

%output,preserve="false" Result: True Side Effects: 1 2 3 4 6 7 8. %/output

Notice that the number 5 is not printed when this program is executed.

19.1.5 The Repeat() FunctionThe Repeat() function is a looping function which is similar to While() and

3909

391039113912

3913391439153916

391739183919392039213922392339243925392639273928

3929

393039313932393339343935393639373938393939403941

3942

3943

3944

Page 136: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 136/140

ForEach(), but it is simpler than these two. Here are the two calling formats for Repeat():

Repeat(count) bodyRepeat() body

The first version of Repeat() simply takes an integer argument which indicates how many times it should loop. The following program shows how to use Repeat() to print 4 copies of the word "Hello":

%mathpiper Repeat(4)[ Echo("Hello");]; %/mathpiper

%output,preserve="false" Result: 4 Side Effects: Hello Hello Hello Hello. %/output

The second version of Repeat() does not take any arguments and it is designed to run as an infinite loop. The Break() function is then used to make the Repeat() function stop looping. The following program would print the loop indexing variable index forever, but the Break() function is used to stop the loop after 3 iterations:

%mathpiper index := 1; loopCount := Repeat()[ Echo(index); If(index = 3, Break());

39453946

394739483949

39503951395239533954395539563957

395839593960396139623963396439653966

39673968396939703971

3972397339743975397639773978397939803981

Page 137: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 137/140

index := index + 1;]; Echo("Loop count: ", loopCount); %/mathpiper

%output,preserve="false" Result: True Side Effects: 1 2 3 Loop count: 2. %/output

Notice that Repeat() returns the number of times it actually looped as a result and that this information is assigned to the variable loopCount.

19.1.6 The EchoTime() FunctionComputers are extremely fast, but they still take time to execute programs. Sometimes it is important to determine how long it takes to evaluate a given expression in order to do things like determine if a section of code need to run quicker than it currently is or determine if one piece of code is slower than another. The EchoTime() function is a bodied function which is used to time how long a section of code takes to run and here is its calling format:

EchoTime()expression

The following examples use EchoTime() to determine how long it takes to add the numbers 2 and 3 together and how long it takes to factor 1234567:

In> EchoTime() 2 + 3Result: 5Side Effects:0.000080946 seconds taken.

In> EchoTime() Factor(1234567)Result: 127*9721Side Effects:0.395028773 seconds taken.

In the following program, a ForEach loop is used to have the Factor() function

398239833984398539863987

398839893990399139923993399439953996

39973998

3999

400040014002400340044005

40064007

4008400940104011

4012401340144015

4016

Page 138: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 138/140

factor all the numbers in a list. The EchoTime() function is used to determine how long it takes to do all the factoring:

%mathpiper EchoTime() ForEach(number, {100,54,65,67,344,98,454})[

Echo(number, " - ", Factor(number));]; %/mathpiper

%output,preserve="false" Result: True Side Effects: 100 - 2^2*5^2 54 - 2*3^3 65 - 5*13 67 - 67 344 - 2^3*43 98 - 2*7^2 454 - 2*227 0.262678978 seconds taken.. %/output

Finally, the following program show how to time a code block which prints the numbers from 1 to 100:

%mathpiper EchoTime() [ index := 1; While(index <= 100) [ Write(index,,); If(index % 10 = 0, NewLine()); index++; ]; NewLine();];

%/mathpiper

40174018

4019402040214022

4023402440254026

4027402840294030403140324033403440354036403740384039

40404041

40424043404440454046404740484049405040514052405340544055405640574058

4059

Page 139: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 139/140

%output,preserve="false" Result: True Side Effects: 1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,19,20, 21,22,23,24,25,26,27,28,29,30, 31,32,33,34,35,36,37,38,39,40, 41,42,43,44,45,46,47,48,49,50, 51,52,53,54,55,56,57,58,59,60, 61,62,63,64,65,66,67,68,69,70, 71,72,73,74,75,76,77,78,79,80, 81,82,83,84,85,86,87,88,89,90, 91,92,93,94,95,96,97,98,99,100, 0.055418423 seconds taken.. %/output

19.2 Exercises

For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_19_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called:

book_1_section_19_exercises_john_smith.mpw.

After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:

%mathpiper,title="Exercise 1"

//Sample fold.

%/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

19.2.1 Exercise 1Create a program which uses a While loop to display the numbers from 1 to 50. Use the ++ operator to increment the loop index variable.

19.2.2 Exercise 2Create a program which uses a While loop to display the numbers from 1 to

40604061406240634064406540664067406840694070407140724073407440754076

4077

4078407940804081

4082

4083408440854086

4087

4088

4089

40904091

409240934094

40954096

Page 140: Introduction to Programming With Mathpiper V

v.95b - 08/01/10 Introduction To Programming With MathPiper 140/140

50 in reverse order. Use the -- operator to decrement the loop index variable.

19.2.3 Exercise 3Create a program which uses a Continue() function to cause a While loop which is configured to print the numbers from 1 to 100 to skip printing the number 72.

19.2.4 Exercise 4Create a program which uses the version of the Repeat() function which takes an integer as an argument and the : string concatenation operator to print the following:

HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello

Hint:

In> string := "Hi"Result: "Hi"

In> string := string : "Hi"Result: "HiHi"

19.2.5 Exercise 5In the last example in the EchoTime() section, what operator is being used to format the output into lines of 10 numbers and how is this operator doing this?

40974098

4099410041014102

4103410441054106

41074108410941104111

4112

41134114

41154116

4117411841194120