calc

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2021 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Evaluate

func Evaluate(s string) (int, error)
Example
fmt.Println(calc.Evaluate("1 + 1"))
fmt.Println(calc.Evaluate("1 + 1 * 1"))
fmt.Println(calc.Evaluate("1 + 1 * 1 + 1"))
fmt.Println(calc.Evaluate("1 + 1 * (1 + 1)"))
fmt.Println(calc.Evaluate("(1 + 1) * (1 + 1)"))
Output:

2 <nil>
2 <nil>
3 <nil>
3 <nil>
4 <nil>

func EvaluateNode

func EvaluateNode(n *Node) int

Types

type CalculatorParser

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

func New

func New(s string) (*CalculatorParser, error)

func (*CalculatorParser) AddSub

func (cp *CalculatorParser) AddSub() (*Node, error)

func (*CalculatorParser) Factor

func (cp *CalculatorParser) Factor() (*Node, error)

func (*CalculatorParser) Integer

func (cp *CalculatorParser) Integer() (int, error)
Example
p, _ := calc.New("007")
fmt.Println(p.Integer())
Output:

7 <nil>

func (*CalculatorParser) MulDiv

func (cp *CalculatorParser) MulDiv() (*Node, error)

func (*CalculatorParser) Space

func (cp *CalculatorParser) Space()

Space consumes all the spaces.

type Node

type Node struct {
	Value int // If leaf node.

	Operators []rune  // An list of operators like '+', '-', '*' or '/'.
	Children  []*Node // The len(Children) should be len(Operators)+1
}

Node is a simple node representation.

Value Node:

1 = {1}

Operator Node:

1 * (1 + 2) = {['*'] [{1}, {['+', [1, 2]]}]}

func Parse

func Parse(s string) (*Node, error)
Example
fmt.Println(calc.Parse("1 + 1"))
fmt.Println(calc.Parse("1 + 1 * 1"))
fmt.Println(calc.Parse("1 + 1 * 1 + 1"))
fmt.Println(calc.Parse("1 + 1 * (1 + 1)"))
fmt.Println(calc.Parse("(1 + 1) * (1 + 1)"))
Output:

(1 + 1) <nil>
(1 + (1 * 1)) <nil>
(1 + (1 * 1) + 1) <nil>
(1 + (1 * (1 + 1))) <nil>
((1 + 1) * (1 + 1)) <nil>

func (*Node) String

func (n *Node) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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