История изменений
Исправление monk, (текущая версия) :
только трансформации.
Ну так я и на C++ могу написать
#include <iostream>
enum selector {Lit, Plus, Mult};
struct expr
{
Selector t;
expr *value1, *value2;
int value;
expr(int val) { t = Lit; value = val; }
expr(selector _t, expr *_v1, expr *_v2) { t = _t; value1 = _v1; value2 = _v2 };
string show()
{
case (t)
{
Lit: return "Lit(" + to_string(value) + ")";
Plus: return "Plus(" + value1.show() + "," +value2.show() + ")";
Mult: return "Mult(" + value1.show() + "," +value2.show() + ")";
}
}
~expr() { delete value1; delete value2; }
}
expr* plus(expr *a, expr* b) { new expr(Plus, a, b); }
expr* mult(expr *a, expr* b) { new expr(Mult, a, b); }
int eval(expr *a)
{
case (a->t)
{
Lit: return a->value;
Plus: return eval(a->value1) + eval(a->value2);
Mult: return eval(a->value1) * eval(a->value2);
}
}
int main()
{
expr *x = new expr(Mult, new expr Plus(1, 2), new expr Plus(3, 4));
cout << x.show() << end;
cout << eval(x) << endl;
}
Исправление monk, :
только трансформации.
Ну так я и на C++ могу написать
#include <iostream>
enum selector {Lit, Plus, Mult};
struct expr
{
Selector t;
expr *value1, *value2;
int value;
expr(int val) { t = Lit; value = val; }
expr(selector _t, expr *_v1, expr *_v2) { t = _t; value1 = _v1; value2 = _v2 };
string show()
{
case (t)
{
Lit: return "Lit (" + to_string(value) + ")";
Plus: return "Plus (" + value1.show() + "," +value2.show() + ")";
Mult: return "Mult(" + value1.show() + "," +value2.show() + ")";
}
}
~expr() { delete value1; delete value2; }
}
expr* plus(expr *a, expr* b) { new expr(Plus, a, b); }
expr* mult(expr *a, expr* b) { new expr(Mult, a, b); }
int eval(expr *a)
{
case (a->t)
{
Lit: return a->value;
Plus: return eval(a->value1) + eval(a->value2);
Mult: return eval(a->value1) * eval(a->value2);
}
}
int main()
{
expr *x = new expr(Mult, new expr Plus(1, 2), new expr Plus(3, 4));
cout << x.show() << end;
cout << eval(x) << endl;
}
Исходная версия monk, :
только трансформации.
Ну так я и на C++ могу написать
#include <iostream>
enum selector {Lit, Plus, Mult};
struct expr
{
Selector t;
expr *value1, *value2;
int value;
expr(int val) { t = Lit; value = val; }
expr(selector _t, expr *_v1, expr *_v2) { t = _t; value1 = _v1; value2 = _v2 };
string show()
{
case (t)
{
Lit: return "Lit (" + to_string(value) + ")";
Plus: return "Plus (" + value1.show() + "," +value2.show() + ")";
Mult: return "Mult(" + value1.show() + "," +value2.show() + ")";
}
~expr() { delete value1; delete value2; }
}
expr* plus(expr *a, expr* b) { new expr(Plus, a, b); }
expr* mult(expr *a, expr* b) { new expr(Mult, a, b); }
int eval(expr *a)
{
case (a->t)
{
Lit: return a->value;
Plus: return eval(a->value1) + eval(a->value2);
Mult: return eval(a->value1) * eval(a->value2);
}
}
int main()
{
expr *x = new expr(Mult, new expr Plus(1, 2), new expr Plus(3, 4));
cout << x.show() << end;
cout << eval(x) << endl;
}