|
It's time to add in multiplication and division. Multiplication and DivisionHere's a shot at it with those nasty left-recusion form of productions:
Of course, we can't use them in this form. But it may help to see them, anyway. There's a new thing going on here, now -- binding priority. We want the multiplication and division to take place before any addition or subtraction, in the absence of parenthesis. (Or, we will if we ever get around to actually calculating values.) So, initially, we start out considering every algebriac expression as an expression. An expression can then be some combination of plus and minus terms, not times and divide -- not yet, anyway. Only in a term do we find multiplication and division. By layering the productions this way we can achieve the priority we want. Look at a possible example and see if you can see how it matches up with the above productions::
Since we already know those productions are going to be a problem, I won't bother breaking it down, step by step. Hopefully, you can see that it probably works ... except for the left-recusion problem. So, let's just hop over to a right-recursive form we can use to code a useful predictive recursive descent parser. (What a mouthful, eh?)
Take a close look at the above productions. The basic idea is that an expression is groups of things added and subtracted from each other and that each of those things are groups of still other things multiplied or divided together. By thinking this way, the multiplications and divisions are automatically given priority over additions and subtractions. You may also notice the similarity of the new productions. I've again renamed them, though. I hope you won't mind. In any case, there's a pattern here you can recognize. Coding?Well, I think you can probably guess about how we might code up something to fit the above productions:
I've prepared a newly modified source file to illustrate: Let's finish this up, adding in powers.
Last updated: Friday, January 13, 2006 23:59
|