对输入的内容进行解析,并处理
package main
import (
"log"
"strings"
)
// Interpreter
// 对输入的内容进行解析,并处理
// 如实现表达式解析
// 1、设置表达式模型
// 2、解析模型
// 3、模型赋值
type Expression interface {
Interpret(variables map[string]Expression) int
}
// 正数
type Integer struct {
integer int
}
func (n *Integer) Interpret(variables map[string]Expression) int {
return n.integer
}
// 加号
type Plus struct {
leftOperand Expression
rightOperand Expression
}
func (p *Plus) Interpret(variables map[string]Expression) int {
return p.leftOperand.Interpret(variables) + p.rightOperand.Interpret(variables)
}
// 变量
type Variable struct {
name string
}
func (v *Variable) Interpret(variables map[string]Expression) int {
value, found := variables[v.name]
if !found {
return 0
}
return value.Interpret(variables)
}
// 栈内节点
type Node struct {
value interface{}
next *Node
}
// 栈,单向链表
type Stack struct {
top *Node
size int
}
func (s *Stack) Push(value interface{}) {
s.top = &Node{
value: value,
next: s.top,
}
s.size++
}
func (s *Stack) Pop() interface{} {
if s.size == 0 {
return nil
}
value := s.top.value
s.top = s.top.next
s.size--
return value
}
type Evaluator struct {
syntaxTree Expression
}
func (e Evaluator) Interpret(variables map[string]Expression) int {
return e.syntaxTree.Interpret(variables)
}
func NewEvaluator(expression string) *Evaluator {
expressionStack := &Stack{}
for _, token := range strings.Split(expression, " ") {
switch token {
case "+":
right := expressionStack.Pop().(Expression)
left := expressionStack.Pop().(Expression)
subExpression := &Plus{left, right}
expressionStack.Push(subExpression)
default:
var val Expression = &Variable{name: token}
expressionStack.Push(val)
}
}
syntaxTree := expressionStack.Pop().(Expression)
return &Evaluator{syntaxTree: syntaxTree}
}
func main() {
expression := "w x z +"
sentence := NewEvaluator(expression)
variables := make(map[string]Expression)
variables["w"] = &Integer{integer: 6}
variables["x"] = &Integer{integer: 7}
variables["z"] = &Integer{integer: 8}
result := sentence.Interpret(variables)
// 解析结果为 15 即 x+z 的值
log.Println("result", result)
}
发表回复