One way to do it would be to write code that
seperates the sentence. What you want to do
is write a function that returns the next token. So
repeativly calling the function on the input stream
A*B+(C+A)*B gives
A , *, B, +, (, C, +, A, ), *, B
You would also need to store some data in the token
such as what value are the variables, what kind of
token it is etc. Another function that is used
is match. match takes token as one of the paremeters. If the current token
equals that token it reads another token into the current
token else it prints out an error.
Now to do this properly you could write
a symbol table but I think you can probably just
do double var_list[256]. So then the value of
C is var_list['C' - 'A'].
The hardest part of your program is going to be
the parser but once you get good at
recursive descent it's really mechanical.
There is one more thing that you need to do.
You need to write the grammer to the language.
I think this one will work
prog: <expr>
expr: {<factor> + <factor>} | {<factor> - <factor>} | <factor>
factor: {<base> * <base> } | {<base> / <base> } | <base>
base: <var> | ( <expr> )
var: 'A' | 'B' .. | 'Z'
you read this like this. prog is defined to be an expr.
An expr is series of factor+factor or a series
of factor - factor or just a factor.
A factor is a series of base * base or a series of base/base
or just a base.
A base is just a variable or an expression grouped by
parens. This is recursive; you must make sure
there's no left recursion in recursive descent.
A variable is just the uppercase letters.
To write the recursive descent parser for this grammer
all you need to do is to write functions prog, expr,
factor, base, var.
For example here is how I would start out roughly
Code:
/* prog: <expr> */
double prog()
{
return expr();
}
/* expr: {<factor> + <factor>} | {<factor> - <factor>} | <factor>
*/
double expr()
{
double eval;
Token next_token;
int quit = 0;
eval = factor();
while(!quit)
{
/* retrives the current token from the lexer */
next_token = lookup();
switch(next_token.type)
{
case PLUS:
match(next_token.type);
eval += factor();
break;
case MINUS:
match(next_token.type);
eval -= factor();
break;
default:
quit = 1;
}
}
return eval;
}
factor is defined similarly
/* base: <var> | ( <expr> ) */
double base()
{
Token next_token;
double eval;
next_token = lookup()
if (next_token.type == LEFT_PARAN)
{
match(LEFT_PARAN);
eval = expr();
match(RIGHT_PARAN);
}
else if (next_token.type == VAR)
{
eval = next_token.value;
}
else
{
error("Expected a '(' or variable");
}
return eval;
}
You will want to change some this stuft but you
should have no problem doing this.