7 "golang.org/x/exp/slices"
30 //a := &AST{Op: imm, N: 5
31 //b := &AST{Op: plus, A: a, B: &AST{Op: arg, N: 0}}
32 input := "[ a b ] (a*a) + (5*5)"
34 variables, program := extractVariables(input)
36 fmt.Println(variables, program)
38 firstPass(variables, program, &Tree)
45 func printer(tree *AST) {
50 fmt.Printf("%c", tree.Value)
72 func firstPass(variables, program []rune, node *AST) {
86 node.Left.Parent = node
90 node.Right.Parent = node
97 if program[0] > 47 && program[0] < 58 {
99 if node.Op == zeroOp {
100 node.Left = &AST{Op: imm, Value: int(program[0]) - 48}
101 //a := &AST{Op: imm, N: 5
103 node.Right = &AST{Op: imm, Value: int(program[0]) - 48}
105 } else if slices.Contains(variables, program[0]) {
107 if node.Op != 2 && node.Op != 3 && node.Op != 4 && node.Op != 5 {
108 node.Left = &AST{Op: arg, Value: int(program[0])}
109 //a := &AST{Op: imm, N: 5
111 node.Right = &AST{Op: arg, Value: int(program[0])}
117 if len(program) > 1 {
118 firstPass(variables, program[1:], pass)
124 func secondPass(node *AST) {
131 if node.Right.Op == imm && node.Left.Op == imm {
135 node.Value = node.Left.Value - node.Right.Value
137 node.Value = node.Left.Value + node.Right.Value
139 node.Value = node.Left.Value * node.Right.Value
141 node.Value = node.Left.Value / node.Right.Value
148 if node.Left.Op != arg && node.Left.Op != imm {
149 secondPass(node.Left)
151 if node.Right.Op != arg && node.Right.Op != imm {
152 secondPass(node.Right)
156 // extractVariables receives the original program string and converts it in
157 // two rune slices, the first containing the variables and a second containing
158 // the trimmed program
159 func extractVariables(input string) ([]rune, []rune) {
160 variables := strings.Split(input, "]")
161 // Cleaning out the variables that are gettting extracted
162 variables[0] = strings.Split(variables[0], "[")[1]
163 variables[0] = strings.Trim(variables[0], " ")
164 cleanVariables := []rune(variables[0])
165 var resultVariables []rune
166 for _, v := range cleanVariables {
168 resultVariables = append(resultVariables, v)
172 //Cleaning out the program that is getting extracted
173 variables[1] = strings.Trim(variables[1], " ")
174 cleanProgram := []rune(variables[1])
175 var resultProgram []rune
176 for _, v := range cleanProgram {
178 resultProgram = append(resultProgram, v)
184 return resultVariables, resultProgram