My goal is to write a function that will take a logical expression (eg: A OR NOT(B AND C)) and convert that into disjunctive normal form. (A OR NOT B OR NOT C)
I have written a grammar that will generate logical expressions
S => !S
S => (S)
S => S op S
S => W
op => AND | OR
W => A | B | C | ... | Z
This is my algorithm
- Given an expression S
- recursively parse the expression using the grammar above and build the corresponding parse tree
- Convert the expression to DNF by recursively "simplifying" any NOT operators on the tree.
- Recursively go through final parse tree and output the DNF logical expression.
With a parse tree I can simplify NOT operators by checking the current node's parent, and pushing it down the tree or re-arranging the tree (in the case of NOT NOT). Then it is trivial to flatten the tree.
This works on paper, but now I'm stuck with the actual parser. How can I convert these rules into a parser class? I don't want to use external libraries and want to write the parser from scratch.