Let's implement a dead simple command line calculator from scratch!
Your goal is to implement a very simple command line calculator from scratch in Go. Write an arithmetic expression parser on your own, without using any existing parser libraries.
- Do not use
go/*
packages such asgo/parser
orgo/scanner
in the standard library. - Do not use
text/scanner
package in the standard library. - Do not use any third-party libraries.
- Do not invoke any external processes, for example using
os/exec
package.
The recommended way is TDD style:
- Run
go test
command and make sure all tests are passed (actually no tests are run). - Remove
t.Skip()
line withinTestInt
function inmain_test.go
. - Run
go test
command and make sureTestInt
fails. - Implement
calc
function inmain.go
so that all the tests that failed above are passed. - If all tests have been passed, then remove
t.Skip()
line withinTestAddSub
function inmain_test.go
. - Run
go test
command and make sureTestAddSub
fails. - Update
calc
function inmain.go
so that all the tests that failed above are passed. - If all tests have been passed, then remove
t.Skip()
line withinTestMulDiv
function inmain_test.go
. - In the same way, update
calc
function until all tests inmain_test.go
have been passed after removing allt.Skip()
lines.
Eventually, your calculator should be able to correctly calculate complex arithmetic expressions like this:
$ go build
$ ./simple-calc '(8 - 5) * (-2) + (-9 + 8) * (5 - 7) - 12 / (22 - 16) * (-3)'
2