Expression

From FlexRule Wiki
Jump to: navigation, search

Expression

An expression is a combination of explicit values, variables, operators, and functions that are evaluated according to the particular rules and then produces new values.

For evaluating an expression ExpressionEval should be used. If variable is required an instance of VariableContainer must be passed.

Expression is the building block of writing rules and conditions. There are some other models (i.e. Decision Table) that support more expressions format as well as normal expressions.

Evaluating Expression in Code

Here is an example of how you can evaluate an expression containing some variables:

  1. var variables = new VariableContainer();
  2. variables.RegisterVariable("x");
  3. variables.RegisterVariable("y");
  4. variables.RegisterVariable("result");
  5.  
  6. variables["x"] = 5;
  7. variables["y"] = "a test string";
  8.  
  9. var res = ExpressionEval.Default.Compute(variables, "result = (x lt 3) ? x : (x+y.Length)");
  10. // res, variables["result"] are both equal to 18

Values

Value is an expression that can not be evaluated any further. The evaluation engine can process the following values types:

Type Suffix Sample
String "test string value"
Integer i 23i
Decimal m 67m
Double d 0d
Long l 20l
Boolean true false
null null
DateTime # date_time_string # #23-04-2009 3:9 pm#
DateTime with Format specifier # date_time_string | formatter_string # #23-04-2009 | dd-MM-yyyy#
TimeSpan #{ }# #{3:45}#

For datetime Format specifier please visit Format specifier

Variables

