Decent Simplification Algorithm for C++

Programming, for all ages and all languages.
Post Reply
kfreezen
Member
Member
Posts: 46
Joined: Tue Jul 21, 2009 11:36 am

Decent Simplification Algorithm for C++

Post 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
ru2aqare
Member
Member
Posts: 342
Joined: Fri Jul 11, 2008 5:15 am
Location: Hungary

Re: Decent Simplification Algorithm for C++

Post 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.
kfreezen
Member
Member
Posts: 46
Joined: Tue Jul 21, 2009 11:36 am

Re: Decent Simplification Algorithm for C++

Post by kfreezen »

Thanks, that should help me.
kfreezen
Member
Member
Posts: 46
Joined: Tue Jul 21, 2009 11:36 am

Re: Decent Simplification Algorithm for C++

Post by kfreezen »

Is there also a decent precedence determining algorithm?

I have a feeling there isn't :)
User avatar
NickJohnson
Member
Member
Posts: 1249
Joined: Tue Mar 24, 2009 8:11 pm
Location: Sunnyvale, California

Re: Decent Simplification Algorithm for C++

Post 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.
User avatar
Thomas
Member
Member
Posts: 281
Joined: Thu Jun 04, 2009 11:12 pm

Re: Decent Simplification Algorithm for C++

Post by Thomas »

kfreezen
Member
Member
Posts: 46
Joined: Tue Jul 21, 2009 11:36 am

Re: Decent Simplification Algorithm for C++

Post 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
Post Reply