Converting Natural language logical condition into a Java code - java

How do I go about translating a Natural language logical condition into its Java code counterpart?
Say I have this condition
(Color Equals Blue) AND (Name Contains Smith)
What can be done to translate this to a Java level code, which might look like
(Color.equals("Blue") && (Name.contains("Smith")))
I could not come up with any definitive approach to achieve the desired outcome, so here I am asking this question.
Also, please let me know that reason before down-voting.

I would try a dsl that parses the syntax you specified (Color Equals Blue) AND (Name Contains Smith) into java code. Make sure you understand the grammar for this syntax very well though before you start translating it into your parser grammar. A language specification link would help a lot. In the past I used ANTLR and it was really easy to generate JAVA code once i had the syntax tree from the output string.

Related

interpreting conditions written in natural language into Java code

The problem:
I want users to be able to write conditions in a simple syntax in a text editor, as in:
A?outcome1:(B?outcome2:outcome3)
A and B are boolean conditions. So the sentence above means: if A is true, then outcome1, else if B is true, then outcome 2, else outcome3.
In Java, I implement an interpreter of this syntax so that A, B, outcome1, outcome2,outcome3 get translated in values that are pre-stored somewhere (A and B will be functions returning a boolean, outcomes will be objects), and the condition is evaluated and a result is returned.
My question is, am I reinventing the wheel here? Are there Java packages or libraries that already provide neat implementations of "[constrained] natural language interpreted to Java code" kind of functions?
Thx!
I ended up writing a class in Java that reads a human-written rule and interprets it. Find it here:
https://github.com/seinecle/Umigon/blob/master/src/java/RuleInterpreter/Interpreter.java

