Simple Haskell Data Pretty-printing

A couple years ago when I was knee-deep in Ruby, there was this really neat module called ‘pp’ that you could use to print out, in prettified format, any data structure.


require 'pp'

a = {0 => [1, 2, 3, [4, 5], 6], 1 => "hello", 2 => ["foo", "bar", "quux", "toto", "tata"], 3 => "this is a long sentence"}


Would result in something like this (depending on your window width):

{0=>[1, 2, 3, [4, 5], 6],
 2=>["foo", "bar", "quux", "toto", "tata"],
 3=>"this is a long sentence"}

Today I discovered that you can do basically the same thing in Haskell with minimum fuss. All you need is the Text.Show.Pretty module (fellow Archers can grab the haskell-pretty-show package on AUR). The github page for the module is here. Here is how you’d use it:

import IO
import qualified Text.Show.Pretty as Pr

data VeryComplexNestedType = VeryComplexNestedType
    { foo :: Foo
    , bar :: Bar
    , quux :: Quux

someData = VeryComplexNestedType ......

main = putStrLn $ Pr.ppShow someData 

It took me quite a while to figure out that the module I needed was Text.Show.Pretty. All the web searches I did for pretty-printing led me to gigantic/industrial libraries like Text.PrettyPrint.HughesPJ or Language.Haskell.Pretty. Those libraries are there to let you customize your own pretty printing function on some arbitrary data type of your choice. But for super-simple, generic pretty-printing like Ruby’s ‘pp’ module, there’s Text.Show.Pretty. For some reason, it remains relatively unknown (the AUR page shows just 1 vote for it as of this writing).

Spread the word!

UPDATE March 13, 2011: In the comments, Neill pointed out that you can also optionally use the “ppsh” executable, which comes with the Text.Show.Pretty module (/usr/bin/ppsh on Arch Linux). Thus, you don’t have to change all of your existing code that uses “show”; all you have to do is pipe the output into ppsh, like “./myprogram | ppsh”. This method is arguably superior because now you don’t have to include Text.Show.Pretty as a dependency in your project.

Update October 30, 2012: To install Text.Show.Pretty (aka pretty-show on Hackage) on Arch Linux, just use cblrepo. The all AUR Haskell packages are pretty much dead at this point.