Variables can be defined with a name,

  • Short variable name: alphabetic numeric _ $
    • x
    • abc3
    • point_x
    • $value
  • Long variable name: { variable name }
    • {applicant name}
    • {risk factor}
    • {person's father name}

Variables in different logic are defined as parameters. You can define them in the following types of rules and logic:

  • Procedural rules
  • Flow logic
  • Validation rules
  • Workflow logic
  • Inference rules
  • Decision

Operators

All the execution routing conditions in the rules and logic are based on a expression evaluation. An expression can

Mathematical operators

Name Sign Sample
Addition + 23+4
Subtraction - 2.1-5.76
Division / 34/8
Multiplication * 3*6.9
Modulus  % 7%2
Power ** 2**3

Assignment operator

Name Sign Sample
Assignment = x=y.GetCordinate().X/2
approved=true
applicant.GetDoc('system',true).IsValid=system.Validity

Assignment operator format:

expression = expression 

In this case left-hand-side expression must finish with Property or Field of an object

variable = expression

Boolean operators

Name Sign Sample
And &&
and
(age<18) && (i>10)
(age<18) and (i>10)
Or ||
or
(Age lt 15) || (Male==true)
(Age lt 15) or (Male==true)
Negate !
 !(Age lt 15)
Format:  (LEFT-BOOLEAN-EXPRESSION) [boolean operator] (RIGH-BOOEALN-EXPRESSION)

Please note you MUST use parentheses around both sides of a boolean operator to make sure you prioritize the evaluation on left and right side of boolean operator.

Comparing operators

Name Sign Sample
Equality ==
eq
Age==18
Inequality  !=
neq
Gender != Female
Less than <
lt
(Age < 15)
(Age lt 15)
Smaller than or equal <=
le
(Age <= 15)
(Age le 15)
Greater then >
gt
(Age > 15)
(Age gt 15)
Greater then or equal >=
ge
(Age >= 15)
(Age ge 15)

Case insensitive

Name Sign Sample Result
Equality ===
is
'test'==='TEST' true
Inequality  !==
isnt
'abce' !== 'Abcd' false

Priority operator

Sub-expression evaluation based on priority:

  • Begin (
  • End )
(1-risk)*applicantAge

Object members operators

Access to objects (variable) members:

  • Method (.)
  • Property (.)
  • Indexer, Array, list item access ([) and (])
applicant.Age*applicant.CalculateRiskFactor("A")

Condition operator

Inline condition operator
Name Sign Sample
Condition  ?
Alternatives  : 2.1-5.76

For example:

(3==4)?'this is cool':'what are you talking about?'
If-Then-Else

The alternative of inline condition operator is use if-then-else format:

if condition then result else other-result

For example the above example can be written like:

if 3==4 then 'this is cool' else 'what are you talking about?'

Also, they can be nested:

if Product Type == 'STANDARD LOAN'
then 20.00d
else if Product Type == 'SPECIAL LOAN'
then 25.00d
else null

Methods

When a variable is defined, then method of the variable can be called using . operator and parenthesis are required at the end of the method and input arguments are comma separated.

Example: Assume x and b are defied parameter then expression 'x.Calculate(2i ,b)' calls Calculate method of the x and passes integer 2 and variable b as input arguments.

Functions

Functions are very similar to methods but the difference is they do not belong to any specific variable. They are global in the whole expression evaluation context. For example let's consider the following expression:

in(age, array(3,4,56,60,3,10))

As you can see in and array are accepting arguments with parenthesis and they are comma separated, exactly like methods. But there is no . operator involved. Functions can be defied at application/rule level and they are a very concept to extend the functionality in expression evaluation level.

Please check API for built-in functions.

Decision Table Expressions

In Decision Table, there are some more expressions format that can be used to simplify the value based rules. In general when a value is entered in a data section of a decision table, it dynamically resolves its type based on the column type and template expression.

Type of Value Sample Expression description
Negate not: 2-3-4 Prefix with not:
String blah blah blah
Explicit String "blah blah blah" or 'blah...' String quotes (double or single)
Numbers 23 or 4i or 3.4d No prefix (all expression rules in above sections apply)
Expression  : applicant.GetLastAttendanceDate()  :
Range [23, 45]
(43, 50)
[39;456)
Square brackets [] for inclusion and Parentheses exclusion in value ranges and they are comma (,) or semicolon (;) split.
Multi-Values 12,3,4

34,3d,'string value', true, var2.Length
Multi values are ',' split. They can be combination of different values and variable references.

For example in the second example, we have have defined multiple values as 34 (integer number), 3.0 (decimal number), true (boolean value) and var2.Length (as Length property of a variable reference named var2)

Note: Multi values must explicitly specify their types on each element separated by comma.

Samples

Calculation:

(a+b)+(2 * c)-d

Comparison:

a < 10
(a+b) gt 23
a<=(c+d)

Assignment

a = b + c
str = 'hello FlexRule expressions'

Storing the result of comparison into 'r'

r = (b+c)<d


Method Call: i.e. obj is an object reference which is not null

a = obj.CalculateSum()+20-b

Access Property:

 b = obj.Name + '-' + obj.Family

Pipe

Pipe are types of function that you can chain them together and they pass previous result to the next one.

|pipeName (arg1, arg2, arg3...)

For example the result of people |count() is an integer that is the length of the people list. In this example count function, receives people as its input and its result as a number (integer).

  1. var list = new List<DecisionAgeTests.Person>()
  2. {
  3.     new DecisionAgeTests.Person("arash", 38, DecisionAgeTests.Gender.Male),
  4.     new DecisionAgeTests.Person("Parsa", 6, DecisionAgeTests.Gender.Male),
  5.     new DecisionAgeTests.Person("Pooya", 3, DecisionAgeTests.Gender.Male),
  6.     new DecisionAgeTests.Person("Shah", 3, DecisionAgeTests.Gender.Female)
  7. };
  8.  
  9. var vc = new VariableContainer();
  10. vc.RegisterVariable("people", list);
  11.  
  12. var res = ExpressionEval.Default.Compute(vc, "people |count ()");
  13.  
  14. Assert.AreEqual(list.Count, (int)res);

Learn more about list of pipes

XML

When you are working with XML-based data/information. You need to read and manipulate XML. For more details visit Xml API help