Skip to content

Evaluation

WhiteBlackGoose edited this page Feb 15, 2023 · 1 revision

Let us consider approaches to compute an expression.

Evaluation

All constant types, such as booleans and numbers, have their own types in the AM's type hierarchy. When evaluating, you will also get a result in one of these types.

To evaluate an Entity you need to call its method EvalNumerical to evaluate it into a Complex and EvalBoolean to evaluate it into a Boolean. Example:

Entity expr = "2 + 3";
Console.WriteLine(expr.EvalNumerical()); // 5
Entity expr2 = "true implies false";
Console.WriteLine(expr2.EvalBoolean()); // false

If the given expression cannot be represented as the requested type, for example, the result is a set, or the expression contains unresolved variables, exception CannotEvalException. Example:

Entity expr = "2 + 3 + a";
Console.WriteLine(expr.EvalNumerical()); // throws, as "a" is unknown
Entity expr2 = "{ 1, 3 }";
Console.WriteLine(expr2.EvalNumerical()); // throws, as the result is not a number
Entity expr3 = "true implies b";
Console.WriteLine(expr3.EvalBoolean()); // throws, as "b" is unknown

Properties EvaluableBoolean and EvaluableNumerical show whether the expression can be expressed as a single boolean or a single numerical value. For example, do not call EvalNumerical() if EvaluableNumerical is false.

Once evaluated, the result might be converted into a primitive via explicit cast. Example:

Entity expr = "3 / 5";
double evalDouble = (double)expr.EvalNumerical();
Console.WriteLine(evalDouble);
Complex evalComplex = (Complex)expr.EvalNumerical();
Console.WriteLine(evalComplex);
int evalInt = (int)expr.EvalNumerical();
Console.WriteLine(evalInt);

Output:

0.6
(0.6, 0)
0

If a number cannot be converted into the given primitive, a NumberCastException will be thrown. Example:

Entity expr = "3 / 5 + i";
double evalDouble = (double)expr.EvalNumerical(); // throws NumberCastException

However, if you do not need the final number, but instead, the "most" evaluated expression, you may address property Evaled. Example:

Entity expr = "2 + 3";
Console.WriteLine(expr.Evaled);
Entity expr2 = "2 + 3 + a";
Console.WriteLine(expr2.Evaled);

Output:

5
5 + a

It is recommended to consider Evaled as a free-to-access property. It is a so-called lazy property. Nonetheless, it should be pointed out that the first address of this property executes computations and puts into cache.

Extensions: string.EvalNumerical(), string.EvalBoolean().

Clone this wiki locally