CLI Program for Pretty-Printing Haskell Datatypes

2018-03-02

About a year ago I released the pretty-simple Haskell library. pretty-simple gives an easy way to pretty-print Haskell datatypes. It is easier to use and has more features than other pretty-printing libraries.

One drawback of pretty-simple is that if you forget to use it, you're basically out of luck. You need to go back and re-print the datatype using functions provided by pretty-simple. This is quite annoying.

To get around this, I created a small command line program that will pretty-print anything on stdin. I explain how it works below.

Review of pretty-simple

Imagine you have the following datatypes:

data Foo = Foo { foo1 :: Integer , foo2 :: [String] } deriving Show

data Bar = Bar { bar1 :: Double , bar2 :: [Foo] } deriving Show

You then create some values using these datatypes like the following:

foo :: Foo
foo = Foo 3 ["hello", "goodbye"]

bar :: Bar
bar = Bar 10.55 [foo, foo]

If you run this in GHCi and print bar, you get something like the following:

> print bar
Bar {bar1 = 10.55, bar2 = [Foo {foo1 = 3, foo2 = ["hello","goodbye"]},Foo {foo1 = 3, foo2 = ["hello","goodbye"]}]}

This is hard to read.

pPrint from pretty-simple can be used to make this easier to read:

Command Line Interface to pretty-simple

I just released version 2.0.2.1 of pretty-simple. This adds an optional executable that can be used to pretty-print anything passed in on stdin.

It can be installed like the following:

$ stack install pretty-simple-2.0.2.1 --flag pretty-simple:buildexe

This will install an executable called pretty-simple to ~/.local/bin/. Make sure that ~/.local/bin/ is on your PATH before you try to run it. Note that the executable will not get installed if you don't use the buildexe flag.

When run on the command line, it takes all stdin and tries to pretty-print it. That means that after running it and pasting in what you want to format, you need to hit Ctrl-D. Here is an example of running it:

This is great for when you accidentally use print to print something out instead of pPrint. Just copy and paste to get nicely formatted output.

It can also be used for format things with a similar syntax1 to Haskell, like JSON2:

Conclusion

pretty-simple is nice to visualize complex Haskell datatypes. Adding a CLI executable makes it even easier to pretty-print things in a pinch.

Footnotes


  1. It really just requires that the input have balanced parentheses, brackets, braces, and quotes. This is true for a lot of formats, including Haskell datatypes, JSON, Lisp, etc.↩︎

  2. Although if you really want to pretty-print JSON, the jq program is probably a better choice.↩︎

tags: haskell