Arithmetic interpreter

This is an arithmetic interpreter written in C++ that first parses the line, whether from file or console, and then evaluates the expression.

For the parsing, each element is classified as a certain type of atom, that can either be an operator or an operand.

Operators

Operators are divided in two main categories, unary and binary, and then there are a few others that inherit directly from the Operator class.

Binary operators

They are the most straightforward and simple operators from the bunch. Will later simply take two operands to their sides and evaluate them somehow. The ones supported in my interpreter are +, -, * and ^ (power).

Unary operators

These, similar to binary operators, will later take a single operand and evaluate it. The expected ones are – and +. But in this category also go the lambdas and the functions.

Lambdas are “Custom expressions”. Basically, a unary operator where instead of having a predefined behavior, the user can specify the expression for the evaluation of the operand. They are written as in the following example:

    \x -> x*3 + 1

An can be inserted mid expression as an operator, in such a way:

    4 – 2 * \x -> (x*3 + 1) 8+1

           (parenthesis can be omitted, but makes it more readable)

Lambdas can also be stored in variables, yielding functions as a result, for ease of use.

    let square = \value -> value*value

    square 4        (yields 16)

Operands

Literals

Literals are any kind of numerical value introduced in the line to parse. In my interpreters case though, it only supports integer values.

Variables

Similarly of how we can assign lambdas to variables and make them functions, it is possible to simply assign values to them. This is done in such a manner:

    let x = 2

        or

    let y = x*3

The evaluation of the expression is done using stacks for the operands an operators separately and evaluating the operators taking operands from their stack when the set rules say to do so. Specifically, I have used the Shunting-Yard algorithm, which you can check for yourself for a more in detail explanation.