Expr

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<String,Double>();
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 1st argument should evaluate to true or false (the numerical comparison operators can be used); if it's true, cond evaluates to the 2nd argument, otherwise to the 3rd.
? returns a random number between 0 and 1.
Variables can be upper- or lowercase; they override functions of the same name. "PI" and "E" are predefined to be the corresponding mathematical constants.

Changes:

The source code is available here.


Back To Stuff Page