Evaluate formula in Go

前端 未结 8 958
梦如初夏
梦如初夏 2021-01-02 12:46

Using Go (golang) I\'d like to take a string with a formula and evaluate it with pre-defined values. Here\'s a way to do it with python\'s parser module:

<
相关标签:
8条回答
  • 2021-01-02 13:07

    Googling around I found this: https://github.com/sbinet/go-eval

    It appears to be an eval loop for Go.

    go get github.com/sbinet/go-eval/cmd/go-eval
    go install github.com/sbinet/go-eval/cmd/go-eval
    go-eval
    
    0 讨论(0)
  • 2021-01-02 13:11

    I have made my own equation evaluator, using Djikstra's Shunting Yard Algorithm. It supports all operators, nested parenthesis, functions and even user defined variables.

    It is written in pure go

    https://github.com/marcmak/calc

    0 讨论(0)
  • 2021-01-02 13:11

    With this code you can evaluate dynamically any formula and return true or false:

    package main
    
    import (
        "go/token"
        "go/types"
    )
    
    func main() {
        fs := token.NewFileSet()
        tv, err := types.Eval(fs, nil, token.NoPos, "(1 + 4) >= 5")
        if err != nil {
            panic(err)
        }
        println(tv.Value.String())
    }
    
    0 讨论(0)
  • 2021-01-02 13:21

    This package will probably work for your needs: https://github.com/Knetic/govaluate

    expression, err := govaluate.NewEvaluableExpression("(x + 2) / 10");
    
    parameters := make(map[string]interface{}, 8)
    parameters["x"] = 8;
    
    result, err := expression.Evaluate(parameters);
    
    0 讨论(0)
  • 2021-01-02 13:21

    You will probably need to resort to a library that interprets math statements or have to write your own parser. Python being a dynamic language can parse and execute python code at runtime. Standard Go cannot do that.

    If you want to write a parser on your own, the go package will be of help. Example (On play):

    import (
        "go/ast"
        "go/parser"
        "go/token"
    )
    
    func main() {
        fs := token.NewFileSet()
        tr, _ := parser.ParseExpr("(3-1) * 5")
        ast.Print(fs, tr)
    }
    

    The resulting AST (Abstract Syntax Tree) can then be traversed and interpreted as you choose (handling '+' tokens as addition for the now stored values, for example).

    0 讨论(0)
  • 2021-01-02 13:25

    There's nothing built in that could do that (remember, Go is not a dynamic language).

    However, you can always use bufio.Scanner and build your own parser.

    0 讨论(0)
提交回复
热议问题