Class Evaluator<O>

  • Type Parameters:
    O - the type parameter
    All Implemented Interfaces:
    Serializable

    public abstract class Evaluator<O>
    extends Object
    implements Serializable

    An evaluator provides a switch-like interface for evaluating expressions. Custom evaluators can be created as follows:

     
    
     Evaluator<Double> eval = new Evaluator<Double>() {{
          $(BinaryOperatorExpression.class, CommonTypes.PLUS, e -> eval(e.left) + eval(e.right));
          $(ValueExpression.class, e -> Double.valueOf(e.toString()));
     }}
    
     
     
    The various $ methods allow easily adding if-like predicates and then-like functions. The eval(Expression) method can be used to make recursive evaluation calls.

    Author:
    David B. Bracewell
    See Also:
    Serialized Form
    • Constructor Detail

      • Evaluator

        protected Evaluator()
        Instantiates a new Evaluator.
    • Method Detail

      • $

        protected final <E extends Expression> void $​(@NonNull
                                                      @NonNull Class<E> expressionClass,
                                                      @NonNull
                                                      @NonNull Tag type,
                                                      @NonNull
                                                      @NonNull CheckedFunction<E,​? extends O> function)
        Adds a switch statement where the condition is that the expression is of type expressionClass and the expressions's token type is an instance of type. When the condition is met the expression is cast as the given expression class and the given function is applied.
        Type Parameters:
        E - the type of expression
        Parameters:
        expressionClass - the expression class
        type - the token type
        function - the function to apply when the condition is met.
      • $

        protected final <E extends Expression> void $​(Class<E> expressionClass,
                                                      CheckedFunction<E,​? extends O> function)
        Adds a switch statement where the condition is that the expression is of type expressionClass. When the condition is met the expression is cast as the given expression class and the given function is applied.
        Type Parameters:
        E - the type of expression
        Parameters:
        expressionClass - the expression class
        function - the function to apply when the condition is met.
      • eval

        public final O eval​(Expression expression)
                     throws ParseException
        Evaluates the given expression
        Parameters:
        expression - the expression to evaluate
        Returns:
        the result of evaluation
        Throws:
        ParseException - Something went wrong during evaluation