expr

package module
v0.0.0-...-f38277b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 4, 2016 License: MIT Imports: 5 Imported by: 0

README

expr - tiny yet super fast math expression evaluator in Go

GoDoc Build Status codecov.io

Example

vars := map[string]expr.Var{
	"x": NewVar(5),
}
funcs := map[string]expr.Func{
	"next": NewFunc(func(args expr.FuncArgs, env expr.FuncEnv) expr.Num {
		return expr.Num(args[0].Eval()+1)
	}),
}
vars["x"].Set(5)
e, err := expr.Parse("y=x+5/next(x)", vars, funcs)
if err != nil {
	log.Fatal(err)
}
result := e.Eval()
log.Println(result)
log.Println(vars["y"])

Performance

The goal is to speed up frequent evaluations of immutable expressions. For example, user enters a formula to calculate some metrics and backend does the calculation. Formula itself changes rarely, but is evaluated very often.

On my dual-core laptop the benchmark shows that:

  • Parsing expression x=2+3*(x/(42+plusone(x))),x takes 14us, evaluation takes 65ns.
  • Parsing a more complex expression of 280 chars takes 112us, evaluation takes 649ns.
  • Parsing an even more complex expresison of ~3k chars takes 1ms, evaluation takes 7us.

This probably means that time grows linearly depending on the formula length and the performance is really good for short (human-generated) formulas.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrParen                = errors.New("parenthesis mismatch")
	ErrUnexpectedNumber     = errors.New("unexpected number")
	ErrUnexpectedIdentifier = errors.New("unexpected identifier")

	ErrBadCall        = errors.New("function call expected")
	ErrBadVar         = errors.New("variable expected in assignment")
	ErrBadOp          = errors.New("unknown operator or function")
	ErrOperandMissing = errors.New("missing operand")
)

Functions

This section is empty.

Types

type Expr

type Expr interface {
	Eval() Num
}

func Parse

func Parse(input string, vars map[string]Var, funcs map[string]Func) (Expr, error)

type Func

type Func func(f *FuncContext) Num

type FuncContext

type FuncContext struct {
	Args []Expr
	Vars map[string]Var
	Env  interface{}
	// contains filtered or unexported fields
}

func (*FuncContext) Eval

func (f *FuncContext) Eval() Num

func (*FuncContext) String

func (f *FuncContext) String() string

type Num

type Num float64

type Var

type Var interface {
	Expr
	Set(value Num)
	Get() Num
}

Mutable variable expression returns the currently stored value of the variable

func NewVar

func NewVar(value Num) Var

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL