项目作者: relnod

项目描述 :
Interpreter for Numeric Expressions
高级语言: Go
项目地址: git://github.com/relnod/calcgo.git
创建时间: 2017-11-11T13:27:42Z
项目社区:https://github.com/relnod/calcgo

开源协议:MIT License

下载


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:

  1. lexer.Lex("(1 + 2) * 3")

Parser:

  1. parser.Parse("(1 + 2) * 3")

Interpreter:

  1. interpreter.Interpret("1 + 2 * 3") // Result: 7
  2. interpreter.Interpret("(1 + 2) * 3") // Result: 9

Interpreter with variable:

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

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

Example

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/relnod/calcgo"
  5. )
  6. func main() {
  7. number, _ := calcgo.Calc("1 + 1")
  8. fmt.Println(number)
  9. }

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.