M Web Magazine Issue 001 (Dec 5, 1996 to Mar 4, 1997)

Teach You, Teach Me

This section of MWM is a tutorial on M. You may have already read how efficient and fast it is; well why not try it out for yourself. It's as easy as they say. This tutorial assumes no knowledge of programming whatsoever.

Our tutorial is based on the Student version of Micronetics Standard M (MSM). For more information about this company jump over to their web page. In order to download a copy of this program check out Chris Bonnici's Download M section. Before you leave this page be sure to bookmark it so that you can find your way back with ease.

We're new to web publishing and the section is appropriately called Teach You, Teach Me (TYTM). The reason for such a name is that we want this tutorial to be as useful to you as is possible on the web. We know what we want to pass on, but we want you, through your feedback, to guide us on this route. Your input could be in the form of general comments for the Feedback part of this e-zine. Here you can give us the green light, hit the expand-topic button and eventually even take us back a step or two.

No two people will generate the same solution to a problem. The approach we have adopted is one we feel lies somewhere between the extremes of coding conventions though our code will lopside towards the lengthier, easier to understand programming style. We welcome any code you send in, be it different approaches to what we present here or other annotated code of your choice. All accepted submissions will be displayed either the Interactive Zone or in The Library.

Direct Mode

The screen below summarizes what MSM looks like when it is loaded. Some of the details appear only in the Student version of MSM; for example, the commercial version will not expire in 1997!

MSM

Anything you type appears next to the command line (>).

For example if you type WRITE "HELLO WORLD" next to the >, you'll get the phrase HELLO WORD appearing on the screen.

Write the command necessary to display the phrase I'm programming!!!

At the command line, you have full line editing facilities, as summarized below:

Key
Action
Example
 
 
Before
After
DEL
Deletes character above the cursor
1234567890
123467890
BackSpace
Deletes character to left of cursor
1234567890
123567890
Ctrl + X
Deletes the entire command line
1234567890
 
Ctrl + D
Deletes all characters from the character under cursor to the end of the command line.
1234567890
1234

The above demonstrates direct-mode programming. In direct mode, a command entered is acted upon immediately, after which you are returned back to the >. This type of programming is good when one wants to place a command (or, as we shall see in a future issue, commands under the microscope). Rather than have an entire program, one can concentrate on the code sequence of interest. Direct mode is also normally used when one is trying to figure out logical errors in a program.

Programming Mode

Programming mode allows one to bundle a number of commands together. Assume you want to direct someone to your house for a party. You print a list such as the one below:

  1. Drive up Big Road until you get to the intersection between Big Road and Tiny Road.
  2. When at the intersection turn to the left.
  3. Drive up until you get to a big oak tree with John Loves Mary etched into it. At that point you should notice an house painted lime green.
  4. ...

The list performs an action (getting a guest to your party); a program drives a computer towards some goal. In order to write a list, you'll need a word processor, with MSM you can make use of its CUA-Style full screen editor. To invoke the editor type in X ^%G (G has to be upper case). Below is a screen shot of the editor.

^%G

To access any menu press key F10. Alternatively you can handle menus using the ALT key (as with Windows programs). The table below, summarizes them

ALT + Calls Up
F File Menu
E Edit Menu
S Search Menu
O Options Menu
N Window Menu
H Help Menu

Independently of whether you bring down a menu using F10 or the ALT combination, you can call up a particular menu item either by moving down using the arrow keys or by pressing the highlighted letter corresponding to the menu command you're interested in. As with GUI's (Graphical User Interface as that found on any version of Windows), some options have a shortcut key combination.

Let's get down to our first program.

Problem: You would like to create a program that calculates simple interest. The simple interest formula is , where I º Interest Earned; P º Principal Amount; R º Interest Rate; T º Time (Years). Your program will ask for P, R and T and will display I together with the total amount (P + I).

Solution:

Call up the editor X ^%G

Choose File -> New. You will be prompted for the Routine Name (a program is called a Routine in M).

Type in a name. A routine name may anything between 1 and 8 characters in length. You could also use mixed case but do remember that M routine names are case sensitive.

Copy the following code. Download a version of this program by clicking here.

Operator Precedence

The operators we will be mentioning today are exponentiation ( ** ), multiplication ( * ), division ( / ), addition ( + ) and subtraction ( - ). Operator Precedence M does not support operator precedence in that all expressions are evaluated left to right.

Brackets ( ) force certain parts of a computation to be performed before others. If one wanted the addition to be performed before the multiplication and division the expression would have to be rewritten as 2*(3+4)/5. Try It!What will the following give? Try working out what MSM will display. Use direct mode to get an immediate result.

