-
Notifications
You must be signed in to change notification settings - Fork 16
/
calc.go
74 lines (58 loc) · 1.24 KB
/
calc.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
package calc
import (
"fmt"
. "github.com/vektah/goparsify"
)
var (
value Parser
sumOp = Chars("+-", 1, 1)
prodOp = Chars("/*", 1, 1)
groupExpr = Seq("(", sum, ")").Map(func(n *Result) {
n.Result = n.Child[1].Result
})
number = NumberLit().Map(func(n *Result) {
switch i := n.Result.(type) {
case int64:
n.Result = float64(i)
case float64:
n.Result = i
default:
panic(fmt.Errorf("unknown value %#v", i))
}
})
sum = Seq(prod, Some(Seq(sumOp, prod))).Map(func(n *Result) {
i := n.Child[0].Result.(float64)
for _, op := range n.Child[1].Child {
switch op.Child[0].Token {
case "+":
i += op.Child[1].Result.(float64)
case "-":
i -= op.Child[1].Result.(float64)
}
}
n.Result = i
})
prod = Seq(&value, Some(Seq(prodOp, &value))).Map(func(n *Result) {
i := n.Child[0].Result.(float64)
for _, op := range n.Child[1].Child {
switch op.Child[0].Token {
case "/":
i /= op.Child[1].Result.(float64)
case "*":
i *= op.Child[1].Result.(float64)
}
}
n.Result = i
})
y = Maybe(sum)
)
func init() {
value = Any(number, groupExpr)
}
func calc(input string) (float64, error) {
result, err := Run(y, input)
if err != nil {
return 0, err
}
return result.(float64), nil
}