in reply to a timid approach to parsing arithmetic expressions in perl

Short description of the algorithm:
  1. give each operator/operand a priority based on it's depth and on a base priority each has.
  2. take the biggest priority operand and the 2 operands adjacent to it
  3. evaluate the 3 elements extracted at step 2 and put in the array at the place where they were the result of the calculation and the results's priority is decreased by a depth_bonus because it's paranthesis have disappeared.
  4. repeat step 2 until the array has just one element(which is the result of the evaluation)

On the surface, it looks like this algorithm should work, however, it seems like you are doing more work than is necessary, and the algorithm reduces basically to an infix-to-postfix conversion combined to a postfix calculation but with a larger big o complexity.

Since you are able to parse and calculate postfix with a single pass through the data and a stack, and convert from infix to postfix with a single pass and stack, I am not certain what this buys you.

As far as your implementation, for educational purposes, go crazy. On my initial scan, I would have concerns with the element selection routine, but it appears that it should work. For performance, I would be concerned with the repeated sorts.

If this is not for educational reasons, then I would seriously consider looking at the algorithms listed above, a parse tree, and a postorder traversal of that tree, as those are probably able to be implemented with less code and less complexity.

--MidLifeXis

  • Comment on Re: a timid approach to parsing arithmetic expressions in perl