[Haskell] Displaying trees in Haskell

John Lato jwlato at gmail.com
Thu Mar 8 16:13:13 CET 2012


> From: Luana Fagarasan <luana_0105 at yahoo.com>
>
> Hello,
>
> I am quite new to Haskell and I am seeking the best way to
> display trees graphically when using Haskell. I have looked on
> the web, but am still not clear!

IMHO Haskell is a good language for this sort of task; there are
several graphics libraries that I would consider fairly mature and
reliable.  I have a project that uses "diagrams"
(http://hackage.haskell.org/package/diagrams) to draw a tree; the code
is:

> import Diagrams.Prelude
>
> drawTree (Node dt children) =
>    fmap (queryFunc $ nodePath dt) (circle 1
>         # scaleY 0.5
>         # fc darkblue
>         # lw 0.1
>         # lc deepskyblue
>         # pad 1.1
>         # named (show $ nodePath dt)
>    )
>   ===
>    (hcat' with {sep = 0.2} (map drawTree children) # centerX)

drawTree could be understood as "draw the current node on top of the
diagram produced by applying the node's children to drawTree".

This function just draws each node as an oval.  "#" is a
diagrams-provided operator to apply parameters to a diagram.  The
"queryFunc" and "named" stuff is to enable queries into the diagram,
so that mouse click coordinates can be converted into a label for the
node (as retrieved by "nodePath").  Depending on what you want to
display for each node, the image could be as simple or complex as you
would like.

Probably the most full-featured diagrams backend uses Cairo, so your
drawings can be rendered in any format Cairo supports (including GTK
widgets).  Other backends are also available although I don't know as
much about them.

HTH,
John Lato



More information about the Haskell mailing list