Advanced Features

Manipulating expressions

It is possible to manipulate expressions by manipulating the corresponding expression tree created by Jep.Net. The Parse() method and LastRootNode property can be used to obtain the expression tree of an expression. This will be useful if you want to do more than just evaluate the expressions you parse. For example, you may want to determine the derivative of an expression. In order to be able to this, you need direct access to the expression tree.

The expression tree consists of nodes. Each of the nodes in the parse tree is an object of one of the following types:

Node methods

There are several methods and properties of Node and its sub-classes which can be used to interrogate the node.

All nodes
  • node.JjtGetNumChildren() returns the number of children of the node. For constants and variable nodes this is 0, for functions and operators this is the number of arguments.
  • node.JjtGetChild(i) returns the i-th child of the node.
Constant nodes
  • ((ASTConstant) node).Value returns the value of a constant node.
Variable nodes
  • ((ASTVarNode) node).Var returns the variable object associated with a variable node.
  • ((ASTVarNode) node).Var.Name returns the name of the variable.
  • ((ASTVarNode) node).Var.Value returns the value of the variable.
Function nodes
  • ((ASTFunNode) node).GetName() returns the name of the function.
  • ((ASTFunNode) node).GetPFMC() returns IPostfixMathCommand for the function.
Operator nodes
  • ((ASTOpNode) node).Op returns the operator.
  • ((ASTOpNode) node).GetPFMC() returns IPostfixMathCommand for the function.

Constructing expressions

The SingularSys.Jep.NodeFactory class contains various methods for creating different types of nodes to make an expression. For example the following produces an expression "5+cos(x)".

NodeFactory nf = jep.NodeFac;
// Build variables for cos() function
INode[] vars = new INode[1];  
vars[0] = nf.BuildVariableNode("x");
// Build operator node for "+" and add children (5, cos(x))
INode node = nf.BuildOperatorNode(
  jep.OpTab.GetAdd(),
  nf.BuildConstantNode(new JepDouble(5)),
  nf.BuildFunctionNode("cos", new Cosine(), vars)
);
top