Microsyntax:
N -> \p{Nd}+
Macrosyntax:
P -> "-"? T ([+-] T)*
T -> N ("x" ("^" N)?)? | "x" ("^" N)?
// Evaluator.jj
//
// This spec generates a (threadsafe) utility parser class called
// Evaluator.java that contains a static method that takes in a
// string representing a polynomial p and a value x and returns p(x).
PARSER_BEGIN(Evaluator)
import java.io.*;
public class Evaluator {
/**
* Returns the value of the polynomial at the given value.
*/
public static double eval(String p, double x) throws ParseException {
return new Evaluator(new StringReader(p)).parsePolynomial(x);
}
/**
* Writes the value of args[0] on the value args[1] to standard output.
*/
public static void main(String[] args) throws ParseException {
System.out.println(eval(args[0], Double.parseDouble(args[1])));
}
}
PARSER_END(Evaluator)
// P -> "-"? T ( ("+"|"-") T )*
// T -> INTLIT? "x" ("^" INTLIT)? | INTLIT
SKIP: {" " | "\t" | "\n" | "\r"}
TOKEN: {"+" | "-" | "^" | "x" | <INTLIT: (["0"-"9"])+>}
double parsePolynomial(double x):
{double result = 0.0; int multiplier = 1; double termValue;}
{
["-" {multiplier = -1;}] result=parseTerm(x) {result *= multiplier;}
(
("+" {multiplier = 1;} | "-" {multiplier = -1;})
termValue=parseTerm(x)
{result += multiplier * termValue;}
)*
<EOF>
{return result;}
}
double parseTerm(double x):
{int coefficient = 1; int exponent = 1; Token c, e;}
{
LOOKAHEAD(2)
[c=<INTLIT> {coefficient = Integer.parseInt(c.image);}]
"x"
["^" e=<INTLIT> {exponent = Integer.parseInt(e.image);}]
{return coefficient * Math.pow(x, exponent);}
|
c=<INTLIT> {return Integer.parseInt(c.image);}
}