1
+ package Interpreter
2
+
3
+ import "strings"
4
+
5
+ type Expression interface {
6
+ Interpret (variables map [string ]Expression ) int
7
+ }
8
+
9
+ type Integer struct {
10
+ integer int
11
+ }
12
+
13
+ func (n * Integer ) Interpret (variables map [string ]Expression ) int {
14
+ return n .integer
15
+ }
16
+
17
+ type Plus struct {
18
+ leftOperand Expression
19
+ rightOperand Expression
20
+ }
21
+
22
+ func (p * Plus ) Interpret (variables map [string ]Expression ) int {
23
+ return p .leftOperand .Interpret (variables ) + p .rightOperand .Interpret (variables )
24
+ }
25
+
26
+ func (e * Evaluator ) Interpret (context map [string ]Expression ) int {
27
+ return e .syntaxTree .Interpret (context )
28
+ }
29
+
30
+ type Variable struct {
31
+ name string
32
+ }
33
+
34
+ type Node struct {
35
+ value interface {}
36
+ next * Node
37
+ }
38
+
39
+ type Stack struct {
40
+ top * Node
41
+ size int
42
+ }
43
+
44
+ func (s * Stack ) Push (value interface {}) {
45
+ s .top = & Node {
46
+ value : value ,
47
+ next : s .top ,
48
+ }
49
+ s .size ++
50
+ }
51
+
52
+ func (v * Variable ) Interpret (variables map [string ]Expression ) int {
53
+ value ,found := variables [v .name ]
54
+ if ! found {
55
+ return 0
56
+ }
57
+ return value .Interpret (variables )
58
+ }
59
+
60
+ func (s * Stack ) Pop () interface {} {
61
+ if s .size == 0 {
62
+ return nil
63
+ }
64
+ value := s .top .value
65
+ s .top = s .top .next
66
+ s .size --
67
+ return value
68
+ }
69
+
70
+ type Evaluator struct {
71
+ syntaxTree Expression
72
+ }
73
+
74
+
75
+
76
+ func NewEvaluator (expression string ) * Evaluator {
77
+ expressionStack := new (Stack )
78
+ for _ ,token := range strings .Split (expression ," " ){
79
+ switch token {
80
+ case "+" :
81
+ right := expressionStack .Pop ().(Expression )
82
+ left := expressionStack .Pop ().(Expression )
83
+ subExpression := & Plus {left ,right }
84
+ expressionStack .Push (subExpression )
85
+ default :
86
+ expressionStack .Push (& Variable {token })
87
+ }
88
+ }
89
+ syntaxTree := expressionStack .Pop ().(Expression )
90
+ return & Evaluator {syntaxTree :syntaxTree }
91
+ }
0 commit comments