TweetFollow Us on Twitter

MPW Calculator
Volume Number:9
Issue Number:1
Column Tag:Jörg's Folder

MPW Calculator Tool in C++

An MPW tool written in bare bones C++ - not with MacApp.

By Jörg Langowski, MacTech Magazine Regular Contributing Author

Note: Source code files accompanying this article are located on MacTech CD-ROM or source code disks.

After a long break, you’ll find another C++ example in my column. Not with MacApp - we’re going back to the basics here and show a simple ‘bare C++’ program that executes as an MPW tool, or in the Simple Input/Output Window environment (SIOW) provided by Apple.

I came across this example reading a book on C++, “Programming in C++”, by Stephen Dewhurst and Kathy Stark (1989, Prentice Hall). I very much recommend this book for those of you who want to get the basic notions of C++ and an idea of its ‘programming flavor’. It may be not as comprehensive as the “C++ programming language” by Stroustrup (Addison-Wesley), or as the manuals that come with Apple’s C++ compiler; but it contains a lot of examples and exercises.

One classic exercise in computer science is to write a parser for algebraic expressions, that is, a program that takes an input string like

(3 + 5) * (-4 + (2 - 9))

and calculates the result of this expression. In fact, what you do to compute that expression is to convert it into an internal representation, and then evaluate that representation.

You can represent the expression given above by a linked list:

where each node of the list either contains an operator or a number. Once the arithmetic expression is given in list form, evaluating it is easy and can be done in a straightforward, object oriented way. Suppose you define a class node (also in listing):

class node {
 protected:
 
 node() {}
 public:
 virtual ~node() {}
 virtual int set (int)
 { cout << "Error: node::set(int) undefined" << eoln;
  return 0;} 
 virtual int eval() 
 { cout << "Error: node::eval() undefined" << eoln; 
 return 0;} 
};

where the constructor and destructor do nothing at the moment; they will have to be overridden by the derived node classes. There are two more virtual methods: eval(), which returns the value of the node, and set(), which can ‘set something’ in the node if defined in a subclass. For the base class, the methods just print error messages and return zero. These methods will be overridden, and they are virtual because we want their behavior to be determined at run time. That is, if we define a pointer mynode *node and assign it an object of a subclass of node, the actual eval() or set() methods used will be the ones corresponding to the subclass of the object that the pointer contains.

We now define two types of subclasses of node: dyadic operators and other stuff. All dyadic operators will be derived from the subclass :

class dyad : public node {
 protected:
 node *left, *right;
 dyad(node *l, node *r) {left=l; right=r;}
 ~dyad() {delete left; delete right;}
};

dyad only defines the two nodes that the operator connects: the constructor assigns these two nodes to two instance variables, and the destructor deletes them again. The classes derived from dyad define the four arithmetic operations, and the assignment (see listing). For example, addition is defined as:

class plus : public dyad {
 public:
 plus(node *l, node *r) : dyad(l,r) {}
 int eval() { return left->eval() + right->eval();} 
};

where the constructor just calls the superclass constructor, and

eval() returns the value of the sum of the values of the left and right hand side of the plus operation.

For the ‘expression tree’ shown above, you need one more class: numbers, which are ‘end nodes’ of the list. Thus, they do not contain pointers to other nodes, but an integer value in an instance variable. Their constructor assigns the value, and their eval() method simply returns it:

class inumber : public node {
 int value;
 public:
 inumber(int v) {value = v;}
 int eval() {return value;}
};

Finally, the unary minus operator (uminus in the listing) will return the negative value of the node that it points to.

The listing contains two more node classes: variables (id) and the assignment operator (equals), Variables contain a pointer to the head of a symbol table, and a pointer to the entry of this variable into the symbol table. The symbol table is a linked list of entries, and the pointer to its head is a static class variable. This means that, unlike instance variables, the pointer is not created again for every object of the class, but only one copy exists. Thus, all objects of this class reference the same symbol table, which is just what you want.

