From 4178bfefea991e5c28060de5fd3420f376cdaa18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petar=20Kapri=C5=A1?= Date: Wed, 15 Jan 2025 21:10:50 +0100 Subject: [PATCH] Add reverse polish notation printer for AST This is meant to complete chapter 5 challenge 3. --- pj1-go/ast-rpn.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 pj1-go/ast-rpn.go diff --git a/pj1-go/ast-rpn.go b/pj1-go/ast-rpn.go new file mode 100644 index 0000000..f2034ae --- /dev/null +++ b/pj1-go/ast-rpn.go @@ -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" +}