From d9fbebffdd6ecf376884b4f0867f24bf472c7134 Mon Sep 17 00:00:00 2001 From: Brian Buller Date: Wed, 6 Mar 2019 14:45:30 -0600 Subject: [PATCH] Basic Feature Complete --- .gitignore | 1 + main.go | 85 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 main.go diff --git a/.gitignore b/.gitignore index 7560965..f55b953 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ *.dll *.so *.dylib +stc # Test binary, build with `go test -c` *.test diff --git a/main.go b/main.go new file mode 100644 index 0000000..885bf48 --- /dev/null +++ b/main.go @@ -0,0 +1,85 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" +) + +var stack []float64 + +func pop() float64 { + var x float64 + if len(stack) > 0 { + x, stack = stack[len(stack)-1], stack[:len(stack)-1] + } + return x +} + +func push(v float64) { + stack = append(stack, v) +} + +func addOp(v1, v2 float64) float64 { + fmt.Printf("%f + %f = %f\n", v1, v2, (v1 + v2)) + return v1 + v2 +} +func subtractOp(v1, v2 float64) float64 { + fmt.Printf("%f - %f = %f\n", v1, v2, (v1 - v2)) + return v1 - v2 +} +func multiplyOp(v1, v2 float64) float64 { + fmt.Printf("%f * %f = %f\n", v1, v2, (v1 * v2)) + return v1 * v2 +} +func divideOp(v1, v2 float64) float64 { + fmt.Printf("%f / %f = %f\n", v1, v2, (v1 / v2)) + return v1 / v2 +} + +func main() { + fmt.Println("vim-go") + var in string + reader := bufio.NewReader(os.Stdin) + for { + fmt.Print(stack) + fmt.Print(" > ") + in, _ = reader.ReadString('\n') + in = strings.TrimSpace(in) + switch in { + case ".": + break + case "+": + doStackOperation(addOp) + case "-": + doStackOperation(subtractOp) + case "*": + doStackOperation(multiplyOp) + case "/": + doStackOperation(divideOp) + default: + val, err := strconv.ParseFloat(in, 64) + if err != nil { + fmt.Println(err.Error()) + fmt.Println("Valid inputs: +, -, /, *, ") + fmt.Println("'.' by itself to quit") + } else { + push(val) + } + } + if in == "." { + break + } + } +} + +func doStackOperation(op func(float64, float64) float64) { + if len(stack) < 2 { + fmt.Println("Not enough on stack to add") + return + } + v1, v2 := pop(), pop() + push(op(v1, v2)) +}