码迷,mamicode.com
首页 > 编程语言 > 详细

go语言设计模式之interpreter

时间:2019-11-23 13:04:13      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:mamicode   erro   ota   false   case   ret   length   tac   temp   

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\n", 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\n", 4, res)
	}
}

  技术图片

 

go语言设计模式之interpreter

标签:mamicode   erro   ota   false   case   ret   length   tac   temp   

原文地址:https://www.cnblogs.com/aguncn/p/11916892.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!