pj1/pj1-go/ast-rpn.go

23 lines
497 B
Go
Raw Normal View History

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"
}