[Haskell-cafe] How to pretty print code efficiently

Alexander Dunlap alexander.dunlap at gmail.com
Fri Jul 3 23:13:56 EDT 2009


On Fri, Jul 3, 2009 at 6:45 PM, John Ky<newhoggy at gmail.com> wrote:
> Hi,
>
> Currently I'm pretty printing code by building arrays of strings and calling
> indent.  For example:
>
> instance JavaPrintableNamed AST.EnumeratedType where
>    javaLinesNamed parentName (AST.EnumeratedType memberDefinitions) =
>       [ "public enum " ++ asJavaId(parentName)
>       , "{"
>       ] ++ memberCodeLines ++
>       [ "}"
>       , ""
>       ]
>       where
>          memberCodeLines = indent $ javaLines memberDefinitions
>
> The indent function takes a list of strings and adds an indent to the
> beginning of every line.
>
> I can imagine this to be very inefficient as it builds many strings and
> concatenates them.
>
> In Ruby, I might do the same thing like this:
>
> class EnumeratedType < JavaPrintableNamed
>    def writeTo(writer)
>       writer.print "public enum "
>       writer.puts self.asJavaId
>       writer.puts "{"
>       writer.indent do
>          self.memberDefinitions.writeTo(writer)
>          writer.puts
>       end
>
> where above, the writer.indent takes care of the indent, and everything is
> appended to a stream, which doesn't seem so bad in terms of efficiency.
>
> I'm looking for a way to do something similar in Haskell.
>
> Anyone can give me a hand?
>
> Thanks
>
> -John
>
>
> _______________________________________________

You may want to investigate the standard module
Text.PrettyPrint.HughesPJ, which contains a number of (I assume fairly
efficient) combinators for pretty printing.

Alex


More information about the Haskell-Cafe mailing list