-
Notifications
You must be signed in to change notification settings - Fork 23
/
interpreter_caculator.go
101 lines (85 loc) · 1.62 KB
/
interpreter_caculator.go
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
package interpreter
import (
"strconv"
"strings"
)
//解释自定义的加减法运算
//输入:字符串
//输出:整数值
//将一个包含加减运算的字符串,正常解析出结果
//Element 每个元素的解释接口
type Element interface {
Interpret() int
}
//ValElement 值节点
type ValElement struct {
val int
}
//Interpret 值解析单元的返回值
func (n *ValElement) Interpret() int {
return n.val
}
//AddOperate Operation(+)
type AddOperate struct {
left, right Element
}
//Interpret AddOperate
func (n *AddOperate) Interpret() int {
return n.left.Interpret() + n.right.Interpret()
}
//MinOperate Operation(-)
type MinOperate struct {
left, right Element
}
//Interpret MinOperate
func (n *MinOperate) Interpret() int {
return n.left.Interpret() - n.right.Interpret()
}
//Parser machine
type Parser struct {
exp []string
index int
prev Element
}
//Parse content
func (p *Parser) Parse(exp string) {
p.exp = strings.Split(exp, " ")
for {
if p.index >= len(p.exp) {
return
}
switch p.exp[p.index] {
case "+":
p.prev = p.newAddOperte()
case "-":
p.prev = p.newMinOperte()
default:
p.prev = p.newValElement()
}
}
}
func (p *Parser) newAddOperte() Element {
p.index++
return &AddOperate{
left: p.prev,
right: p.newValElement(),
}
}
func (p *Parser) newMinOperte() Element {
p.index++
return &MinOperate{
left: p.prev,
right: p.newValElement(),
}
}
func (p *Parser) newValElement() Element {
v, _ := strconv.Atoi(p.exp[p.index])
p.index++
return &ValElement{
val: v,
}
}
//Result of parsing result
func (p *Parser) Result() Element {
return p.prev
}