https://github.com/relnod/calcgo
Interpreter for Numeric Expressions
https://github.com/relnod/calcgo
calculator golang lexer parser
Last synced: 16 days ago
JSON representation
Interpreter for Numeric Expressions
- Host: GitHub
- URL: https://github.com/relnod/calcgo
- Owner: relnod
- License: mit
- Created: 2017-11-11T13:27:42.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2018-03-06T12:10:43.000Z (almost 8 years ago)
- Last Synced: 2025-06-22T20:32:59.784Z (7 months ago)
- Topics: calculator, golang, lexer, parser
- Language: Go
- Homepage:
- Size: 176 KB
- Stars: 6
- Watchers: 3
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Calcgo
[](https://travis-ci.org/relnod/calcgo)
[](https://codecov.io/gh/relnod/calcgo)
[](https://godoc.org/github.com/relnod/calcgo)
[](https://goreportcard.com/report/github.com/relnod/calcgo)
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](#grammar).
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:
``` go
lexer.Lex("(1 + 2) * 3")
```
#### Parser:
``` go
parser.Parse("(1 + 2) * 3")
```
#### Interpreter:
``` go
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.
```go
i := interpreter.NewInterpreter("1 + a")
i.SetVar("a", 1.0)
i.GetResult() // Result: 2
i.SetVar("a", 2.0)
i.GetResult() // Result: 3
```
## Example
``` go
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](../master/LICENSE) file for details.