This is a simple scan push apply (the twist is the braces).
- Look for a number:
- If you see a number push onto stack
- if you see a '(' push it onto stack and goto 1
- Otherwise an error.
- Look for an op:
- If you see an op push it onto stack
- Otherwise an error
- Look for a number:
- If you see a number push onto stack
- If you see a '(' push onto stack and goto 1
- Otherwise an error
- pop last three items from the stack (should be number op number)
- do the operation and push the result onto the stack.
- Now the complex bit:
- Peek to see if the next character is a ')' if it is goto "PopCode" below.
- If no more input goto 7.
- If only one item on the stack you have your result.
PopCode
- Pop last two values from the stack. Should be '( Number'
- If it is not then an error
- Throw away the '('
- If the top of the stack is an op push value goto 4 (above)
- Otherwise push the value onto the stack goto 5 (above)
When finished there should be one number on the stack.
Example:
1+3
Rule 1: push 1 stack = '1'
Rule 2: push + stack = '1 +'
Rule 3: push 3 stack = '1 + 3'
Rule 4: pop and do: stack = '4'
Rule 5: Nothing stack = '4'
Rule 6: goto 7 stack = '4'
Rule 7: stack = '4'
(1 + (12 * 2)
Rule 1: push ( goto 1 stack = '('
Rule 1: push 1 stack = '( 1'
Rule 2: push + stack = '( 1 +'
Rule 3: push ( goto 1 stack = '( 1 + ('
Rule 1: push 12 stack = '( 1 + ( 12'
Rule 2: push * stack = '( 1 + ( 12 *'
Rule 3: push 2 stack = '( 1 + ( 12 * 2'
Rule 4: Pop and do: stack = '( 1 + ( 24'
Rule 5: Do 'PopCode' stack = '( 1 + ( 24'
Pop 1: Pop 2 stack = '( 1 +'
Pop 2: Holding 24 stack = '( 1 +'
Pop 3: push 24 goto 4 stack = '( 1 + 24'
Rule 4: Pop and do stack = '( 25'
Rule 5: Nothing stack = '( 25'
Rule 6: goto 7 stacj = '( 25'
Rule 7: More than 1 item error
Re-Doing with correct formula
(1 + (12 * 2))
Rule 1: push ( goto 1 stack = '('
Rule 1: push 1 stack = '( 1'
Rule 2: push + stack = '( 1 +'
Rule 3: push ( goto 1 stack = '( 1 + ('
Rule 1: push 12 stack = '( 1 + ( 12'
Rule 2: push * stack = '( 1 + ( 12 *'
Rule 3: push 2 stack = '( 1 + ( 12 * 2'
Rule 4: Pop and do: stack = '( 1 + ( 24'
Rule 5: Do 'PopCode' stack = '( 1 + ( 24'
Pop 1: Pop 2 stack = '( 1 +'
Pop 2: Holding 24 stack = '( 1 +'
Pop 3: push 24 goto 4 stack = '( 1 + 24'
Rule 4: Pop and do stack = '( 25'
Rule 5: Do 'PopCode' stack = '( 25'
Pop 1: Pop 2 stack = ''
Pop 2: holding 25 stack = ''
Pop 3: Nothing. stack = ''
Pop 4: push 25 goto 5 stack = '25'
Rule 5: Nothing stack = '25'
Rule 6: goto 7 stack = '25'
Rule 7: Result = 25