Subject: Re: Q: print arithmetic expression in infix form
From: rpw3@rigden.engr.sgi.com (Rob Warnock)
Date: 1997/03/15
Newsgroups: comp.lang.scheme
Message-ID: <5gd3ml$6s9@tokyo.engr.sgi.com>

Stas Polonsky  <stas@frida.physics.sunysb.edu> wrote:
+---------------
| I'm looking for Scheme function to print arithmetic expression in infix form;
| something like (to-infix '(* (+ 1 2) (+ 3 4))) -> "(1+2)*(3+4)"
+---------------

Going from infix to prefix is "interesting", but going from
prefix to infix is downright trivial. If you're not trying for
the result to have the absolute minimum of parentheses, it's
a simple recursive function:

- If the arg is an atom, print it.

- If the arg is a list, print an open paren, call yourself to print
  the second element, then print a close paren. Then print the first
  element. Then (with parens, as before) call yourself to print the
  third element (if any). For extra credit, you can handle more
  than 3-element lists, e.g., (to-infix '(+ 2 3 4)) ==> "2+3+4".

Reducing the number of parens to a minimum requires a few more
special-case tests, and also requires a table of the relative
priorities of the infix operators. [Hint: pass the priority of
your own operator down to any recursive calls, and let *them*
print the parens, if needed.]


-Rob

-----
Rob Warnock, 7L-551		rpw3@sgi.com
Silicon Graphics, Inc.		http://reality.sgi.com/rpw3/
2011 N. Shoreline Blvd.		Phone: 415-933-1673  FAX: 415-933-0979
Mountain View, CA  94043	PP-ASEL-IA