Rate formula in Go

Using Go (golang) I would like to take a line with a formula and evaluate it with predefined values. Here you can do it with the python parser module:

 x = 8 code = parser.expr("(x + 2) / 10").compile() print eval(code) # prints 1 

Any idea how to do this with Go?

+6
source share
7 answers

You may have to resort to a library that interprets mathematical statements or must write its own parser. Python, a dynamic language, can parse and execute python code at runtime. Standard Go cannot do this.

If you want to write a parser yourself, the go package will be useful. Example ( In game ):

 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 of your choice (for example, processing "+" tokens as an addition for already saved values).

+10
source

I made my own equation evaluator using the Djikstra Shunting Yard Algorithm . It supports all operators, nested brackets, functions, and even user variables.

It is written in pure go

https://github.com/marcmak/calc

+4
source

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); 
+3
source

Go has no such module. You must build your own. You can use go package subpackages , but they may be excessive for your application.

+1
source

There is nothing to do this (remember that Go is not a dynamic language).

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

0
source

To express or evaluate a program, you can create a lexer and parser using lex and yacc, and specify the exact syntax and semantics of your mini-language. The calculator has always been a standard example of yacc, and the versions of go and leacc are no different.

Here's a pointer to a calculation example: https://github.com/golang-samples/yacc/tree/master/simple

0
source

A googling search I found this: https://github.com/sbinet/go-eval

This seems 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
source

Source: https://habr.com/ru/post/970014/


All Articles