Assume we create a new node for a variable with its name given by the *char pointer nm. The constructor then first looks up the name in the symbol table (see listing, method look); if it is already there, it will put a pointer to the symbol table entry in the instance variable ent of the node. Otherwise, it will add a new entry to the symbol table, put its pointer into ent, make the new entry the head of the list, and change the (static) pointer so that it references the new head. All other variable objects will now have an updated reference to the symbol table.

A variable is assigned a value by the assignment operation equals. When an equals node is created, its right and left hand sides are set just as for the arithmetic operations; when its eval() method is called, the variable on the left hand side is set to the result of the right hand side. No check is done whether the left hand side is really a node of class id; but only those nodes contain a set method. The assignment operation also returns a value (just as in C), the right hand side of the statement.

So now we have defined a syntax tree for simple arithmetic expressions with assignment of variables. If, lets say, root is the pointer to the root of this tree (the times symbol in the drawing), and we call root->eval(), the result returned should be the value of the expression, in our case (3 + 5) * (-4 + (2 - 9)) = -88. With the class definitions given so far, this should work. But how do we set up the syntax tree in the first place? We need a routine, an expression parser, that takes the string expression and constructs the tree from it.

In order to write the parser, we first need to formalize the syntax of our simple arithmetic expressions. Such a formal description would for instance look like this:

<expression> :== <term> { [+|-] <term> }
<term>   :== <factor> { [*|/] <factor> }
<factor> :== <identifier> | <inumber> |
 (<expression >) | -<factor> |
 <identifier> = <expression>

We then define three parser routines that return an object of class node: e(), t(), and f(), returning, respectively, a pointer to an expression, a term, and a factor. Each of these routines makes repeated calls to another routine scan(), which gets the next token from the input stream. A token is a separate syntactic element, such as an open or close bracket, an arithmetic operator, a number or an identifier. scan() returns a character value, either the ascii value of a symbol if the token consists of one symbol, or a special value > 127. For the special values ID and INT, additional information can be found in a static char variable; this string will be used for the value of a number or the name of a variable. Other possible values are BAD (the scanner found something it couldn’t interpret), or EOLN (end of line found).

The first of the three parser routines, e(), is called from the main program (see listing for main()). On entry, one token has been read from the input stream; then e() tries to parse the input into a valid arithmetic expression and assign a pointer to its syntax tree to root. It does so by calling t() (see listing), which makes a term out of one or several factors by calling f(), just like e() makes the expression out of one or several term. When e() encounters a plus or minus sign after a term, is makes a new plus resp. minus node which connects the first term with the next one. Same for t(); here eventually a times or divide node is made, which connects two factors. f(), finally, will look for a number or identifier token and return a pointer to the corresponding node; or it might find an open bracket or a minus sign, after which a new expression or a factor have to follow. When all these recursive calls have been evaluated and no syntax errors have been found, the top-level e() returns the expression’s syntax tree.

In order to get the value of the expression, all we have to do then is call root->eval(), and the syntax tree will be evaluated as described above.

As long as no syntax errors are found, the main program loops continuously and asks for new expressions; the names and values of identifiers are remembered from one evaluation to the next, so you can play around with stored values a little.

As you may imagine, it is not too difficult to add on to this extremely simple calculator program e.g. to implement exponentiation or to include functions like exp(), log() etc. The constructed syntax tree could also serve in a bigger program as an internal representation of a function that the user has typed in and that has to be evaluated a lot of times (and computed fast). One could even imagine to generate real machine code out of the syntax tree, which makes this program some kind of a rudimentary compiler. We’ll add to the example during the next columns.

On the source code disk, I have compiled two versions of the program, one as an MPW tool, and the other one using the Simple Input/Output Window mechanism. Actually, the only thing that has to be changed is the linking. The MPW sequence to create the two versions of the program look like the following:

