Class PrefixedNotationExpressionEngine<R>

  • Type Parameters:
    R - the type the data the evaluation must result.

    public class PrefixedNotationExpressionEngine<R>
    extends Object
    This engine reads a prefixed notation expression in order to evaluate it.
    Each part of the expression is composed of an operator with one or several operands.
    Each operand must be wrapped into parentheses.
    An operand can be:
    • a value to evaluate (by the converter given as first parameter of from(Function, OperatorFunction[])) method. The value to convert is detected when it has no parenthesis
    • an operator with one or several operands
    Each operator must be defined by the caller and given to variable parameter of from(Function, OperatorFunction[]) method.
    So, by calling from(Function, OperatorFunction[]) method, the caller defines the behaviour of the operators of the expression to evaluate.
    An operator without operands means that the operator is part of the value to evaluate (by the converter).

    For example:

       PrefixedNotationExpressionEngine<Integer> engine = from(
         (aString) -> aString == null ? 0 : Integer.parseInt(aString), // the converter
         new OperatorFunction<Integer>("+", (a,b) -> (a == null ? 0 : a) + b), // ADD operator
         new OperatorFunction<Integer>("-", (a,b) -> (a == null ? 0 : a) - b) // SUBTRACT operator
       )
    
       engine.evaluate("+(+(3)(4))(+(-(5))(2))"); // gives 4
    
       // Decomposed treatment:
       // +(7)(+(-(5))(2))
       // +(7)(+(-5)(2))
       // +(7)(-3)
       // 4
    
       engine.evaluate("+(+(3)(4))(+(-5)(2))"); // gives also 4, here the minus character from '-5'
                                                // is taken into account as part of the value and not
                                                // as an operator
     

    Some errors can be thrown as IllegalArgumentException with message containing an error key. It is free to the caller to use these keys.
    The errors:

    • expression.operation.malformed 1 (1)
    • expression.operation.operator.none (1)(2)
    • expression.operation.operand.parentheses.missing.open +1)(2)
    • expression.operation.operand.parentheses.missing.close +(1)(2"
    Author:
    Yohann Chastagnier
    • Method Detail

      • evaluate

        public R evaluate​(String expression)
        Evaluates the given expression.
        Parameters:
        expression - the expression to evaluate.
        Returns:
        the typed result.
      • detectOperator

        public boolean detectOperator​(String expression)
        Indicates if the given expression is contains an operator, and so, a potential expression to evaluate.
        Parameters:
        expression - the expression to verify.
        Returns:
        true if the expression contains an operator, false otherwise.