Handling user-defined operators – binary operators
User-defined operators are similar to the C++ concept of operator overloading, where a default definition of an operator is altered to operate on a wide variety of objects. Typically, operators are unary or binary operators. Implementing binary operator overloading is easier with the existing infrastructure. Unary operators need some additional code to handle. First, binary operator overloading will be defined, and then unary operator overloading will be looked into.
Getting ready
The first part is to define a binary operator for overloading. The logical OR operator (|
) is a good example to start with. The |
operator in our TOY language can be used as follows:
def binary | (LHS RHS) if LHS then 1 else if RHS then 1 else 0;
As seen in the preceding code, if any of the values of the LHS or RHS are not equal to 0, then we return 1
. If both the LHS and RHS are null, then we return 0
.
How to do it...
Do the following steps:
- The first step, as...