cplus calc.cp
Link -w -c 'MPS ' -t MPST 
 calc.cp.o 
 "{CLibraries}"StdCLib.o 
 "{Libraries}"ToolLibs.o 
 "{Libraries}"Runtime.o 
 "{Libraries}"Interface.o 
 "{CLibraries}"CPlusLib.o 
 -o calc

Rez -a "{MPW}"Interfaces:Rincludes:SIOW.r -o calcAppl
Link -w -c 'JLMT' -t 'APPL' 
 calc.cp.o 
 "{CLibraries}"StdClib.o 
 "{MPW}"Libraries:Libraries:SIOW.o 
 "{Libraries}"Runtime.o 
 "{Libraries}"Interface.o 
 "{CLibraries}"CPlusLib.o 
 -o calcAppl

So the second version can be run also by those of you who don’t have MPW.

FORTHcoming

I’m still waiting for those MacForth contributions coming in we’d really like to see more of that in MacTutor. I’m sure there are quite a few of you satisfied MacForth users who have something interesting to write about. Please contact me: I promise that you get your space in this column. My network address has changed in the meantime, since our institute is going from the Bitnet to the Internet world; so in the future, please send messages to either of those three addresses (in order of preference):

 jl@macjl.embl-grenoble.fr
 langowski.j@applelink.apple.com
 langowsk@titan.embl-grenoble.fr 

(note the missing last letter in the name)

Meanwhile, we do have news from the Forth world. I don’t have to tell you that the NEON successor, Yerk, keeps being updated faster than I can write about it; you know that you can get the current version by ftp from oddjob.uchicago.edu. Mops, the NEON lookalike with real 680x0 machine code, can also be found there.

But here is something very interesting for those of you who used and liked Mach2, the Forth in which I did most of my examples here: Two users of Mach2, John Fleming who works at Motorola, and Steven Wiley, a molecular biologist at the University of Utah, got together and made all those modifications to Mach2 that the implementers should have done two years ago; now it is System7 and 32-bit compatible. It may also be soon in the public domain (non-commercial) like Yerk is, with the full source code available. You’ll hear more about it in one of the next columns. Until then.

Listing: The MPW calculator tool
// 
// calc.cp
//
// a simple calculator program
// based on an example from Dewhurst/Stark
// "Programming in C++"
//
// J. Langowski November 1992
//

#include <Ctype.h>
#include <StdIO.h>
#include <String.h>
#include <Stream.h>
#include <StdLib.h>

#define NIL 0

// basic syntax tree structure
//
class node {
 protected:
 node() {}
 public:
 virtual ~node() {}
 virtual int set (int)
 { cout << "Error: node::set(int) undefined" << eoln;
  return 0;} 
 virtual int eval() 
 { cout << "Error: node::eval() undefined" << eoln; 
 return 0;} 
};

class dyad : public node {
 protected:
 node *left, *right;
 dyad(node *l, node *r) {left=l; right=r;}
 ~dyad() {delete left; delete right;}
};
// operators
//
class plus : public dyad {
 public:
 plus(node *l, node *r) : dyad(l,r) {}
 int eval() { return left->eval() + right->eval();} 
};

class minus : public dyad {
 public:
 minus(node *l, node *r) : dyad(l,r) {}
 int eval() { return left->eval() - right->eval();}
};

class times : public dyad {
 public:
 times(node *l, node *r) : dyad(l,r) {}
 int eval() { return left->eval() * right->eval();}
};

class divide : public dyad {
 public:
 divide(node *l, node *r) : dyad(l,r) {}
 int eval() { return left->eval() / right->eval();}
};

class uminus : public node {
 node *operand;
 public:
 uminus(node *o) {operand = o;}
 ~uminus() {delete operand;}
 int eval() {return -operand->eval();}
};

class inumber : public node {
 int value;
 public:
 inumber(int v) {value = v;}
 int eval() {return value;}
};


// identifier table
//
class id;

