title: Pretty print expression with as few parentheses as possible?
body: <p><strong>My Question:</strong> What is the cleanest way to pretty print an expression without redundant parentheses?</p>
  
  <hr>
  
  <p>I have the following representation of lambda expressions:</p>
  
  <pre><code>Term ::= Fun(String x, Term t)
        |  App(Term t1, Term t2)
        |  Var(String x)
  </code></pre>
  
  <p>By convention <code>App</code> is left associative, that is <code>a b c</code> is interpreted as <code>(a b) c</code> and function bodies stretch as far to the right as possible, that is, <code>λ x. x y</code> is interpreted as <code>λ x. (x y)</code>.</p>
  
  <p>I have a parser that does a good job, but now <strong>I want a pretty printer</strong>. Here's what I currently have (pseudo scala):</p>
  
  <pre><code>term match {
      case Fun(v, t) =&gt; "(λ %s.%s)".format(v, prettyPrint(t))
      case App(s, t) =&gt; "(%s %s)".format(prettyPrint(s), prettyPrint(t))
      case Var(v)    =&gt; v
  }
  </code></pre>
  
  <p>The above printer always puts <code>(</code> <code>)</code> around expressions (except for atomic variables). Thus for <code>Fun(x, App(Fun(y, x), y))</code> it produces</p>
  
  <pre><code>(λ x.((λ y.x) y))
  </code></pre>
  
  <p>I would like to have</p>
  
  <pre><code>λ x.(λ y.x) y
  </code></pre>