tags:

views:

90

answers:

2

In reference to the accepted solution in: SO:expression_evaluator

Can anyone provide a version that works with negation as well? things like

((!(0 or !1) and !((0 or 1 or 1) and !1))

need to work as well.

I got it working so that negating the 0's or 1's is fine but I can't get it to work with the negation of whole groups(!'s at beginning of parenthesis)

I tried negating tmp after returning from eval in the *expr == '(' block.. if ! had been seen before calling it, but that didn't work.

+6  A: 

The code in that answer is a bit ad-hoc. Parsing is a well-understood field, there's no need for invention. One of the other answers there recommends looking into recursive descent parsing. I second that recommendation.

Ned Batchelder
+1 - there's nothing more to say, except that one should build something like an AST which can then easily be computed.
Lucero
A: 

The algorithm described here can deal with unary operators (operators having one operand), as well as functions.

I once used it as the basis for a complete C expression evaluator with support for symbolic variables for a command-line console on an embedded system. I did not use the accompanying example code, but rather wrote it from scratch to suit my purposes.

Clifford