[Haskell-cafe] Prettyprinting infix expressions with HughesPJ

Alfonso Acosta alfonso.acosta at gmail.com
Tue Apr 10 03:20:52 EDT 2007


Hi all,

I have to prettyprint infix expressions writing the least possible
parenthesis (taking in account precedence and associativity). A
simplified expression type could be:

data Expr = Val String |
                  -- Binary operators (using infix constructors)
                  Expr :+: Expr  | Expr  :-: Expr  |
                  Expr :*: Expr  | Expr  :/: Expr  |
                  Expr :^: Expr |
                  -- Unary operators
                  Negate Expr


I'm using HughesPJ for the rest of my AST (not just expressions) but
the library doesn't provide any mechanism to help coding this kind of
prettyprinter so I decided to simply use the standard showsPrec and
then feed HughesPJ with the obtained text .

showsPrec helps to take advantage of the precedence information.
However, I don't find a way to remove parenthesis according to
associativity.

I'm sure this kind of prettyprinting has been already done zillions of
times in Haskell. Any suggestions?

Thanks in advance,

Alfonso Acosta


More information about the Haskell-Cafe mailing list