[Haskell-cafe] Pretty printing a tree
wren ng thornton
wren at freegeek.org
Fri May 15 04:33:52 EDT 2009
José Romildo Malaquias wrote:
> Hello.
>
> I would like to pretty print a tree in a way that its structure is
> easily perceived.
>
> For instance, consider the declarations:
>
> data Node a = Node a [Node a]
>
> type Tree a = [ Node a ]
>
> t = [ Node "a" [ Node "b" []
> , Node "c" [ Node "c1" []
> , Node "c2" [] ]
> , Node "d" [ Node "d1" [ Node "d1a" [] ]
> , Node "d2" [] ] ] ]
>
> Then the resulting of pretty printing the given tree would be something
> like the following:
>
> a
> |
> +-------------+
> | | |
> b c d
> | |
> +---+ +---+
> | | | |
> c1 c2 d1 d2
> |
> d1a
If you're just curious about how one would write such a thing, you can
look at Data.Trie.Internal.showTrie[1]--- it's horizontal rather than
vertical, and it doesn't center labels above their children, but it
should give you a starting idea. Data.Map and Data.IntMap also have
examples (showTree, showTreeWith) which are a bit simpler.
This is a common homework assignment (because it's a great exercise!)
though I haven't seen any prepackaged generic solutions. Perhaps we need
more enterprising students :)
[1]
http://community.haskell.org/~wren/bytestring-trie/src/Data/Trie/Internal.hs
--
Live well,
~wren
More information about the Haskell-Cafe
mailing list