class entry {
 char *name;
 int value;
 entry *next;
 entry (char *nm, entry *n) {
 name = strcpy (new char[strlen(nm) + 1], nm);
 value = 0;
 next = n;
 }
 friend id;
};

class id : public node {
 static entry *symtab;
 entry *ent;
 entry *look(char *);
 public:
 id(char *nm) {ent = look(nm);}
 int set(int i) {return ent->value = i;}
 int eval() {return ent->value;}
};

entry *id::look(char *nm) {
 for(entry *p = symtab; p; p = p->next)
 if(strcmp(p->name,nm) == 0) return p;


 return symtab = new entry(nm,symtab);
}

entry *id::symtab = NIL;

// assignment
//
class equals : public dyad {
 public:
 equals(node *t,node *e) : dyad(t,e) {}
 int eval()
 { return left->set(right->eval()); }
};


// parsing + evaluation
//

static char token;   // current token 
static char line[81];   // for reading identifiers + numbers
enum {ID = char(128), INT, EOLN, BAD}; // special tokens

node *e(), *t(), *f();    // parser routines 
 // for expression, term, factor

// input stream scanner, returns next token
//
char scan() {
 char c;
 while (1)
 switch (c = cin.get()) {
 case '+': case '-': case '*': case '/':
 case '(': case ')': case '=':
 return c;
 case ' ': case '\t':
 continue;
 case '\n': case '\r':
 return EOLN;
 default:
 if (isdigit(c)) {
 char *s = line;
 do*s++ = c;
 while(isdigit(c = cin.get()));
 *s = '\0'; 
 // terminate string just read
 cin.putback(c); 
 // had read one too much
 return INT;
 }
 
 if (isalpha(c)) {
 char *s = line;
 do*s++ = c;
 while(isalnum(c = cin.get()));
 *s = '\0'; 
 // terminate string just read
 cin.putback(c); 
 // had read one too much
 return ID;
 }
 
 return BAD; 
 // if nothing fits, syntax error
 }
}

// simple error routine
//
void error() { cout << "Syntax error." << endl; exit(255); }

// parser routines for expression, term, factor
//

// expression = term (+ -) term
node *e() {
 node *root = t();
 while (1)
 switch (token) {
 case '+':
 token = scan();
 root = new plus(root, t()); 
 break;
 case '-':
 token = scan();
 root = new minus(root, t());
 break;
 default:
 return root;
 }
}

// term = factor (* /) factor
node *t() {
 node *root = f();
 while (1)
 switch (token) {
 case '*':
 token = scan();
 root = new times(root, t()); 
 break;
 case '/':
 token = scan();
 root = new divide(root, t()); 
 break;
 default:
 return root;
 }
}

// factor = identifier | number | expression | -factor
node *f() {
 node *root = NIL;
 switch (token) {
 case ID:
 root = new id(line);
 token = scan();
 if (token == '=') {
 token = scan();
 root = new equals(root, e());
 }
 return root;
 case INT:
 root = new inumber(atoi(line));
 token = scan();
 return root;
 case '(':
 token = scan();
 root = e();
 if (token != ')' ) error();
 token = scan();
 return root;
 case '-':
 token = scan();
 return new uminus(f());
 default:
 error();
 }
}

// main program
//

void main() {
 node *root = NIL;
 while (1) {
 cout << "Enter expression: " << endl;
 token = scan();
 root = e();

 if (token == BAD) error();
 
 if (root != NIL)
 { 
     cout << "Result = " << root->eval() << endl;
     delete root; 
 }
 }
}

 
AAPL
$100.96
Apple Inc.
-0.83
MSFT
$47.52
Microsoft Corpora
+0.84
GOOG
$596.08
Google Inc.
+6.81

MacTech Search:
Community Search:

Software Updates via MacUpdate

