-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfixPrinterVisitor.cpp
More file actions
110 lines (93 loc) · 2.09 KB
/
InfixPrinterVisitor.cpp
File metadata and controls
110 lines (93 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include "InfixPrinterVisitor.h"
#include "Math.h"
#include <string>
template <typename T>
void InfixPrinterVisitor::VisitBinary(T* n, const char& a)
{
if (n != nullptr) {
auto printer = std::make_shared <InfixPrinterVisitor>();
if (n->left != nullptr && n->right != nullptr) {
n->left->Accept(printer.get());
output = printer.get()->get();
output += " ";
output += a;
output += " ";
n->right->Accept(printer.get());
output += printer.get()->get();
return;
}
if (n->left != nullptr) {
n->left->Accept(printer.get());
output = printer.get()->get();
return;
}
if (n->right != nullptr) {
n->right->Accept(printer.get());
output = printer.get()->get();
return;
}
output = "";
return;
}
}
std::string InfixPrinterVisitor::wrapper(const std::string& word)
{
return "("+word+")";
}
InfixPrinterVisitor::InfixPrinterVisitor() : output("")
{
}
void InfixPrinterVisitor::VisitConst(Const* n)
{
if (n != nullptr) {
output = std::to_string(n->val);
}
}
void InfixPrinterVisitor::VisitX(X* n)
{
if (n != nullptr) output = "x";
}
void InfixPrinterVisitor::VisitAdd(Add* n)
{
VisitBinary<Add>(n, '+');
}
void InfixPrinterVisitor::VisitMinus(Minus* n)
{
VisitBinary<Minus>(n, '-');
}
void InfixPrinterVisitor::VisitTimes(Times* n)
{
VisitBinary<Times>(n, '*');
}
void InfixPrinterVisitor::VisitDivide(Divide* n)
{
VisitBinary<Divide>(n, '/');
}
void InfixPrinterVisitor::VisitExp(Exp* n)
{
if (n != nullptr) {
auto printer = std::make_shared <InfixPrinterVisitor>();
if (n->base != nullptr && n->power != nullptr) {
n->base->Accept(printer.get());
output = printer.get()->get();
output += "^";
n->power->Accept(printer.get());
output += printer.get()->get();
return;
}
if (n->base != nullptr) {
n->base->Accept(printer.get());
output = printer.get()->get();
return;
}
output = "";
return;
}
}
std::string InfixPrinterVisitor::get()
{
return wrapper(output);
}
InfixPrinterVisitor::~InfixPrinterVisitor()
{
}