我的问题:在没有多余括号的情况下漂亮地打印表达式的最简洁方法是什么?
我有以下 lambda 表达式的表示:
Term ::= Fun(String x, Term t)
| App(Term t1, Term t2)
| Var(String x)
按照惯例App
是左结合的,a b c
即被解释为(a b) c
并且函数体尽可能向右伸展,λ x. x y
即被解释为λ x. (x y)
。
我有一个很好的解析器,但现在我想要一个漂亮的打印机。这是我目前拥有的(伪scala):
term match {
case Fun(v, t) => "(λ %s.%s)".format(v, prettyPrint(t))
case App(s, t) => "(%s %s)".format(prettyPrint(s), prettyPrint(t))
case Var(v) => v
}
上面的打印机总是放置(
)
表达式(原子变量除外)。因此Fun(x, App(Fun(y, x), y))
它产生
(λ x.((λ y.x) y))
我想拥有
λ x.(λ y.x) y