-
Notifications
You must be signed in to change notification settings - Fork 0
/
operators.go
100 lines (86 loc) · 1.47 KB
/
operators.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
package operators
import "math"
type Operator struct {
Symbol string
Operation func(...float64) float64
Priority int
}
func Plus() Operator {
return Operator{
Symbol: "+",
Operation: func(nums ...float64) float64 {
if len(nums) == 1 {
return nums[0]
}
return nums[0] + nums[1]
},
Priority: 0,
}
}
func Minus() Operator {
return Operator{
Symbol: "-",
Operation: func(nums ...float64) float64 {
if len(nums) == 1 {
return 0 - nums[0]
}
return nums[0] - nums[1]
},
Priority: 1,
}
}
func Multiplication() Operator {
return Operator{
Symbol: "*",
Operation: func(nums ...float64) float64 {
return nums[0] * nums[1]
},
Priority: 2,
}
}
func Division() Operator {
return Operator{
Symbol: "/",
Operation: func(nums ...float64) float64 {
return nums[0] / nums[1]
},
Priority: 2,
}
}
func Parenthes() Operator {
return Operator{
Symbol: "(",
Operation: func(nums ...float64) float64 {
return nums[0]
},
Priority: 6,
}
}
func Power() Operator {
return Operator{
Symbol: "^",
Operation: func(nums ...float64) float64 {
return math.Pow(nums[0], nums[1])
},
Priority: 4,
}
}
func Add(ops map[string]Operator, elems ...Operator) map[string]Operator {
for _, v := range elems {
ops[v.Symbol] = v
}
return ops
}
func Defaults() map[string]Operator {
all := make(map[string]Operator)
Add(
all,
Plus(),
Minus(),
Multiplication(),
Division(),
Parenthes(),
Power(),
)
return all
}