go语言设计模式之interpreter
2024-08-30 02:45:04
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) } }
最新文章
- C#+OpenGL+FreeType显示3D文字(1) - 从TTF文件导出字形贴图
- 给 C# 开发者的代码审查清单
- Code First :使用Entity. Framework编程(6) ----转发 收藏
- Libgdx 循环绘制图片时间隔的问题
- Redis Lua脚本原理
- mysql5.7.11安装配置
- Jenkins快速上手
- Libsvm的MATLAB调用和交叉验证
- sql语句分组统计出年月日下数据记录数目
- poj 3678 Katu Puzzle(Two Sat)
- underscorejs-every学习
- putty修改编码
- ubuntu16 网络设置
- 无法加载shockwave flash
- python中html解析-Beautiful Soup
- python读文件指定行的数据
- LINQ的增删改查写法&;&;组合查询
- 第九次Scrum meeting
- 【TensorFlow】CNN
- EditPLus添加到右键图文教程
热门文章
- Java生鲜电商平台-生鲜电商中商品类目、属性、品牌、单位架构设计与实战
- Flask 教程 第十一章:美化
- [springMvc]常见配置
- [Go]TCP服务中增加消息队列与工作池
- 【转载】解决:'webpack-dev-server' 不是内部或外部命令,也不是可运行的程序 或批处理文件。
- uiautomatorviewer 报错 Error while obtaining UI hierarchy XML file: com.android.ddmlib.SyncException: Remote object doesn't exist!
- pytest系列(一):什么是单元测试界的高富帅?
- import com.sun.org.apache.xml.internal.security.utils.Base64问题
- 微信小程序的坑(持续更新中)
- 03-MySQL安装与配置