------------------------------------------------------------------------- PHYS210 MAPLE PROGRAMMING LAB 1 ------------------------------------------------------------------------- ------------------------------------------------------------------------- IMPORTANT: Maple Programming Guide is available online via Course Notes page, or, explicitly http://www.maplesoft.com/view.aspx?SF=131923/432652/ProgrammingGuide.pdf Excellent reference for full details of topics covered in class/labs, as well as much, much more. PDF file is very large, takes some time to download even with fast network so may want to save a copy if you're working at home In lab, local copy /home/phys210/maple/ProgrammingGuide.pdf Maple User's Manual also available, via Course Notes, or locally as /home/phys210/maple/UserManual.pdf ------------------------------------------------------------------------- ------------------------------------------------------------------------- SETUP ------------------------------------------------------------------------- o Login and open a terminal window. o Also open a browser and point it to these notes via the Syllabus part of the home page o Create the subdirectory maplepgm in your home directory, and cd to it. % cd % mkdir maplepgm % cd maplepgm % pwd /home/phys210d/maplepgm o Copy all of the files in the directory ~phys210/maplepgm. Recall that the * 'globs' to all of the files in ~phys210/maplepgm, and that '.' (the second argument means the working directory). % cp ~phys210/maplepgm/* . o Get a listing of the files % ls err1 errif index.html procs o Copy the following pathname, open a new tab in your browser and paste the text into the URL box /home/phys210/maplepgm/index.html o This will allow you to click on the links to see the contents of each file in ~maplepgm o You can also use 'more' from the terminal window, e.g. % more procs o Remember that for the 'more' command o Space bar moves forward a page o 'b' moves back a page o 'q' quits o Look at the contents of 'procs' using your browser or from the command line with 'more' o IMPORTANT!! We are now going to learn a general technique to start a program such as xmaple from the command line in such a way that you continue to type commands in the terminal window. To do this, simply add an ampersand '&' to the end of the command line (this is called "backgrounding" the command) o Ensure that the working directory for your terminal is ~/maplepgm % pwd /home/phys210d/maplepgm o Start xmaple IN THE BACKGROUND (BE SURE TO END THE COMMAND LINE WITH AN AMPERSAND, & % xmaple & o Read in the procedure definitions in 'procs' > read procs; o Maple will echo the definitions of the procedures myadd := proc(x, y) x + y end proc . . . myif3 := proc(x::numeric) if 0 < x then 1 elif x < 0 then -1 else 0 end if end proc ------------------------------------------------------------------------- NOTES ------------------------------------------------------------------------- o The maple output below is produced by command-line maple: the output from xmaple will appear different ("prettier") but has the same content o In the following, only type in what follows the maple prompt, '>' o If something happens to your xmaple session, or you accidentally exit it, restart using % xmaple & from a terminal with working directory ~/maplepgm ------------------------------------------------------------------------- DISPLAYING PROCEDURE DEFINITIONS ------------------------------------------------------------------------- o Use the 'op' command to see the definition of a procedure > op(myadd); proc(x, y) x + y end proc o Give myadd a whirl and note the output in each case > myadd(2, 3); 5 > myadd(w, z); w + z > myadd(sin(x)^2, cos(x)^2); 2 2 sin(x) + cos(x) o Try > myadd("a", "b"); o What happens? o Does this make any sense? I.e. is there a situation where we would want to compute/represent the sum of two strings? ------------------------------------------------------------------------- TYPE CHECKING ------------------------------------------------------------------------- o Maple has a notion of the 'type' of expressions (best illustrated through example, as below) o Maple has a simple and powerful facility to state what type each argument is expected to be. When a procedure is invoked, the arguments will be checked in turn, and if any is of incorrect type, an error message is generated and the procedure immediately returns o Only the first invalid argument encountered generates an error: if more that one arg is of the wrong type you may/will have to correct them one after another o Look at the definition of 'myadd1' > op(myadd1); proc(x::algebraic, y::algebraic) x + y end proc o IMPORTANT!! ----------------------------------------------------------- To perform type checking of an argument, follow the argument with a double colon (no space between the colons), and then the expected type Will generally want to have type checking for ALL arguments ----------------------------------------------------------- > myadd1(x, 2*y); x + 2 y > myadd1("a", "b"); Error, invalid input: myadd1 expects its 1st argument, x, to be of type algebraic, but received a > myadd1(diff(sin(x),x), diff(x^4, x)); 3 cos(x) + 4 x o Here's an example where we supply a list, which is NOT of type algebraic, as the first argument to 'myadd1' > myadd1([a, b], 2); Error, invalid input: myadd1 expects its 1st argument, x, to be of type algebraic, but received [a, b] o A version of 'myadd' which requires 'numeric' arguments > op(myadd2); proc(x::numeric, y::numeric) x + y end proc > myadd2(2, 3); 5 > myadd2(1.5, 3/2); 3.000000000 > myadd2(x, y); Error, invalid input: myadd2 expects its 1st argument, x, to be of type numeric, but received x o A version of 'myadd' which requires 'integer' arguments > op(myadd3); proc(x::integer, y::integer) x + y end proc > myadd3(3, 5); 8 > myadd3(3.0, 5); Error, invalid input: myadd3 expects its 1st argument, x, to be of type integer, but received 3.0 o IMPORTANT!! ----------------------------------------------------------- KEY TYPES FOR US o algebraic o numeric o integer o float o list ----------------------------------------------------------- o QUESTION o Why wouldn't a sequence, e.g. 1, 2, 3 be a valid type? ------------------------------------------------------------------------- SYNTAX ERRORS (The most basic type of bug encountered in programming) ------------------------------------------------------------------------- o Syntax error -> improper construction of code. o You will be informed of the first error encountered, as well as some information about the location of the error, but will not always be obvious exactly what the error is. o Finding and removing syntax errors is a key talent that must be honed for programming in any language: experience is the primary means to develop the skill (in addition to the acceptance that you have made an error!) o Easiest type of debugging o Finding conceptual (you don't understand exactly what you want to do) and/or implementation (your program doesn't work the way you want it to; i.e. the output is incorrect) errors tends to be more difficult o Look at contents of err1 (using 'more' or browser) ###################################################### # PHYSICS 210 # # Illustrates syntax error in definition of procedure ###################################################### err1 := proc(x,y) x + y end porc; o Read 'err1' into your xmaple session > read err1; on line 8, syntax error, missing operator or `;`: end porc; ^ Error, while reading `err1` o Notice the reference to a line number, the error message, and the caret '^', which indicates where maple thinks the error is (approximately) o WHAT IS THE ERROR? o Will fix it later ------------------------------------------------------------------------- EXERCISE 1 ------------------------------------------------------------------------- o Using your text editor, create the file 'myprocs1' that contains a definition for the following procedure o Procedure name: mysub1 o Arguments: a, b (no restrictions on the type of arguments) o What the procedure does: Computes the difference of a and b Make sure that myprocs1 lives in ~/maplepgm o Read 'myprocs1' into your xmaple session via > read myprocs1; and test it with various input. o If you have one or more syntax errors, try to fix them by o Editing the 'myprocs1' file o Saving 'myprocs1' o Re-reading 'myprocs1' into maple o Iterating as necessary o ASK FOR HELP AS NECESSARY! o Add another procedure definition to 'myprocs1' as follows o mysub2 o Arguments a, b (a must be numeric, b must be integer) o Computes the difference of a and b o Test/debug as before o IMPORTANT: Each time you modify 'myprocs1', be sure to SAVE IT, then reload it into maple using > read myprocs1; ------------------------------------------------------------------------- EXERCISE 2 ------------------------------------------------------------------------- o Fix the error in 'err1' using your text editor, save the file (overwrite previous 'err1'), reread and verify that err1 works o NOTE: When 'err1' is read, maple reports that there is a syntax error 'on line 8', thus useful to see line numbers when you are editing maple source files o If you are using gedit, you can turn on line-numbering via Edit -> Preferences, then check "Display line numbers" box ------------------------------------------------------------------------- PRINT STATEMENT ------------------------------------------------------------------------- o Use 'print' to display (print) one or more values; useful in procedures to output "intermediate" values, since only the last result evaluated in a procedure is returned o Can have arbitrary number of arguments; string arguments especially useful > a := 2; a := 2 > print("The value of a is", a); "The value of a is", 2 > print("Here are three numbers", 1, 17, 42); "Here are three numbers", 1, 17, 42 ------------------------------------------------------------------------- IF STATEMENT ------------------------------------------------------------------------- o HERE AND BELOW RECALL THAT CONSTRUCTS OF THE FORM MEAN THAT (including the "meta-parentheses" <>) IS TO BE REPLACED WITH A SPECIFIC INSTANCE OF A 'something" o General Form o = Boolean expression o = statement sequence if then elif then elif then . . . else end if; o If is false, go on to first 'elif'. If is false, go on to second 'elif' ... If all 'elif' tests are false execute statements after 'else' ------------------------------------------------------------------------- BOOLEAN OPERATORS AND EXPRESSIONS ------------------------------------------------------------------------- o Constructing Boolean expressions (expressions with a true or false value): Relational and Logical Operators o Maple's Boolean values true false o Relational Operators: = -> equal <> -> not equal < -> less than > -> greater than <= -> less than or equal >= -> greater than or equal o Note: These operators also can be used in algebraic expressions, where they are "placeholders" for constructing equations, inequalities, etc. > eqn := x = y; > ineq := 2 * z > 13; o Logical Operators and or not o See programming guides for operator precedence: safest simply to use parentheses to ensure evaluation order is what we want Examples > if 3 > 2 then print("foo") end if; "foo" > if 2 <> (1 + 1) then print("foo") else print("bar") end if; "bar" o The following illustrates two other maple features o Mutiple statements can be type on a single line o A colon (:) can also be used to terminate a statement, and will cause the output from the statement to be suppressed > a := 3: b := 2: c := 5: o Note that there was no output if you terminated the assignment statements with colons o Example using 'and' ... boolean expression is true if BOTH a <= b AND b <= c are true > if (a <= b) and (b <= c) then b else a + c end if; 8 o Example using 'or' ... boolean expression is true if EITHER/BOTH of a < b and a <> c is/are true > if (a < b) or (a <> c) then b else c end if; 5 o Example using 'not' ... not "reverses" value of Boolean expression, > not true; false > not false; true > if not (a > b) then a else b end if; 2 o Can evaluate general (determine its truth value) using 'evalb' procedure (analogous to 'evalf' for floating point evaluation > evalb(a > b); true > evalb(a <= b); false o BEGIN ASIDE: "McCarthy" evaluation rules: evaluation of Boolean expression stops as soon as truth value is known - can have important consequences > a := 10; > if (a > 2) or mylogical(b) then a else b end if; 10 o mylogical(b) does NOT get invoked! o END ASIDE ------------------------------------------------------------------------- SAMPLE PROCEDURES USING IF STATEMENTS ------------------------------------------------------------------------- -------------------------------------------------- o myif: Simple if-then-else with no type checking -------------------------------------------------- > op(myif); proc(a, b) if b < a then a else b end if end proc > myif(3, 2); 3 > myif(3, 10.0); 10.0 o Try an invocation that doesn't seem to make sense ... > myif(3, x); Error, (in myif) cannot determine if this expression is true or false: x < 3 o ... and maple returns an appropriate error message ----------------------------------------------- o myif1: Simple if-then-else with type checking ----------------------------------------------- > op(myif1); proc(a::numeric, b::numeric) if b < a then a else b end if end proc o Note how maple has transformed 'a > b' in the code in the file 'procs' to 'b < a'. The two forms are algebraically equivalent of course. > myif1(10, 3); 10 > myif1(x, 2); Error, invalid input: myif1 expects its 1st argument, a, to be of type numeric, but received x ----------------------------------------------- o myif2: If-then-else with more complicated test ----------------------------------------------- > op(myif2); proc(a::numeric, b::numeric, c::numeric) if 5 < a + b and 10 < a + c then true else false end if end proc > myif2(1,5,12); true > myif2(1,5,6); false --------------------------------- o myif3: Simple If-then-elif-else --------------------------------- > op(myif3); myif3 := proc(x::numeric) if 0 < x then 1 elif x < 0 then -1 else 0 end if end proc > myif3(2); 1 > myif3(-3); -1 > myif3(0); 0 ------------------------------------------------------------------------- EXERCISE 3 ------------------------------------------------------------------------- o Using your text editor, create the file ~/maplepgm/myprocs2 that contains definitions of procedures that do the following (recall that maple is case-sensitive) o Do as many as you can! o Test your procedures interactively --- particularly for myifC try to make your testing exhaustive (i.e. all possible permutations of x1, x2, x3 with respect to "largest" property, including cases where two numbers have the maximum value) o myaddA o Arguments a, b, c (no type checking) o Returns sum of a, b and c o myaddB o Arguments a, b, c (a, b, c must be of integer type) o Returns sum of a, b and c o myaddC o Arguments x, y, z (x, y, must be numeric, z algebraic) o Returns sum of x, y and z o myifA o Arguments a, b (a, b must be numeric) o Returns larger of (sum of a and b) and (product of a and b) o myifB o Arguments a1, a2, a3 (all numeric) o If sum of arguments is positive, returns product of the numbers, if sum of arguments is negative, returns reciprocal of the product of the numbers, otherwise returns 0 o myifC o Arguments x1, x2, x3 (all numeric) o Returns largest of three arguments ------------------------------------------------------------------------- SYNTAX ERRORS IN IF STATEMENT ------------------------------------------------------------------------- o Look at the file 'errif' o Read it into maple > read errif; on line 9, syntax error, missing operator or `;`: a; ^ Error, while reading `errif` ------------------------------------------------------------------------- EXERCISE 4 ------------------------------------------------------------------------- o Find and correct the syntax error(s) in the three procedures defined in 'errif'