# Expr

Last edited: 28 Feb 2018

`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.

Changes:

- May 1997: ported to Oberon and small enhancements
- November 1997: ported to Java
- May 1999: now accepts an arbitrary number of variables
- May 1999: added cond and % functions, PI and E constants
- June 2001: added min, max, tan, asin, acos functions, and ? (random number)
- March 2002: enhanced min and max to accept an arbitrary number of arguments; added AND, OR and NOT operators: AND and OR accept an arbitrary number of arguments - a number whose absolute value is below 1.0e-6 is considered to be logically false, otherwise true

The source code is available here

CodeSnippets