goparsify/calc/calc.go

75 lines
1.3 KiB
Go
Raw Normal View History

2017-08-08 15:11:47 +02:00
package calc
import (
"fmt"
. "github.com/vektah/goparsify"
)
var (
value Parser
sumOp = Chars("+-", 1, 1)
prodOp = Chars("/*", 1, 1)
2017-08-13 04:56:46 +02:00
groupExpr = Seq("(", sum, ")").Map(func(n Result) Result {
2017-08-09 13:18:14 +02:00
return Result{Result: n.Child[1].Result}
2017-08-08 15:11:47 +02:00
})
2017-08-13 04:56:46 +02:00
number = NumberLit().Map(func(n Result) Result {
2017-08-08 15:11:47 +02:00
switch i := n.Result.(type) {
case int64:
2017-08-09 13:18:14 +02:00
return Result{Result: float64(i)}
2017-08-08 15:11:47 +02:00
case float64:
2017-08-09 13:18:14 +02:00
return Result{Result: i}
2017-08-08 15:11:47 +02:00
default:
panic(fmt.Errorf("unknown value %#v", i))
}
})
2017-08-13 04:56:46 +02:00
sum = Seq(prod, Some(Seq(sumOp, prod))).Map(func(n Result) 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-09 13:18:14 +02:00
return Result{Result: i}
2017-08-08 15:11:47 +02:00
})
2017-08-13 04:56:46 +02:00
prod = Seq(&value, Some(Seq(prodOp, &value))).Map(func(n Result) 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-09 13:18:14 +02:00
return Result{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
}