Why should I learn "switch case" when "if else" already exists [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Advantage of switch over if-else statement
Why Switch/Case and not If/Else If?
I am currently learning "switch case" in school and am wondering what's the point of learning it when "if else" already exists. "if else" is basically another way of doing "switch case".
Please correct me if i am wrong.
It kinda nostalgic to heard it. Both of them actually 'looked' the same. But is a little bit different when the codes executed.
Firstly, 'switch-case' is about comparing value-only. But 'if-else' could process a boolean expression (which would support much more complex clauses)
If you use general 'if-else' when you have found what you are actually searching for, the process will still run until it has finished processing the last if (but actually it could use jump-technique to have similar mechanism like 'switch-case'.)
It won't happen if you use 'switch-case' because once the value you're searching for has been found, it will break and won't continue to the next case. Also, 'switch-case' is faster-to-process than if else because it only compares defined values (not expression). And 'switch-case' also has a good formatting structure (it's simple, compact, readable and clean).
The more tools you have the better. Flat out the best statement of why you should know both... however a more detailed example -
A switch statement works on a single type of variable of the construct:
variable == value
So for example in C if you were trying to compare something to a few different strings in order to make a decision, you can't do that with a switch. In this case you need to know about the if/else constructs.
However if you have a large number of sequential checks:
var == 1 or
var == 2 or
var == 3 etc
The compiler may take your switch statement and convert it to a jump table, which would end up being faster than a large number of comparisons that an if/else list would be.
You should learn the switch construct because it is a useful tool provided by the C language.
It is not the same as if-else blocks.
In the comments section of your question, there are links to existing StackOverflow answers explaining what the differences are.
Each construct has its strengths and weaknesses, and over time you will learn when it is appropriate to choose one over the other.
You should learn both. While it is technically possible to implement any if / else sequence with a switch and vice versa, it would be extremely bad practice to do this ... in most cases.
So you need to learn the two constructs, understand their strengths and weaknesses, and learn to use your judgement as to when it is appropriate to use each one.
And the mere fact that C and C++ and Java (and C# and Pascal and many other languages) all support switch statements should tell you something about its usefulness ...
Difference between switch-case and if-else constructs:
Switch-case switches on values only, it does not evaluates boolean expressions.
Switch-case offers execution of next cases below it automatically if you don't use break after your case block. This feature is sometimes useful for writing complex code, like "Telephone Dial Plan"
Switch-case are more elegant compared to if-else when the number of comparisons are huge, like in displaying "Menu", etc.

Is this Java in "The Art of Multiprocessor Programming" or fancy pseudocode?

I've started reading "The Art of Multiprocessor Programming". Seems like a great book. It claims to have examples written in Java, and it really seems this way in the beginning, to the level that they can be copied and run as-is. However, quite quickly I start to see features which I had no idea were in Java. I guess they're not and the book simply uses fancy Java-like pseudocode, but it still doesn't hurt to verify.
I'm talking about things like:
Using the existential quantifier in a while condition, e.g.
while(\exists k != me) (level[k] >= i && victim[i] == me)
(replace \exists with the actual mathematical sign; recall that Haskell has similar things).
Using tuples and lexicographical ordering built-in to the syntax, e.g.
(label[k], k) << (label[i], i)
Which compares the left component and if needed, the right component.
As far as I know this is pseudocode and not Java, but I'm hardly familiar with this language.
It's not Java. I didn't check in detail, but e.g. 02~Chapter_02.zip/ch02/Mutex/src/mutex/Bakery.java from the book's website seems to be the program the first code fragment originate from expressed in "real" Java.

BigDecimal notation eclipse plugin or nice external tool

I need to make a lot of operations using BigDecimal, and I found having to express
Double a = b - c * d; //natural way
as
BigDecimal a = b.subtract(c.multiply(d))//BigDecimal way
is not only ugly, but a source of mistakes and communication problems between me and business analysts. They were perfectly able to read code with Doubles, but now they can't.
Of course a perfect solution will be java support for operator overloading, but since this not going to happen, I'm looking for an eclipse plugin or even an external tool that make an automatic conversion from "natural way" to "bigdecimal way".
I'm not trying to preprocess source code or dynamic translation or any complex thing, I just want something I can input text and get text, and keep the "natural way" as a comment in source code.
P.S.: I've found this incredible smart hack but I don't want to start doing bytecode manipulation. Maybe I can use that to create a Natural2BigDecimal translator, but I don't want to reinvent the wheel if someone has already done such a tool.
I don't want to switch to Scala/Groovy/JavaScript and I also can't, company rules forbid anything but java in server side code.
"I'm not trying to preprocess source code ... I just want something I can input [bigDecimal arithmetic expression] text".
Half of solving a problem is recognizing the problem for what it is. You exactly want something to preprocess your BigDecimal expressions to produce legal Java.
You have only two basic choices:
A stand-alone "domain specific language" and DSL compiler that accepts "standard" expressions and converts them directly to Java code. (This is one kind of preprocessor). This leaves you with the problem of keeping all the expression fragments around, and somehow knowing where to put them in the Java code.
A tool that reads the Java source text, finds such expressions, and converts them to BigDecimal in the text. I'd suggest something that let you code the expressions outside the actual code and inserted the translation.
Perhaps (stolen from another answer):
// BigDecimal a = b - c * d;
BigDecimal a = b.subtract( c.multiply( d ) );
with the meaning "compile the big decimal expression in the comment into its java equivalent, and replace the following statement with that translation.
To implement the second idea, you need a program transformation system, which can apply source-to-source rewriting rules to transforms (generate as a special case of transform) the code. This is just a preprocessor that is organized to be customizable to your needs.
Our DMS Software Reengineering Toolkit with its Java Front End could do this. You need a full Java parser to do that transformation part; you'll want name and type resolution so that you can parse/check the proposed expression for sanity.
While I agree that the as-is Java notation is ugly, and your proposal would make it prettier, my personal opinion is this isn't worth the effort. You end up with a dependency on a complex tool (yes, DMS is complex: manipulating code isn't easy) for a rather marginal gain.
If you and your team wrote thousands of these formulas, or the writers of such formulas were Java-naive it might make sense. In that case,
I'd go further, and simply insist you write the standard expression format where you need it. You could customize the Java Front End to detect when the operand types were of decimal type, and do the rewriting for you. Then you simply run this preprocessor before every Java compilation step.
I agree, it's very cumbersome! I use proper documentation (comments before each equation) as the best "solution" to this.
// a = b - c * d;
BigDecimal a = b.subtract( c.multiply( d ) )
You might go the route of an expression evaluator. There is a decent (albeit paid) one at http://www.singularsys.com/jep. Antlr has a rudimentary grammar that also does expression evaluation (tho I am not sure how it would perform) at http://www.antlr.org/wiki/display/ANTLR3/Expression+evaluator.
Neither would give you the compile-time safety you would have with true operators. You could also write the various algorithm-based classes in something like Scala, which does support operator overloading out of the box and would interoperate seamlessly with your other Java classes.

Simple java recursive descent parsing library with placeholders

For an application I want to parse a String with arithmetic expressions and variables. Just imagine this string:
((A + B) * C) / (D - (E * F))
So I have placeholders here and no actual integer/double values. I am searching for a library which allows me to get the first placeholder, put (via a database query for example) a value into the placeholder and proceed with the next placeholder.
So what I essentially want to do is to allow users to write a string in their domain language without knowing the actual values of the variables. So the application would provide numeric values depending on some "contextual logic" and would output the result of the calculation.
I googled and did not find any suitable library. I found ANTLR, but I think it would be very "heavyweight" for my usecase. Any suggestions?
You are right that ANTLR is a bit of an overkill. However parsing arithmetic expressions in infix notation isn't that hard, see:
Operator-precedence parser
Shunting-yard algorithm
Algorithms for Parsing Arithmetic Expressions
Also you should consider using some scripting languages like Groovy or JRuby. Also JDK 6 onwards provides built-in JavaScript support. See my answer here: Creating meta language with Java.
If all you want to do is simple expressions, and you know the grammar for those expressions in advance, you don't even need a library; you can code this trivially in pure Java.
See this answer for a detailed version of how:
Is there an alternative for flex/bison that is usable on 8-bit embedded systems?
If the users are defining thier own expression language, if it is always in the form of a few monadic or binary operators, and they can specify the precedence, you can bend the above answer by parameterizing the parser with a list of operators at several levels of precedence.
If the language can be more sophisticated, you might want to investigate metacompilers.

Categories

Resources