go语言设计模式之interpreter
Posted aguncn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go语言设计模式之interpreter相关的知识,希望对你有一定的参考价值。
interpreter.go
package interpreter import ( //"fmt" "strconv" "strings" ) const ( SUM = "sum" SUB = "sub" MUL = "mul" DIV = "div" ) type polishNotationStack []int func (p *polishNotationStack) Push(s int) { *p = append(*p, s) } func (p *polishNotationStack) Pop() int { length := len(*p) if length > 0 { temp := (*p)[length-1] *p = (*p)[:length-1] return temp } return 0 } func Calculate(o string) (int, error) { stack := polishNotationStack{} operators := strings.Split(o, " ") for _, operatorString := range operators { if isOperator(operatorString) { right := stack.Pop() left := stack.Pop() mathFunc := getOperationFunc(operatorString) res := mathFunc(left, right) stack.Push(res) } else { val, err := strconv.Atoi(operatorString) if err != nil { return 0, err } stack.Push(val) } } return int(stack.Pop()), nil } func isOperator(o string) bool { if o == SUM || o == SUB || o == MUL || o == DIV { return true } return false } func getOperationFunc(o string) func(a, b int) int { switch o { case SUM: return func(a, b int) int { return a + b } case SUB: return func(a, b int) int { return a - b } case MUL: return func(a, b int) int { return a * b } case DIV: return func(a, b int) int { return a / b } } return nil }
interpreter_test.go
package interpreter import ( "testing" ) func TestCalculate(t *testing.T) { tempOperation := "3 4 sum 2 sub" res, err := Calculate(tempOperation) if err != nil { t.Error(err) } if res != 5 { t.Errorf("Expected result not found: %d != %d ", 5, res) } tempOperation = "5 3 sub 8 mul 4 sum 5 div" res, err = Calculate(tempOperation) if err != nil { t.Error(err) } if res != 4 { t.Errorf("Expected result not found: %d != %d ", 4, res) } }
以上是关于go语言设计模式之interpreter的主要内容,如果未能解决你的问题,请参考以下文章