Skip to content

Adding New Operators

Dave DeLong edited this page Oct 20, 2011 · 2 revisions

There are two steps to adding new operators:

  1. Defining the operator info
  2. Defining the underlying evaluation function

Defining the operator info

You'll need to add two lines to the +_buildOperators method of _DDOperatorInfo.m. Part of this step is to figure out when the operator is evaluated with respect to other operators (ie, its precedence). Precedence is simple: the higher the precedence, the earlier it gets evaluated. Thus, a "logical or" will always be evaluated after everything else, because it has the lowest precedence.

After figuring out the precedence, you'll need to construct a new _DDOperatorInfo object and add it to the operators array in that method. The simplest way to do this is to copy an existing definition and then modify it accordingly.

The method to create a new _DDOperatorInfo is this:

+ (id)infoForOperatorFunction:(NSString *)function 
                        token:(NSString *)token 
                        arity:(DDOperatorArity)arity 
                   precedence:(NSInteger)precedence 
                associativity:(DDOperatorAssociativity)associativity;

The parameters are:

  • the function to which the operator evaluates
  • the string by which to recognize the operator
  • the arity of the operator (if it's unary versus binary)
  • the precedence
  • the associativity of the operator (left versus right)

The combination of the token and the function are enough to uniquely identify an operator. For example, two operators use the ! token, but have different functions (factorial and l_not). Similarly, two operators may have the same function (divide), but will have different tokens (/ and ÷).

The second line to add is to simply increment the precedence variable so that the next operator has the correct relative precedence.

Ambiguous Operators

If the token happens to be the same as another operator, it's possible that you'll need to alter the -[DDMathStringTokenizer _processUnknownOperatorToken:withError:] method in order to differentiate between them.

Defining the function

Finally, the evaluator needs to know what to do when it's supposed to evaluate your operator. You previously chose a function name that will be used in evaluation. Now we define it. This is done by adding a new class method to the _DDFunctionUtilities class. The name of the method should be +fooFunction, where foo is the name of your operator's function. Then simply define a method body that [[returns the appropriate DDMathFunction block|Adding New Functions]].