Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate formula in Go

Tags:

go

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:

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

Any idea how to do it with Go?

like image 627
jlhonora Avatar asked May 28 '14 23:05

jlhonora


1 Answers

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);
like image 77
swill Avatar answered Oct 22 '22 14:10

swill