bittybox

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

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

Go to latest
Published: Mar 13, 2023 License: MIT Imports: 6 Imported by: 0

README

bittybox | Simple floating point calculator

bittybox is a small, underpowered floating point expression evaluator.

Motivation

Performing safe, efficient user-supplied math operations.

Features

Basic operators (+-*/^), grouping, predictable operator precedence, variables, some constants and common unary functions (sin, cos, etc).

Grammar

Expr --> Unit (Binary Unit)*
Unit --> Number | "(" Expr ")" | "-" Unit | Ident
Binary --> "+" | "-" | "*" | "/" | "^"

Some Credits

Initial inspiration from the long abandoned https://github.com/marcak/calc/tree/master/

With advice from https://www.engr.mun.ca/~theo/Misc/exp_parsing.htm

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Evaluate

func Evaluate(formula string, vars ...Var) (float64, error)

Compute will compile and evaluate an expression.

Example
package main

import (
	"fmt"

	"github.com/ischneider/bittybox"
)

func main() {
	fmt.Println(bittybox.Evaluate("5 + y", bittybox.Var{"y", 1}))
}
Output:

6 <nil>

Types

type ErrInvalidSyntax

type ErrInvalidSyntax struct {
	Message string
	Line    int
	Column  int
}

ErrInvalidSyntax describes an invalid expression.

func (ErrInvalidSyntax) Error

func (e ErrInvalidSyntax) Error() string

type ErrUnboundVars

type ErrUnboundVars struct {
	Missing []string
}

ErrUnboundVars is returned when an expression is missing variables.

func (ErrUnboundVars) Error

func (e ErrUnboundVars) Error() string

type Expr

type Expr struct {
	// contains filtered or unexported fields
}

Expr is a compiled expression that can be reused serially.

func CompileExpr

func CompileExpr(formula string, varNames ...string) (Expr, error)

CompileExpr compiles the provided forumula into an Expr.

Example
package main

import (
	"fmt"

	"github.com/ischneider/bittybox"
)

func main() {
	expr, err := bittybox.CompileExpr("5 + y", "y")
	if err != nil {
		panic(err)
	}
	fmt.Println(expr.Evaluate([]float64{10}))
}
Output:

15

func (*Expr) Evaluate

func (e *Expr) Evaluate(vals []float64) float64

Compute evaluates the expression with the provided values. Values must be provided in the order of their corresponding varNames.

type Float

type Float interface {
	float32 | float64
}

type Var

type Var struct {
	Name  string
	Value float64
}

Var is a name, value pair.

Jump to

Keyboard shortcuts

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