Parse non standard form to standard form in java

前端 未结 1 1863
滥情空心
滥情空心 2021-01-22 23:14

I want to write a Java parser that converts a non-standard form (NSF) Boolean function into a standard form (SF).

Example of a NSF:

A * B + D (A + B) C          


        
相关标签:
1条回答
  • 2021-01-22 23:53

    You have to do 4 steps to achieve your purpose:

    1) parse the expression using "standard" (unrelated to your terminology) parsing techniques and produce what amounts to a boolean expression tree representing the (parsed) expression.

    2) apply boolean algebra rules to the expression tree, to convert it from the representation you don't want, to the one you do. Your "standard form" appears to be conjunctive normal form (CNF), so you need distributive law algebra rules to "multiply out" products over sums (e.g., a*(b+c)), to "get rid of parentheses"

    3) You then need to apply some simplification rules (e.g., subsumption, cancellation) to get rid of excess terms, e.g., a*b + a*b+c ==> a*b [a*b*c subsumed], and a*b*a'+b*c ==> b*c [a*..a' cancels out]. This is just more algebra rules.

    4) PrettyPrint the resulting algebra term in a human readable format.

    You can write all this by A) ad hoc hand coded recursive descent parsing and ad hoc rule application and prettyprinting, or B) you can get a parser generator (ANTLR is nice) to do the parsing, and do the rule manipulation by ad hoc methods, and prettyprint using some help like string templates, or C) you could get a tool that does parsing, builds trees, will apply algebra rules you define, and has prettyprinting built in.

    Our DMS Software Reengineering Toolkit can do case C nicely. You can see an example of applying standard algebra rules that is a direct analog to your problem.

    One of the issues that is really hard to get right is handling associativity and commutativity in the algebra, e.g., knowing that A*B*A' is "false" is a consequence of the algebra rule X*X'=> false, but you can't just check for the pattern in the algebra rule directly. You have to apply the algebra rules accounting for commutivity. Same argument for associativity. One of the things that DMS does nicely is handle that for you, if you declare the appropriate operators to have those properties. You can see this in the example.

    Alas, not coded in Java.

    0 讨论(0)
提交回复
热议问题