Exmex is an extendable mathematical expression parser and evaluator. Ease of use, flexibility, and efficient evaluations are its main design goals.
Exmex can parse mathematical expressions possibly containing variables and operators. On the one hand, it comes with a list of default operators
for floating point values. For differentiable default operators, Exmex can compute partial derivatives. On the other hand, users can define their
own operators and work with different data types such as float, integer, bool, or other types that implement Clone
, FromStr
, and Debug
.
The following snippet shows how to evaluate a string.
# use Error;
#
For floats, we have a list of predifined operators containing
^
, *
, /
, +
, -
, sin
, cos
, tan
, exp
, log
, and log2
. Further, the constants π
and Euler's number can be used via π
/PI
and E
, respectively. The full list is
defined in FloatOpsFactory
. Library users can also create their
own operators and constants as shown below in the section about extendability.
Variables
To define variables we can use strings that are not in the list of operators as shown in the following expression.
Additionally, variables should consist only of letters, greek letters, numbers, and underscores. More precisely, they
need to fit the regular expression r"[a-zA-Zα-ωΑ-Ω_]+[a-zA-Zα-ωΑ-Ω_0-9]*"
, if they are not between curly brackets.
Variables' values are passed as slices to eval
.
# use Error;
#
The n
-th number in the slice corresponds to the n
-th variable. Thereby, the
alphabetical order of the variables is relevant. More precisely, the order is defined by the way how Rust sorts strings.
In the example above we have y=3.7
, z=2.5
, and α=1
. Note that α
is the Greek letter Alpha.
If variables are between curly brackets, they can have arbitrary names, e.g.,
{456/549*(}
, {x}
, and also {👍+👎}
are valid variable names as shown in the following.
# use Error;
#
The value returned by parse
is an instance of the struct FlatEx
that implements the Express
trait. Moreover, FlatEx
and
Express
are the only items made accessible by the wildcard import from
prelude
.
Partial Derivatives
For default operators, expressions can be transformed into their partial derivatives
again represented by expressions. To this end, there exists the method partial
.
# use Error;
#
Owned Expression
You cannot return all expression types from a function without a lifetime parameter.
For instance, expressions that are instances of FlatEx
keep &str
s instead of
String
s of variable or operator names to make faster parsing possible.
# use Error;
#
If you are willing to pay the price of roughly doubled parsing times, you can
obtain an expression that is an instance of OwnedFlatEx
and owns
its strings. Evaluation times should be comparable. However, a lifetime parameter is
not needed anymore as shown in the following.
# use Error;
#
Extendability
How to use custom operators as well as custom data types of the operands even with non-numeric literals is described in the following sub-sections.
Custom Operators and Constants
Operators are instances of the struct
Operator
. Constants are defined in terms of constant operators. More precisely,
operators can be
- binary such as
*
, - unary such as
sin
, - binary as well as unary such as
-
, or - constant such as
PI
.
An operator's representation is defined in the field
repr
. A token of the string-to-be-parsed is identified as operator if it matches the operator's
representation exactly. For instance, PI
will be parsed as the constant π while PI5
will be parsed as a variable with name PI5
.
When an operator's representation is used in a string-to-be-parsed, the following applies:
- Binary operators are positioned between their operands, e.g.,
4 ^ 5
. - Unary operators are positioned in front of their operands, e.g.,
-1
orsin(4)
. Note thatsin4
is parsed as variable name, butsin 4
is equivalent tosin(4)
. - Constant operators are handled as if they were numbers and are replaced by their numeric values during parsing.
They can be used as in
sin(PI)
or4 + E
. Note that the calling notation of constant operators such asPI()
is invalid.
Binary, unary, and constant operators can be created with the functions make_bin
, make_unary
,
and make_constant
, respectively.
Operators need to be created by factories to make serialization via serde
possible as
shown in the following.
# use Error;
#
To extend an existing list of operators, the macro ops_factory
is not
sufficient. In this case one has to create a factory struct and implement the
MakeOperators
trait with a little boilerplate code.
# use Error;
#
Custom Data Types of Numbers
You can use any type that implements Clone
,
FromStr
, and Debug
. In case the representation of your data type in the
string does not match the number regex r"^(\.?[0-9]+(\.[0-9]+)?)"
, you have to pass a
suitable regex and use the function
from_pattern
instead of parse
or
from_str
. Here is an example for bool
.
# use Error;
#
You can also pre-compile the regex and use Express::from_regex
.
Two examples of exmex with non-trivial data types are:
- Numbers can be operators and operators can operate on operators, see, e.g., also a blog post on ninety.de.
- The value type implemented as part of the feature
value
allows expressions containing integers, floats, and bools. Therewith, Pythonesque expressions of the form"x if a > b else y"
are possible.
Priorities and Parentheses
In Exmex-land, unary operators always have higher priority than binary operators, e.g.,
-2^2=4
instead of -2^2=-4
. Moreover, we are not too strict regarding parentheses.
For instance
# use Error;
#
If you want to be on the safe side, we suggest using parentheses.
Display
Instances of FlatEx
and OwnedFlatEx
can be displayed as string. Note that this
unparse
d string does not necessarily coincide with the original
string, since, e.g., curly brackets are added, expressions are compiled, and constants are
replaced by their numeric values during parsing.
# use Error;
#
Features
Exmex comes with two features that can be activated in the Cargo.toml
via
[dependencies]
exmex = { ..., features = ["serde", "value"] }
serde
enables serialization and deserialization and value
a more general value type.
Serialization and Deserialization
To use serde
you can activate the feature serde
.
The implementation un-parses and re-parses the whole expression.
Deserialize
and
Serialize
are implemented for
both, FlatEx
and OwnedFlatEx
.
A more General Value Type
To use different data types within an expression, one can activate the feature value
. The additional
flexibility comes with higher parsing (factor 1.1-1.4) and evaluation run times (factor 2-3).