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-09 13:18:14 +02:00
groupExpr = Map(Seq("(", sum, ")"), func(n Result) Result {
return Result{Result: n.Child[1].Result}
2017-08-08 15:11:47 +02:00
})
2017-08-09 13:18:14 +02:00
number = Map(NumberLit(), 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-09 13:18:14 +02:00
sum = Map(Seq(prod, Some(Seq(sumOp, prod))), 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
prod = Map(Seq(&value, Some(Seq(prodOp, &value))), 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)
}
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
}