KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I'm still on my quest for a really simple language and I know now that there are none. So I'm writing one myself using ANTLR3. I found a really great example in this answer : Exp.g: grammar Exp; eval returns [double value] : exp=additionExp {$value = $exp.value;} ; additionExp returns [double value] : m1=multiplyExp {$value = $m1.value;} ( '+' m2=multiplyExp {$value += $m2.value;} | '-' m2=multiplyExp {$value -= $m2.value;} )* ; multiplyExp returns [double value] : a1=atomExp {$value = $a1.value;} ( '*' a2=atomExp {$value *= $a2.value;} | '/' a2=atomExp {$value /= $a2.value;} )* ; atomExp returns [double value] : n=Number {$value = Double.parseDouble($n.text);} | '(' exp=additionExp ')' {$value = $exp.value;} ; Number : ('0'..'9')+ ('.' ('0'..'9')+)? ; WS : (' ' | '\t' | '\r'| '\n') {$channel=HIDDEN;} ; Java Code: public Double evaluate(String string, Map<String, Double> input) throws RecognitionException { ANTLRStringStream in = new ANTLRStringStream(string); ExpLexer lexer = new ExpLexer(in); CommonTokenStream tokens = new CommonTokenStream(lexer); return new ExpParser(tokens).eval(); } Using this ANTLR grammer I can evaluate expressions like (12+14)/2 and get 13 as a result. Now the only thing missing for my use-case is a way to inject simple double variables into this, so that I can evaluate the following by supplying {"A": 12.0, "B":14.0} as the input map: (A+B)/2 </
Tags (comma-separated)
Save Edits
Cancel