unilex/example/math_expression/main.go

52 lines
844 B
Go
Raw Normal View History

2021-03-06 22:30:32 +03:00
package main
import (
"fmt"
2024-04-28 02:33:13 +03:00
"go.neonxp.ru/unilex"
2021-03-06 22:30:32 +03:00
)
2022-02-02 22:17:30 +03:00
const (
LP unilex.LexType = iota
RP
NUMBER
OPERATOR
)
2021-03-06 22:30:32 +03:00
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("("):
2022-02-02 22:17:30 +03:00
l.Emit(LP)
2021-03-06 22:30:32 +03:00
case l.Accept(")"):
2022-02-02 22:17:30 +03:00
l.Emit(RP)
2021-03-06 22:30:32 +03:00
case unilex.ScanNumber(l):
2022-02-02 22:17:30 +03:00
l.Emit(NUMBER)
2021-03-06 22:30:32 +03:00
case l.Accept("+-*/^!"):
2022-02-02 22:17:30 +03:00
l.Emit(OPERATOR)
2021-03-06 22:30:32 +03:00
case l.Peek() == unilex.EOF:
return nil
default:
return l.Errorf("Unexpected symbol")
}
return lexExpression
}