Last edited: 28 Feb 2018

Desktop viewHomePage

Expr is a simple recursive descent expression evaluator. It was originally written in C by Guy Laden. It can be used on the command line:

java Expr "(x+1) * (y%4) + cond(x<>y, 10, 0)" x 2 y 10

prints 16.0

or within a program:

Map<String,Double> vars = new HashMap<>();
vars.put("x"new Double(2));
vars.put("y"new Double(10.0));
double result = Expr.eval("(x+1) * (y%4) + cond(x<>y, 10, 0)", vars);

Available functions are: + - * / ^ ? % sqrt() sin() cos() tan() asin() acos() atan() exp() ln() cond(,,) min(,) max(,)

cond works somewhat like an if/then/else, or rather like the "a ? b : c" construct in C or Java. The first argument should evaluate to true or false (the numerical comparison operators can be used); if it's true, cond evaluates to the second argument, otherwise to the third.

? returns a random number between 0 and 1.

Variables can be uppercase or lowercase; they override functions of the same name.

"PI" and "E" are predefined to be the corresponding mathematical constants.


The source code is available here