|
John on 03/29/10 - 14:17:35
Hi everyone!
I would like to learn an algorithm to convert from infix to postfix notation with parentheses(or brackets). Expression like: 1 + (a + (2 - b) / c) * d because I've only found some which really work but don't accept them. All this because I would like to evaluate the postfix result. Once, I found an M/K productions code which evalutes directly the infix one but it seems poor to me :P Thanks pals!
Yellow Monkey on 03/30/10 - 00:55:34
heyy.... this mite help:
http://en.wikipedia.org/wiki/Shunting_yard_algorithm
Todd on 03/30/10 - 12:57:36
Hi John,
You'll need to use "Recursive Descent." This algorithm is simple and easy to understand. First, you'll need a "stack" or simply an array for storing all the terms. To get these terms onto the stack, you'll also need to parse the values in the expression. For this, it'd be best to write a Lexical Analyzer. In a lexical analyzer, your expression would appear as a series of tokens converted from below while still retaining their values: 1 + (a + (2 - b) / c) * d NUMBER[1] PLUS[+] LPAR[(] IDENT[a] PLUS[+] LPAR[(] NUMBER[2] MINUS[-] IDENT[b] RPAR[)] DIVIDE[/] IDENT[c] RPAR[)] TIMES[*] IDENT[d] Once it is converted into this form, you begin recursive descent. Your expression analyzer will appear in this way: EXPE - examines an expression EXPA - performs + or - EXPB - performs *, /, or % (modulo) EXPC - examines token to see if number, identifier, or left parenthesis Recursive descent would work like this: Expression -> EXPE -> EXPA -> EXPB -> EXPC Here's an example of this in action: http://math.hws.edu/javanotes/c9/s5.html It also includes a Java applet to show you how the process works.
John on 03/31/10 - 16:36:22
Reply to this message
Wooow... It's just what I need. All this stuff is because the teacher ask us to write a compiler for a math expression (I decided to coded it in our dear QB) and the steps (according to him) are:
1. Infix to Postfix conversion 2. Lexical analyzer (convert to tokens) 3. Intermediate code generator The postfix exp. ab+c* must be translated to temporary vars. like: t1 = a + b t2 = t1 * c 4. Code generator (translate to assembler) like mov ax, a add ax, b mov t1, ax ... 5. Write the corresponding ASM hex code to a .COM file to be executable And I have almost all. I stopped because of the trouble with the infix to postfix conversion. One more question. Is all this process the correct one? Because I'd read I need something called "Sintax analyzer" and also a "Semantic Analyzer". I'm reading the "Red Dragon Book" to know a li'l bit more but it seems hard to understand to me. Is there any "Compilers for Dummies" out there? hahaha ok... just a question! Thanx pals! :'( |
|