diff options
author | Alexander Kiryukhin <a.kiryukhin@mail.ru> | 2021-03-06 22:30:32 +0300 |
---|---|---|
committer | Alexander Kiryukhin <a.kiryukhin@mail.ru> | 2021-03-06 22:30:32 +0300 |
commit | 93740d2d153b3da3a1be5707db1400106e3f6491 (patch) | |
tree | ddf705b638434710fa6304201f560f018f4864fe /example/math_expression/main.go |
Initial
Diffstat (limited to 'example/math_expression/main.go')
-rw-r--r-- | example/math_expression/main.go | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/example/math_expression/main.go b/example/math_expression/main.go new file mode 100644 index 0000000..35f7c3b --- /dev/null +++ b/example/math_expression/main.go @@ -0,0 +1,54 @@ +package main + +import ( + "fmt" + + "github.com/neonxp/unilex" +) + +var output []unilex.Lexem = []unilex.Lexem{} +var opPriority = map[string]int{ + "^": 3, + "!": 3, + "*": 2, + "/": 2, + "+": 1, + "-": 1, +} + +func main() { + + l := unilex.New("10 * (20.0 + 30.0)") + + go l.Run(lexExpression) // Start lexer + + // Read infix expression lexems from lexer and convert them to RPN (reverse polish notation) + rpn := infixToRPNotation(l) + fmt.Println("RPN:", rpn) + + // Calculate RPN + result := calculateRPN(rpn) + fmt.Println("Result:", result) +} + +func lexExpression(l *unilex.Lexer) unilex.StateFunc { + l.AcceptWhile(" \t") + l.Ignore() // Ignore whitespaces + + switch { + case l.Accept("("): + l.Emit("LP") + case l.Accept(")"): + l.Emit("RP") + case unilex.ScanNumber(l): + l.Emit("NUMBER") + case l.Accept("+-*/^!"): + l.Emit("OPERATOR") + case l.Peek() == unilex.EOF: + return nil + default: + return l.Errorf("Unexpected symbol") + } + + return lexExpression +} |