This is a piece from the complete program.
What it does is parses mathematical expressions of the form (+(*3,x),5)
to 3*x + 5
and store it in an object of class Formula
. Add
,Mul
, Div
, Exp
, X
, Integer
and Symbols
are derived from Formula
class. Recursive strategy has been used to parse formulae with greater complexity.
Please request for any other piece of code if required.
Does this code have redundancy? How can it be improved?
void parse(Formula*& f, string s, int &k)
{
if(s[k] == '(')
{
k++;
if(s[k] == '+')
{
f = new Add();
}
else if(s[k] == '/')
{
f = new Div();
}
else if(s[k] == '-')
{
f = new Sub();
}
else if(s[k] == '*')
{
f = new Mul();
}
else
{
f = new Exp();
}
k++;
parse(f->left, s, k);
k = k + 2;
parse(f->right, s, k);
k++;
}
else
{
if(s[k] == 'x')
{
X* a = new X();
f = a;
}
else if(48 <= s[k] <= 57)
{
Integer* a = new Integer();
a->i = s[k] - 48;
f = a;
}
}
}