I'm writing a program to parse and evaluate mathematical expressions

the parse tree is in the format:

struct node
{
    string token;
    node*[] children;
}

it is parsed such that for the input 1*(2+3)-4*(5+6), the tree ends up looking like
         -
   *           *
1      +     4     +
     2   3       5   6

When the time comes to evaluate this I thought a sensible way to do it would be this

real evaluate(node top)
{
    real output;
    string token = top.token;

    if (tokenIsAnOperator)
    {
        real[2] operands;

        foreach (i, child; parallel(top.children))
        {
            operands[i] = evaluate(*child);
        }

output = someFunctionWiththeRightOperator(operands[0], operands[1]);
    }
    else // it must be a number
    {
        output = parse!real();
    }

    return output;
}

Which works perfectly - about 20-30% of the time
I can literally paste 1*(2+3)-4*(5+6) into the input over and over, and I get
0
5
-39
no digits seen
Floating point conversion error for input "".

seemingly randomly (those two errors are apparently coming from somewhere in the std library)

When I put in less complicated expressions I get the right answer more of the time, but it can still come out wrong occasionally

And the weirdest part: when I remove "parallel" from the foreach loop, it always gives me the correct answer

anyone know what's going on here, and/or how to fix it?

Reply via email to