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 + b*b"
33 //value := []rune(input)
35 variables, program := extractVariables(input)
37 fmt.Println(variables, program)
39 firstPass(program, &Tree)
40 //si es una letra y el stack esta sin setear pon en el A del stack un AST arg
41 //si es una operacion setea la op en el stack
42 //si es un abrir parentesis apunta al lado que este disponible del AST
43 //si es una letra y ya esta seteada la op mete un AST arg a la otra letra
44 //si es un cerrar parentesis coge para el pai.
46 //los numeros se portan justo como las letras.
50 func firstPass(variables, program []rune, node *AST) {
54 firstPass(variables, program[1:], node)
57 firstPass(variables, program[1:], node)
60 firstPass(variables, program[1:], node)
63 firstPass(variables, program[1:], node)
66 firstPass(variables, program[1:], node.Left)
68 firstPass(variables, program[1:], node.Right)
74 if program[0] > 47 && program[0] < 58 {
76 if node.Op == zeroOp {
77 node.Left = &AST{Op: imm, Value: int(program[0]) - 48}
78 firstPass(variables, program[1:], node)
79 //a := &AST{Op: imm, N: 5
81 node.Right = &AST{Op: imm, Value: int(program[0]) - 48}
82 firstPass(variables, program[1:], node)
84 } else if slices.Contains(variables, program[0]) {
86 if node.Op == zeroOp {
87 node.Left = &AST{Op: imm, Value: int(program[0]) - 48}
88 firstPass(variables, program[1:], node)
89 //a := &AST{Op: imm, N: 5
91 node.Right = &AST{Op: imm, Value: int(program[0]) - 48}
92 firstPass(variables, program[1:], node)
102 // extractVariables receives the original program string and converts it in
103 // two rune slices, the first containing the variables and a second containing
104 // the trimmed program
105 func extractVariables(input string) ([]rune, []rune) {
106 variables := strings.Split(input, "]")
107 // Cleaning out the variables that are gettting extracted
108 variables[0] = strings.Split(variables[0], "[")[1]
109 variables[0] = strings.Trim(variables[0], " ")
110 cleanVariables := []rune(variables[0])
111 var resultVariables []rune
112 for _, v := range cleanVariables {
114 resultVariables = append(resultVariables, v)
118 //Cleaning out the program that is getting extracted
119 variables[1] = strings.Trim(variables[1], " ")
120 cleanProgram := []rune(variables[1])
121 var resultProgram []rune
122 for _, v := range cleanProgram {
124 resultProgram = append(resultProgram, v)
130 return resultVariables, resultProgram