-
Notifications
You must be signed in to change notification settings - Fork 153
Custom Operators
Creating a custom OperatorSet
allows you to define custom operators and modify how existing operators are recognized.
Let's say we want to add a new binary operator called *+
. We can do that by creating a new Operator
instance:
let multipladd = Operator("muladd", arity: .Binary, associativity: .Left, tokens: ["*+"])
Next, we want this operator to be evaluated at the same precedence as multiplication, so we'll find that operator and use it as a point relative to which we can add our new operator:
let multiply = Operator(builtInOperator: .Multiply)
var operatorSet = OperatorSet()
operatorSet.addOperator(multipladd, relatedBy: .EqualTo, toOperator: multiply)
Now we can use this OperatorSet
when constructing an Expression
, and the underlying tokenizer will recognize the *+
operator.
Sometimes you may want to define new ways to recognize existing operators. For example, let's say we wanted to also recognize the >
(greater than) operator with the ≰
symbol ("neither less-than nor equal to").
To do so, all we need is an OperatorSet
and the Operator
we want to work with:
let lessThan = Operator(builtInOperator: .LogicalLessThan)
var operatorSet = OperatorSet()
operatorSet.addTokens(["≰"], forOperator: lessThan)
Now whenever we use this OperatorSet
during tokenization, we'll recognize the ≰
symbol as resolving to the "less than" operator.
It's also interesting to note that operator tokens may contain alphabetic characters and whitespace. This allows you to extend DDMathParser
to do quasi-natural language processing:
let lessThan = Operator(builtInOperator: .LogicalLessThan)
var operatorSet = OperatorSet()
operatorSet.addTokens(["less than", "is less than"], forOperator: lessThan)
Using this OperatorSet
, we can now recognize "1 is less than 2"
as being equivalent to "1 < 2"
.