WRITE 2**3+4
WRITE 6-3-2-(5*2+1)
WRITE 4.2/1.2
SimpIntÞ ;Program prompts user for the following details:

Þ ; 1. Principal, P

Þ ; 2. Interest Rate, R

Þ ; 3. Time (in years)

Þ ;It then calculates the simple interest based on the formula I = P*R*T/100, where I is the interest rate.

Þ ;It outputs the I and I + P and stops

;ACB - October 1996

10Þ READ #,"Name: ",NAME

20Þ READ !,"Enter Principal: ",P

30Þ READ !,"Enter Rate: ",R

40Þ READ !,"Enter Time (in years): ",T

CalcRtÞ SET I=P*R*T/100 ; Compute Interest

Þ WRITE !!,NAME," will earn ",I," in interest,"

Þ WRITE !,"giving a total of ",P+I

Þ QUIT

The Þ stands for the TAB key on your keyboard.

To run the program, type, at the command line, DO ^SimpInt. (observe the ^ before SimpInt--it is an indication that the routine is saved on secondary storage, your hard disk).

Shutting Down MSM

MSM has had a shutdown program long before Windows 95. As with any serious operating environment, a shutdown will normally ensure that before the computer is switched off, any data held in memory is written to disk (the cache is flushed) thereby guaranteeing data integrity.

In MSM the utility that takes care of this job is SSD. At the command line type D ^SSD. A prompt will confirm your instruction. This will guarantee that MSM will be safely shut down.

From the program above, we can comment on the following:

1. Routine Lines have the following general format:

Label <tab / space> Command Line

Lines that use the structure shown here are SimpInt, 10, 20, 30, 40 and CalcRt. The other lines lack a Label. Thus one can conclude that a Label is not a necessity. The first line of the program normally has a label that corresponds to the name of the routine. The program above would probably look better if all Labels except the first one are removed.

A tab (or space) must come before the command line. Labels are limited to 8 characters although if you enter more than 8, M will only look at the first 8.

2. Order of execution.

Labels themselves do not determine the order of execution of a program. In fact, if labels 10, 20, 30 and 40 are rearranged as below, the program will request the four reads in the same order as it did originally.

Try It! 40Þ READ #,"Name: ",NAME

30Þ READ !,"Enter Principal: ",P

20Þ READ !,"Enter Rate: ",R

10Þ READ !,"Enter Time (in years): ",T

While the above will work, it is clearly more difficult to comprehend. Unlike a computer, humans have well developed reasoning capabilities and such an abuse can make a program more difficult to understand, or, cause the person reading the program to misinterpret what it is really doing. This is something any programmer should try hard to avoid.

Mathematical Function Library - %MFUNC

M supports library routines. There is practically very little difference between a library routine and a normal program. The purpose behind libraries is that they allow programmers to reuse code over and over again. As you create your programs you will discover that some parts are reused quite frequently. Rather than repeating the same code in many different places you write the code inside a routine and call up this routine whenever you need to access the code. One area that many new programmers start from are screen routines. You want all your programs to have as consistent an interface as possible and soon after you "settle in" you'll design these parts (e.g. on the top left hand side you put your name and on the right the date). A library routine can either be a program in its own right or it may also be made up of many programs grouped together inside one shell. %MFUNC is an example of a shell consisting of may mini programs within it. It is provided as standard in MSM. We hope to contribute to the creation of a base of such routines (so if anyone would like to share with us such code, simply e-mail it in).

Below is the list of services found in %MFUNC. To call up a routine in this library have to specify the particular section (called the entry point) of routine. For example, if one wanted to square root of variable X the following is necessary:

SET Y=$$SQR^%MFUNC(X). If, on the other hand, you wanted to display the area of a circle (p R2) the following should do the job:

W $$PI^%MFUNC*(R**2)

Function Description of Function
E() The value of e (2.712818...)
PI() The value of p (3.1415926535897932)
EXP(X) The value of e (2.712818...) raised to the power of X
LOG(X) The logarithm (base 10) of X (LOG10 X)
LN(X) The natural logarithm (base e) of X
PWR(X,Y) The value of X raised to the power of Y (XY)
SQR(X) The square root of the argument X
SIN(X) The trigonometric sine of X
COS(X) The trigonometric cosine of X
TAN(X) The trigonometric tangent of X
COT(X) The trigonometric cotangent of X
SEC(X) The trigonometric secant of X
CSC(X) The trigonometric cosecant of X
ASIN(X) The trigonometric inverse sine of X
ACOS(X) The trigonometric inverse cosine of X
ATAN(X) The trigonometric inverse tangent of X

