calcgo

package module
v0.0.0-...-11998ec Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2018 License: MIT Imports: 1 Imported by: 1

README

Calcgo

Build Status codecov Godoc Go Report Card

This is an experimental learning project, to better understand the process of lexing and parsing.

Description

Calcgo exposes a lexer, parser and interpreter to get tokens, an ast and the result of a basic mathematical calculation. All three functions accept a language L(G) defined here.

The calculations follow basic math rules, like "multiplication and division first, then addition and subtraction" rule. To break this rule it is possible to use brackets. There needs to be at least one whitespace character between an operator an a number. All other whitespace character get ignored by the lexer.

Lexer:
lexer.Lex("(1 + 2) * 3")
Parser:
parser.Parse("(1 + 2) * 3")
Interpreter:
interpreter.Interpret("1 + 2 * 3")   // Result: 7
interpreter.Interpret("(1 + 2) * 3") // Result: 9
Interpreter with variable:

Calcgo supports variables. An instantiation of all variables has to be supplied before interpreting.

i := interpreter.NewInterpreter("1 + a")
i.SetVar("a", 1.0)
i.GetResult() // Result: 2
i.SetVar("a", 2.0)
i.GetResult() // Result: 3

Example

package main

import (
	"fmt"

	"github.com/relnod/calcgo"
)

func main() {
	number, _ := calcgo.Calc("1 + 1")

	fmt.Println(number)
}

Tests and Benchmarks

Running Tests

Run tests with go test -v -race ./... or with ginkgo -r -v.

Running Benchmarks

Benchmarks can be tun with go test -run=^$ -bench=. ./...

To see the differences between current branch and master run ./scripts/benchcmp.sh -n 5

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Calc

func Calc(expression string) (float64, []error)

Calc calculates a numerical expression. May return any number of errors, that occur during lexing, parsing or interpreting.

Types

This section is empty.

Directories

Path Synopsis
cmd
Package parser contains the parser of calcgo.
Package parser contains the parser of calcgo.

Jump to

Keyboard shortcuts

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