Add reverse polish notation printer for AST

This is meant to complete chapter 5 challenge 3.
This commit is contained in:
Petar Kapriš 2025-01-15 21:10:50 +01:00
parent a647c39ec4
commit 4178bfefea

22
pj1-go/ast-rpn.go Normal file
View file

@ -0,0 +1,22 @@
package main
import (
"fmt"
)
func rpn(expr Expr) string {
switch e := expr.(type) {
case Binary:
return rpn(e.left) + " " + rpn(e.right) + " " + e.operator.Lexeme
case Grouping:
return rpn(e.expression) // + " group" arguable if this is even wanted
case Literal:
if e.value == nil {
return "nil"
}
return fmt.Sprintf("%v", e.value)
case Unary:
return rpn(e.right) + fmt.Sprintf(" %v", e.operator.Lexeme)
}
return "ERROR: reached impossible branch in print function"
}