/
divide_multiply_modulo.go
105 lines (80 loc) · 1.82 KB
/
divide_multiply_modulo.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
102
103
104
105
package arithmetic
import (
"errors"
)
// divide (/) operator.
type divide struct{}
func (o divide) String() string {
return "/"
}
func (o divide) precedence() uint8 {
return precedenceDivideMultiply
}
func (o divide) solve(st *stack) (interface{}, error) {
// Retreive right and left terms from stack.
// The term can be of type "float" or "variable".
right, err := st.popFloat()
if err != nil {
return nil, rightError(o)
}
left, err := st.popFloat()
if err != nil {
return nil, leftError(o, right)
}
// Secure division by 0.
if right == 0 {
return nil, errors.New("division by 0")
}
return left / right, nil
}
// multiply (*) operator.
type multiply struct{}
func (o multiply) String() string {
return "*"
}
func (o multiply) precedence() uint8 {
return precedenceDivideMultiply
}
func (o multiply) solve(st *stack) (interface{}, error) {
// Retreive right and left terms from stack.
// The term can be of type "float" or "variable".
right, err := st.popFloat()
if err != nil {
return nil, rightError(o)
}
left, err := st.popFloat()
if err != nil {
return nil, leftError(o, right)
}
return left * right, nil
}
// modulo (%) operator
type modulo struct{}
func (o modulo) String() string {
return "%"
}
func (o modulo) precedence() uint8 {
return precedenceDivideMultiply
}
func (o modulo) solve(st *stack) (interface{}, error) {
// Retreive right and left terms from stack.
// The term can be of type "float" or "variable".
// The decimal part of the inputs must be 0.
right, err := st.popFloat()
if err != nil {
return nil, rightError(o)
}
r, ok := floatToInt(right)
if !ok {
return nil, rightError(o)
}
left, err := st.popFloat()
if err != nil {
return nil, leftError(o, right)
}
l, ok := floatToInt(left)
if !ok {
return nil, leftError(o, right)
}
return float64(l % r), nil
}