Audio Hijack Pro 2.11.3 - Record and enh...
Audio Hijack Pro drastically changes the way you use audio on your computer, giving you the freedom to listen to audio when you want and how you want. Record and enhance any audio with Audio Hijack... Read more
Airfoil 4.8.9 - Send audio from any app...
Airfoil allows you to send any audio to AirPort Express units, Apple TVs, and even other Macs and PCs, all in sync! It's your audio - everywhere. With Airfoil you can take audio from any... Read more
WhatRoute 1.13.0 - Geographically trace...
WhatRoute is designed to find the names of all the routers an IP packet passes through on its way from your Mac to a destination host. It also measures the round-trip time from your Mac to the... Read more
Chromium 37.0.2062.122 - Fast and stable...
Chromium is an open-source browser project that aims to build a safer, faster, and more stable way for all Internet users to experience the web. FreeSMUG-Free OpenSource Mac User Group build is... Read more
Attachment Tamer 3.1.14b9 - Take control...
Attachment Tamer gives you control over attachment handling in Apple Mail. It fixes the most annoying Apple Mail flaws, ensures compatibility with other email software, and allows you to set up how... Read more
Duplicate Annihilator 5.0 - Find and del...
Duplicate Annihilator takes on the time-consuming task of comparing the images in your iPhoto library using effective algorithms to make sure that no duplicate escapes. Duplicate Annihilator detects... Read more
jAlbum Pro 12.2 - Organize your digital...
jAlbum Pro has all the features you love in jAlbum, but comes with a commercial license. With jAlbum, you can create gorgeous custom photo galleries for the Web without writing a line of code!... Read more
jAlbum 12.2 - Create custom photo galler...
With jAlbum, you can create gorgeous custom photo galleries for the Web without writing a line of code! Beginner-friendly, with pro results Simply drag and drop photos into groups, choose a design... Read more
Quicken 2015 2.0.4 - Complete personal f...
Quicken 2015 helps you manage all your personal finances in one place, so you can see where you're spending and where you can save. Quicken automatically categorizes your financial transactions,... Read more
iMazing 1.0 - Complete iOS device manage...
iMazing (formerly DiskAid) is the ultimate iOS device manager with capabilities far beyond what iTunes offers. With iMazing and your iOS device (iPhone, iPad, or iPod), you can: Copy music to and... Read more

Latest Forum Discussions

See All

