goparsify/calc/calc.go

75 lines
1.2 KiB
Go
Raw Normal View History

2017-08-08 15:11:47 +02:00
package calc
import (
"fmt"
2021-05-07 21:52:01 +02:00
. "kesim.org/goparsify"
2017-08-08 15:11:47 +02:00
)
var (
value Parser
sumOp = Chars("+-", 1, 1)
prodOp = Chars("/*", 1, 1)
2017-08-13 09:30:10 +02:00
groupExpr = Seq("(", sum, ")").Map(func(n *Result) {
n.Result = n.Child[1].Result
2017-08-08 15:11:47 +02:00
})
2017-08-13 09:30:10 +02:00
number = NumberLit().Map(func(n *Result) {
2017-08-08 15:11:47 +02:00
switch i := n.Result.(type) {
case int64:
2017-08-13 09:30:10 +02:00
n.Result = float64(i)
2017-08-08 15:11:47 +02:00
case float64:
2017-08-13 09:30:10 +02:00
n.Result = i
2017-08-08 15:11:47 +02:00
default:
panic(fmt.Errorf("unknown value %#v", i))
}
})
2017-08-13 09:30:10 +02:00
sum = Seq(prod, Some(Seq(sumOp, prod))).Map(func(n *Result) {
2017-08-08 15:11:47 +02:00
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)
}
}
2017-08-13 09:30:10 +02:00
n.Result = i
2017-08-08 15:11:47 +02:00
})
2017-08-13 09:30:10 +02:00
prod = Seq(&value, Some(Seq(prodOp, &value))).Map(func(n *Result) {
2017-08-08 15:11:47 +02:00
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)
}
}
2017-08-13 09:30:10 +02:00
n.Result = i
2017-08-08 15:11:47 +02:00
})
2017-08-09 13:18:14 +02:00
y = Maybe(sum)
2017-08-08 15:11:47 +02:00
)
func init() {
value = Any(number, groupExpr)
}
2017-08-10 16:08:08 +02:00
func calc(input string) (float64, error) {
2017-08-09 13:18:14 +02:00
result, err := Run(y, input)
2017-08-08 15:11:47 +02:00
if err != nil {
return 0, err
}
return result.(float64), nil
}