Basic Feature Complete

This commit is contained in:
Brian Buller 2019-03-06 14:45:30 -06:00
parent c0d64ecb76
commit d9fbebffdd
2 changed files with 86 additions and 0 deletions

1
.gitignore vendored
View File

@ -4,6 +4,7 @@
*.dll
*.so
*.dylib
stc
# Test binary, build with `go test -c`
*.test

85
main.go Normal file
View File

@ -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: +, -, /, *, <float>")
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))
}