View Source – HTML, JavaScript and CSS...
View Source – HTML, JavaScript and CSS 1.0 Device: iOS Universal Category: Utilities Price: $.99, Version: 1.0 (iTunes) Description: View Source is an app plus an iOS 8 Safari extension that makes it easy to do one key web developer... | Read more »
Avenged Sevenfold’s Hail To The King: De...
Avenged Sevenfold’s Hail To The King: Deathbat is Coming to iOS on October 16th Posted by Jessica Fisher on September 19th, 2014 [ permalink ] Just in time for Halloween, on October 16 Avenged Sevenfold will be launching | Read more »
Talisman Has Gone Universal – Can Now be...
Talisman Has Gone Universal – Can Now be Played on the iPhone Posted by Jessica Fisher on September 19th, 2014 [ permalink ] | Read more »
Tap Army Review
Tap Army Review By Jennifer Allen on September 19th, 2014 Our Rating: :: SHOOT EM ALLUniversal App - Designed for iPhone and iPad Mindless but fun, Tap Army is a lane-based shooter that should help you relieve some stress.   | Read more »
Monsters! Volcanoes! Loot! Epic Island f...
Monsters! Volcanoes! Loot! | Read more »
Plunder Pirates: Tips, Tricks, Strategie...
Ahoy There, Seadogs: Interested in knowing our thoughts on all this plundering and pirating? Check out our Plunder Pirates Review! Have you just downloaded the rather enjoyable pirate-em-up Plunder Pirates and are in need of some assistance? Never... | Read more »
Goat Simulator Review
Goat Simulator Review By Lee Hamlet on September 19th, 2014 Our Rating: :: THE GRUFFEST OF BILLY GOATSUniversal App - Designed for iPhone and iPad Unleash chaos as a grumpy goat in this humorous but short-lived casual game.   | Read more »
A New and Improved Wunderlist is Here fo...
A New and Improved Wunderlist is Here for iOS 8 Posted by Jessica Fisher on September 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Evernote Update for iOS 8 Adds Web Clipp...
Evernote Update for iOS 8 Adds Web Clipping, Quick Notes, and More Posted by Ellis Spice on September 19th, 2014 [ permalink ] | Read more »
Apple Names Ultimate Productivity Bundl...
Apple Names Ultimate Productivity Bundle by Readdle as the Essential Bundle on the App Store Posted by Jessica Fisher on September 19th, 2014 [ permalink | Read more »

Price Scanner via MacPrices.net

iFixIt Tears Down iPhone 6; Awards Respectabl...
iFixit notes that even the smaller 4.7″ iPhone 6 is a giant among iPhones; so big that Apple couldn’t fit it into the familiar iPhone form factor. In a welcome reversal of a recent trend to more or... Read more
Phone 6 Guide – Tips Book For Both iPhone 6...
iOS Guides has announced its latest eBook: iPhone 6 Guide. Brought to you by the expert team at iOS Guides, and written by best-selling technology author Tom Rudderham, iPhone 6 Guide is packed with... Read more
How to Upgrade iPhone iPad to iOS 8 without D...
PhoneClean, a iPhone cleaner utility offered by iMobie Inc., reveals a solution for upgrading iPhone and iPad to iOS 8 without deleting photos, apps, the new U2 album or anything. Thanks to more than... Read more
Inpaint 6 – Photo Retouching Tool Gets Faster...
TeoreX has announced Inpaint 6, a simple retouching tool for end users that helps remove scratches, watermarks, and timestamps as well as more complex objects like strangers, unwanted elements and... Read more
Worldwide PC Monitor Market Sees Growth in To...
Worldwide PC monitor shipments totaled 32.5 million units in the second quarter of 2014 (2Q14), a year-over-year decline of -2.9%, according to the International Data Corporation (IDC) Worldwide... Read more
Updated Price Trackers
We’ve updated our Mac Price Trackers with the latest information on prices, bundles, and availability on systems from Apple’s authorized internet/catalog resellers: - 15″ MacBook Pros - 13″ MacBook... Read more
Mac Pros available for up to $260 off MSRP
Adorama has Mac Pros on sale for up to $260 off MSRP. Shipping is free, and Adorama charges sales tax in NY & NJ only: - 4-core Mac Pro: $2839.99, $160 off MSRP - 6-core Mac Pro: $3739.99, $260... Read more
13-inch 2.6GHz/256GB Retina MacBook Pros avai...
B&H Photo has the 13″ 2.6GHz/256GB Retina MacBook Pro on sale for $1379 including free shipping plus NY sales tax only. Their price is $120 off MSRP. Read more
Previous-generation 15-inch 2.0GHz Retina Mac...
B&H Photo has leftover previous-generation 15″ 2.0GHz Retina MacBook Pros now available for $1599 including free shipping plus NY sales tax only. Their price is $400 off original MSRP. B&H... Read more
21″ 2.7GHz iMac available for $1179, save $12...
Adorama has 21″ 2.7GHz Hawell iMacs on sale for $1179.99 including free shipping. Their price is $120 off MSRP. NY and NJ sales tax only. Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** At the Apple Store, you connect business professionals and entrepreneurs with the tools they need in order to put Apple solutions to work in their Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** The Apple Store is a retail environment like no other - uniquely focused on delivering amazing customer experiences. As an Expert, you introduce people Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** As businesses discover the power of Apple computers and mobile devices, it's your job - as a Solutions Engineer - to show them how to introduce these Read more
Position Opening at *Apple* - Apple (United...
…Summary** As a Specialist, you help create the energy and excitement around Apple products, providing the right solutions and getting products into customers' hands. You Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.