By Herre Kuijpers
http://www.codeproject.com/Articles/241830/a-Tiny-Expression-Evaluator
- Code was adapted to run on .netcf 3.5 profile.
- UI code was separated from parser
- Contexts are recursively scoped. This allows to declare derived contexts.
- Syntax update to have logical
and
,or
operations. - Bit functions: rshift, lshift, bitand, bitor, bitxor
The functionality of the tool is based on the implementation as used in Excel. Currently the expression evaluator supports the following features:
It can parse mathematical expressions, including support for the most commonly used functions,e.g.:
4*(24/2-5)+14
cos(Pi/4)*sin(Pi/6)^2
1-1/E^(0.5^2)
min(5;2;9;10;42;35)
The following functions are supported:
About Abs Acos And Asin Atan Atan2 Avg Ceiling Clear Cos Cosh Exp Fact Floor Format Help Hex If Floor Len Ln Log Lower Max Min Min Not Or Pow Rand Round Sign Sin Sinh Sqr Sqrt StDev Trunc Upper Val Var
String functions:
Left(string; len), Right(string; len), Mid(string; offset; len)
Bit related functions:
rshift, lshift, bitand, bitor, bitxor
Basic string functions:
"Hello " & "world"
"Pi = " & Pi
Len("hello world")
Boolean operators:
true != false
5 > 6 ? "hello" : "world"
If(5 > 6;"hello";"world")
Function and variable declaration
x := 42
f(x) := x^2
f(x) := sin(x) / cos(x) // declare new dynamic functions using built-in functions
Pi
E
Recursion and scope
fac(n) := (n = 0) ? 1 : fac(n-1)*n
// fac calls itself with different parameters
f(x) = x*Y
// x is in function scope, Y is global scope
Currently 5 datatypes are supported: double, hexidecimal, int, string and boolean. Note that integers (and hexadecimals also) are always converted to doubles when used in a calculation by default. Use the int() function to convert to integer explicitly.
The tool uses the following precedence rules for its operators:
- ( ), f(x) Grouping, functions
- ! ~ - + (most) unary operations
- ^ Power to (Excel rule: that is a^b^c -> (a^b)^c
-
- / % Multiplication, division, modulo
-
-
- Addition and subtraction
-
- & concatenation of strings
- < <= > >= Comparisons: less-than, ...
- = != <> Comparisons: equal and not equal
&&
and
- Logical AND||
or
- Logical OR- ?: Conditional expression
- := Assignment
Checkout Grammar for details.