All the trigonometric functions are expressed in radians rather than degrees. To convert a radian quantity to its equivalent degree amount, the following equation can be used:

radians to degree

3. Comments.

In M, a comment line must commence with a semicolon (;). Anything to the right of the semicolon will not be interpreted. Comments inside a program are called inline documentation and are normally used to help explain / clarify what certain parts of a program do. The routine SimpInt has entire line comments at the beginning and another comment line at CalcRt.

You can consider yourself a good programmer not based only on how incredible a computing task you can achieve, but on whether another programmer can understand what you write. Most professional programs will last for years and throughout their life span will need modifications of all sorts. Unreadable programs are not maintainable and will need complete rewrites. (We would like to know which is the oldest M code still in use today).

4. READ.

READ is the most commonly used form of input into a program via the keyboard. The READ command we are presenting has the following format:

READ <space><format character>,<prompt>,Variable

M is very rigid on where spaces are placed and in the above command line (as with many M commands) a space is used to separate the command keyword (e.g. READ) from the options associated with it; the arguments (e.g. #,"Enter Principal: ",P).

Two <format character> are used in our example: # -> clear the screen and ! -> go to the beginning of the next line. There are others, but we will discuss them in a future issue. The formatting characters are optional.

The optional <prompt> follows. This is the message instructing the user what to do, e.g. "Enter Time (in years): ".

Finally we have the variable. The variable is the name assigned to an item of information. On each run of the program, different values entered by the person running the program can be referenced through that variable name, making it possible utilize whatever has been previously entered elsewhere in the program. For most purposes, one can consider a variable to be a named box. Calling up the name will reveal the contents of that box. From SimpInt we can conclude that a variable may be used to store both numbers and characters. This type of flexibility classifies M as having typeless variables.

Variable names can be anything from 1 to 8 characters in length and must commence with a letter (or the % symbol).

5. SET.

This command is used assign a variable some value. In our example, we assign I the computation P*R*T/100. SET may also be used to assign a constant or literal to a variable, e.g. SET PI=3.142 or SET AUTHOR="ACB". In the foremost example, we place in variable PI; the numeric constant 3.142, while the latter case demonstrates SETing a literal string.

The SET command has the following format: SET <space> variable=expression, where expression is replaced by anything that returns a value.

6. WRITE.

WRITE is used to display a value on the screen. With this command, one may use <format characters>, literals, constants, variables and practically anything that may be SET.

In CalcRt+1, the method used by M programmers to reference a routine line that lacks a label, the cursor is first moved two lines down, after which the contents of variable NAME are displayed followed by the literal " will earn " then by whatever I has been worked out to and finally " in interest,". In CalcRt+2, the result of P+I is shown on the screen.

Syntax: WRITE <space> <expression>

7. QUIT.

QUIT is used to indicate routine termination. In our example, if the command is left out, the program would have still come to an end (as there are no more commands to process) but it is good practice (especially as the tutorial develops further) to use it in all programs.


M can grow with you (or should we say M can shrink with you) in that commands can be written either in full or as shorter equivalents. The table below summarizes the commands we've discussed in this issue:

READ R
SET S
WRITE W
QUIT Q
DO D

Below is the program SimpInt written using the shorter flavors of the commands we talked about. Click here to download the already keyed in program.

 SimpInt2Þ ;Program prompts user for the following details:

Þ ; 1. Principal, P

Þ ; 2. Interest Rate, R

Þ ; 3. Time (in years)

Þ ;It then calculates the simple interest based on the formula I = P*R*T/100, where I is the interest rate.

Þ ;It outputs the I and I + P and stops

;ACB - October 1996

10Þ R #,"Name: ",NAME

20Þ R !,"Enter Principal: ",P

30Þ R !,"Enter Rate: ",R

40Þ R !,"Enter Time (in years): ",T

CalcRtÞ S I=P*R*T/100 ; Compute Interest

Þ W !!,NAME," will earn ",I," in interest,"

Þ W !,"giving a total of ",P+I

Þ Q

To get this version of the program running type D ^SimpInt2.

Bye Bye

In programming, practice makes perfect. We advise you to go out and convert into M any straightforward computation be it currency conversions, areas, volumes, complex interest calculations or equations from other subject areas. Don't forget to send in your code so that we could put it online. If you are not familiar with a topic, but would like to know more, a search engine is the only thing you should need. In the File Menu, you have the options to load (Retrieve), save (Save), and create new (New) routines.

So that you will be regularly reminded whenever a new issue of MWM comes out (simply too much information on the net to remember everything that flickers on your screen) fill in the appropriate form. As the Interactive Zone will be updated between issues, it has it's own separate form.

M, you and the rest of the world.

Many M implementations store routines and data files inside one file, a sort of world within another (your computer). This is not something bad, and normally helps to protect users and programmers from the hassles of the operating systems (Dos, Window 3.11, Windows 95, Windows NT, various flavors of UNIX, etc). Once you get M loaded onto a computer (something quite easy) most of the headaches associated with running normal programs (memory problems, conflict issues, etc) practically disappear (or are very easy to control).

In the student version of MSM this womb is the file EXPLORER.MSM. M vendors therefore provide utility programs that will allow you to copy routines to file so that you can distribute them and also provide programs that will allow you to load routines written by others.

In MSM, the utility ^%RS (Routine Save) is used to copy routines from M to a file. The annotated graphic below assumes that you are saving the files on an IBM compatible computer.

^%RS

In the example, the program SimpInt is being copied to the DOS file simpint.rtn. %RS can be used to save more than one file and also allows one to enter a comment line. This can be very useful when distributing files.

When you want to load a M routine stored as a DOS file, the utility program %RR will do the job gracefully.

^%RR

After pressing enter on the HFS line, you are asked to enter the DOS file name. If you want to load the file simpint.rtn (rtn is a good extension to indicate that the file contains M routines) simply type in its name. If the file is located in a location other than C:\EXP, you would have to specify the path to the file. For example if the file is located on your A drive, you would enter A:\simpint.rtn.

 

The last part of this program will ask if you want to keep the names the routines where saved with. Pressing Enter or N will save the routines in your M environment with the default name (overwriting files having the same name). If you press Y you can choose (for each file) whether to:

Restore the routine using the same name Y
Bypass restoring this routine N
Restore the routine with a different name R
Skip restoring all routines until the routine specified will be processed S
Restore all routines up to an entered routine name C
Abort the restore process. ^

!#@@!!&%**

We aren't going to delve deeply into the area of error messages in this issue, but feel that a few words can save you some of the above.

Programming is rewarding partly because some programming solutions end up being the labor of love, when a simple mistake can take hours and hours to trace with comments such as "this is defective", "there is nothing wrong with the program" and others which if mentioned will degrade the quality of MWM.

We are here to help you and if you have a problem with some code do let us know. It is important that you send in as much information as possible, together with the code (saved using %RS, mentioned in another box in this issue).

Without delving into the actual MSM error messages and their interpretation, error messages can be classified into the following groups:

Syntax are errors that violate M rules. These errors are probably the easiest to find (more so as you become more experienced). In programming, commands require a very rigid format. A small mistake such as a space or spelling mistake will render the instruction unprocessable.

The editor (^%G) has an option (File Menu -> Syntax) that will look up some of these errors. Even if you don't specifically invoke it, when you save the program, a check for these errors will be done automatically.

^%G

When you get a dialog box such as the one shown here, you normally would cancel the save to sort the problem out. In this example we've annotated the error, but in a real life example, you would have to seek it out yourself.

A few tips on how to trace out such errors:

Read the line aloud.

Compare the line to similar lines, observing minute details such as spelling and spaces.

Erase the line, take a short break and type it in again.

Say calm. Unless you're being paid for the code (in which case you should have an original, registered copy of M), sleeping over the problem can work miracles.

Seek help. This should always be your last resort. Funnily enough, some of the pride in programming comes out of having fought and conquered the elements.

Logic Errors are errors in the "reasoning" of a program, which you dictate. Unlike syntax errors logic errors will not be pointed out; you discover a logical error when you get a wrong result. For example, if in your party invitation list in the main article, you tell people to turn right (instead of left) no one will arrive, nor will anyone phone because they couldn't understand the list--the logic of your invitation was incorrect.

Until we discuss dry running check out that all computations / calculations are using the proper variables. If you can't solve it that way, try the running the program (with longer programs one would take the problem section) one line at a time using direct mode. If, for example, you are using variable names greater than 8 characters check that no two variables have the first 8 characters the same.

Another environment that encourages logical errors is the reuse of variables. As explained, a variable is a "box name". If your program puts in a new number inside a variable, the computations succeeding this SET will use the wrong number. Your program should normally have scratch variables and good variables. The foremost variables are dummy variables whose value can be replaced as and when needed, the latter are computational quantities and should only contain the intended value. (more on this in a future issue)

Run-time errors are the result of an unexpected condition that causes the program to come to a halt. Probably the most common type of runtime error that which comes up when you attempt to divide a number by zero.

Try It!Downloading the program SimpInt3. It has a few errors. Try fixing them.

Pass on our Web Address!

E&OE

Next Page

Up/TOC

Tell a Friend

(:-) Have you Subscribed? (:-)


1