Page 1 of 1

Decent Simplification Algorithm for C++

Posted: Sun Jan 10, 2010 6:06 pm
by kfreezen
I'm working on an assembler for my OS's emulator bytecode. Does anyone know of an algorithm to simplify?
for example:
input:

Code: Select all

5 * 2 + 4 - ( 2 + 5 )
output:

Code: Select all

7

Re: Decent Simplification Algorithm for C++

Posted: Sun Jan 10, 2010 6:12 pm
by ru2aqare
kfreezen wrote:I'm working on an assembler for my OS's emulator bytecode. Does anyone know of an algorithm to simplify?
for example:
input:

Code: Select all

5 * 2 + 4 - ( 2 + 5 )
output:

Code: Select all

7
Look up 'constant folding' in books about writing compilers. If you parse the expression as a tree, then it is pretty trivial to perform this.

Re: Decent Simplification Algorithm for C++

Posted: Sun Jan 10, 2010 6:15 pm
by kfreezen
Thanks, that should help me.

Re: Decent Simplification Algorithm for C++

Posted: Sun Jan 10, 2010 8:35 pm
by kfreezen
Is there also a decent precedence determining algorithm?

I have a feeling there isn't :)

Re: Decent Simplification Algorithm for C++

Posted: Sun Jan 10, 2010 8:48 pm
by NickJohnson
I think what you're really after is the shunting yard algorithm, which converts/evaluates infix expressions and accounts for order of operations. Wikipedia has a good article on it. It also doesn't require making a tree, assuming that the expression can be evaluated at compile time.

Re: Decent Simplification Algorithm for C++

Posted: Mon Jan 11, 2010 1:51 am
by Thomas

Re: Decent Simplification Algorithm for C++

Posted: Mon Jan 11, 2010 7:08 pm
by kfreezen
Yeah, I saw that one by the time someone had already replied to my thread and realized that that one would be the one I was lookin' for. Sorry I didn't search the forums first #-o