Custom Functions

JEP allows you to add custom functions by calling jep.FunTab.AddFunction(String name, IPostfixMathCommand function). Custom functions are no different from built-in functions, so you can use the source code of the built-in functions as a template. The class methods are accessed both during parsing and evaluation. During parsing, the parser needs to know how many parameters are allowed. During evaluation, the Run(Stack<Object>) method is called to perform the actual calculation.

The following is an example of how a custom function can be added.

Assume you want to add a function "Half" to divide a number by two (for demonstration purposes).

  1. Create a class that extends PostfixMathCommand (in the SingularSys.Jep.Functions namespace). In this example we will name it "Half"
  2. In the constructor set the number of arguments to be taken. In our case this is one. Do this by writing numberOfParameters = 1;
    If you want to allow any number of parameters, initialize the numberOfParameters value to -1. It is highly recommended to study the Sum.cs code as an example of a function that accepts any number of parameters.
  3. Implement the run(Stack<Object> inStack) method. The parameters are passed in a Stack object. This same stack is used as the output for the function. So we first need to pop the parameter off the stack, calculate the result, and finally pop the result back on the stack.
    public override void Run(Stack<object> inStack)
    {
       // check the stack
       CheckStack(inStack);
     	
       // get the parameter from the stack
       Object param = inStack.Pop();
     	
       // check whether the argument is of the right type
       if (param is JepDouble) {
          // calculate the result
          double r = ((JepDouble)param).DoubleValue / 2;
          // push the result on the inStack
          inStack.Push(new JepDouble(r));
       } else {
          throw new EvaluationException("Invalid parameter type");
       }
    }
  4. In your main program or applet that is using the parser, add the new function. Do this by writing
    jep.FunTab.AddFunction("half", new Half());
  5. If numberOfParameters == -1 you may wish to overwrite the bool CheckNumberOfParameters(int n) to catch an illegal number of arguments at parse time.

Source files