JEXP is a small API for parsing and evaluating expressions given as text strings. The API provides classes which you can directly use in your own code in order to parse expressions. You don't have to implement any interfaces or override methods. But the API is also a tiny framework which lets you define your own symbols and functions tailored to your specific application environment.
The JEXP API consists of three packages.
{@link com.bc.jex}
:
The main package of the JEX API. It defines the abstract
{@link Term com.bc.jex.Term}
class which plays a central role in the API.
The other interfaces and classes in this package just support Term
.
The Term
class is used to represent the parsed expressions in memory
and also to evaluate them.
{@link com.bc.jex.impl}
:
Provides some generally useful implementations of the interfaces defined in
the main package. The classes in this package define so to say the ready-to-use API.
Also contained is the UI component {@link com.bc.jex.impl.ExpressionPane}
which
you can use as a base for your application's user interface.
{@link com.bc.jex.ui}
:
(A) Parsing a simple expression without any variables.
Parser parser = new ParserImpl(); Term term = null; try { term = parser.parse("2.3 * sin(2 * 0.56) / (1 + 0.56)"); } catch (ParseException e) { fail("error: " + e.getMessage()); } double result = term.evalD(null);
(B) Parsing a simple expression with variables.
Variable x = SymbolFactory.createVariable("x", 0.56); Variable y = SymbolFactory.createVariable("y", 2.3); DefaultNamespace namespace = new DefaultNamespace(); namespace.registerSymbol(x); namespace.registerSymbol(y); Parser parser = new ParserImpl(namespace); Term term = null; try { term = parser.parse("y * sin(2 * x) / (1 + x)"); } catch (ParseException e) { fail("error: " + e.getMessage()); } double result = term.evalD(null);
(C) Parsing a simple expression with a new function.
DefaultNamespace namespace = new DefaultNamespace(); registerFunction(new AbstractFunction.D("rand", 2) { public double evalD(EvalEnv env, Term[] args) { double x1 = args[0].evalD(env); double x2 = args[1].evalD(env); return x1 + Math.radom() * (x2 - x1); } }); Parser parser = new ParserImpl(namespace); Term term = null; try { term = parser.parse("rand(-1, +1)")); } catch (ParseException e) { fail("error: " + e.getMessage()); } double result = term.evalD(null);
(D) Parsing a simple expression in a user-defined environment.
@todo add example here...