#include <iostream>
#include <string>
#include <map>
// AbstractExpression
class AbstractExpression {
public:
virtual int interpret(std::map<std::string, int>& variables) = 0;
virtual ~AbstractExpression() {}
};
// TerminalExpression
class TerminalExpression : public AbstractExpression {
std::string variable;
public:
TerminalExpression(const std::string& var) : variable(var) {}
int interpret(std::map<std::string, int>& variables) override {
return variables[variable];
}
};
// NonTerminalExpression
class AddExpression : public AbstractExpression {
AbstractExpression* left;
AbstractExpression* right;
public:
AddExpression(AbstractExpression* l, AbstractExpression* r) : left(l), right(r) {}
int interpret(std::map<std::string, int>& variables) override {
return left->interpret(variables) + right->interpret(variables);
}
~AddExpression() {
delete left;
delete right;
}
};
int main() {
// Context
std::map<std::string, int> context;
context["x"] = 5;
context["y"] = 10;
// Client
AbstractExpression* expression = new AddExpression(new TerminalExpression("x"), new TerminalExpression("y"));
std::cout << "Result: " << expression->interpret(context) << std::endl;
delete expression;
return 0;
}