<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>«Insert Name Here»</title>
	<atom:link href="http://ivanmiljenovic.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://ivanmiljenovic.wordpress.com</link>
	<description>Getting into blogging before it&#039;s too late</description>
	<lastBuildDate>Thu, 09 May 2013 12:55:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='ivanmiljenovic.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>«Insert Name Here»</title>
		<link>http://ivanmiljenovic.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://ivanmiljenovic.wordpress.com/osd.xml" title="«Insert Name Here»" />
	<atom:link rel='hub' href='http://ivanmiljenovic.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Announcing planar-graph</title>
		<link>http://ivanmiljenovic.wordpress.com/2012/04/27/announcing-planar-graph/</link>
		<comments>http://ivanmiljenovic.wordpress.com/2012/04/27/announcing-planar-graph/#comments</comments>
		<pubDate>Fri, 27 Apr 2012 10:22:44 +0000</pubDate>
		<dc:creator>Ivan Miljenovic</dc:creator>
				<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://ivanmiljenovic.wordpress.com/?p=192</guid>
		<description><![CDATA[I’ve been working on a new planar graph library on and off for just over the past year. I realise that this might not be exactly a much-sought-after library, but I’ve been using this as a test-bed for various ideas I’ve been having for a &#8220;normal&#8221; graph library. I’m going to discuss various aspects of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=192&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I’ve been working on a new <a href="http://hackage.haskell.org/package/planar-graph">planar graph library</a> on and off for just over the past year.</p>
<p>I realise that this might not be exactly a much-sought-after library, but I’ve been using this as a test-bed for various ideas I’ve been having for a &#8220;normal&#8221; graph library. I’m going to discuss various aspects of the design of this library and some ideas I’ve had for an extensible graph library.</p>
<h3 id="what-is-a-graph">What is a graph?</h3>
<p>The <a href="http://en.wikipedia.org/wiki/Graph_%28mathematics%29#Graph">standard definition</a> of a graph is as follows:</p>
<blockquote>
<p>a graph is an ordered pair <span class="math"><em>G</em> = (<em>V</em>, <em>E</em>)</span> comprising a set <span class="math"><em>V</em></span> of vertices or nodes together with a set <span class="math"><em>E</em></span> of edges or lines, which are 2-element subsets of <span class="math"><em>V</em></span> (i.e., an edge is related with two vertices, and the relation is represented as unordered pair of the vertices with respect to the particular edge).</p>
</blockquote>
<p>However, this definition is rather limiting: by assuming that an edge is comprised of a two-element subset of the vertices, we make it harder for us to consider it computationally: in practice we don’t <em>have</em> a data-structure that represents a two-element set. In practice, we instead tend to use something like <code>(Node,Node)</code>. However, this isn’t ideal:</p>
<ul>
<li>
<p>Using this representation implicitly makes graphs directed rather than undirected, unless you do a lot more bookkeeping by checking both elements of the tuple. In practice this may not be too much of a problem, as people <em>want</em> directed graphs, but this doesn’t make it perfect.</p>
</li>
<li>
<p>The directionality of an edge is now part of its definition rather than being a property of the edge: that is, whether the edge is meant to be directed or not should be a value that can be <em>determined</em> from the edge; currently all edges are directed and undirected graphs are simulated with two inverse edges.</p>
</li>
<li>
<p>Multiple edges become difficult to handle: if you want to delete an edge between node <code>n1</code> and node <code>n2</code> and there are three edges there, how do you know which one to delete? In practice, the answer seems to be &#8220;all of them&#8221;.</p>
</li>
</ul>
<p>A more preferable definition was stated by W. T. Tutte in a 1961 paper:</p>
<blockquote>
<p>A graph <span class="math"><em>G</em></span> consists of a set <span class="math"><em>E</em>(<em>G</em>)</span> of edges and a (disjoint) set <span class="math"><em>V</em>(<em>G</em>)</span> of vertices, together with a relation of incidence which associates with each edge two vertices, not necessarily distinct, called its ends. An edge is a loop if its ends coincide and a link otherwise.</p>
</blockquote>
<p>Note that no indication is given of <span class="math"><em>E</em></span> being a set of two-sets: instead, a mapping exists between every <span class="math"><em>e</em> ∈ <em>E</em></span> to the two endpoints of that edge.</p>
<h4 id="planar-graphs">Planar graphs</h4>
<p>A <a href="http://en.wikipedia.org/wiki/Planar_graph">planar graph</a> is a graph that can be drawn on a specified surface (usually a plane or a sphere) such that no edges intersect/cross except at their endpoints.</p>
<p>When considering a planar graph programmatically, we also want to take into account their <em>embedding</em> (i.e. where all the edges adjacent to a node are in relation to each other). As such, just using an approach of identifying edges solely by their end points fails completely if there are multiple edges. As such, using a unique identifier for each edge is preferable.</p>
<p>But the difficulty of endpoint identification (i.e. distinguishing between <code>(n1,n2)</code>) remains. As such, <a href="http://en.wikipedia.org/wiki/Doubly_connected_edge_list">several</a> <a href="http://cs.anu.edu.au/~bdm/plantri/">implementations</a> of planar graphs use <em>two</em> identifiers for each edge. More about this later.</p>
<h3 id="library-implementation">Library implementation</h3>
<p>As I said earlier, I’ve been using the development of this library as a way to experiment with various approaches to how to design a graph library, all of which I intend to use in a <em>non</em>-planar graph library.</p>
<h4 id="abstract-node-identifiers">Abstract node identifiers</h4>
<p>Most existing graph libraries (e.g. <a href="http://hackage.haskell.org/packages/archive/containers/0.4.2.1/doc/html/Data-Graph.html">Data.Graph</a> and <a href="http://hackage.haskell.org/package/fgl">fgl</a>) use a type alias on <code>Int</code> values to represent vertices/nodes. Furthermore, when considering how to create a graph, it requires that you:</p>
<ol>
<li>
<p>Explicitly come up with new node identifier for each new node;</p>
</li>
<li>
<p>Make sure you don’t re-use an existing identifier.</p>
</li>
</ol>
<p>Whilst this isn’t a big problem if considering a bulk creation of a graph (i.e. you have some arbitrary <code>[a]</code> representing the nodes and edges represented as <code>[(a,a)]</code>, in which case a <code>zip</code>-based solution can be used to assign node identifiers, etc. though it would be a tad messy), it isn’t ideal for adding new nodes on after the fact and it is also open to abuse.</p>
<p>As such, <code>planar-graph</code> does not permit users to create node identifiers: the constructor isn’t exported, it isn’t an instance of <code>Enum</code> or <code>Bounded</code>, etc. Instead, you provide the label for the new node you want to add and the function returns the updated graph <em>and</em> the identifier for the new node. When the node identifiers are changed for some reason (e.g. merging two graphs), a function is returned that allows you to update the values of any node identifiers you’ve been storing elsewhere.</p>
<p><code>Show</code> and <code>Read</code> instances are available and leak some of the internals out, but you have to really be persistent to try and abuse them to create your own identifier values: you need to explicitly call <code>read</code> on the <code>String</code> to get it to parse as the result <em>isn’t</em> valid Haskell code (as the instances exist solely for debugging).</p>
<h4 id="half-edges">Half-edges</h4>
<p>As intimated earlier, each edge is actually represented by two <em>half</em>-edges: an edge from <code>n1</code> to <code>n2</code> is &#8220;stored&#8221; twice: one half-edge <code>n1 -&gt; n2</code> and its inverse <code>n2 -&gt; n1</code> (this also includes loops). Each half-edge has its unique identifier (which is abstract, just as with nodes) and mapping function exists that lets you determine a half-edge’s inverse.</p>
<p>Most graph implementations are something like a newtyped version of:</p>
<pre class="brush: plain; title: ; notranslate">
type Graph = Map Node [Node]
</pre>
<p>where each node has information on its adjacent nodes. Or, if we consider a graph with labels, we have:</p>
<pre class="brush: plain; title: ; notranslate">
type LabelledGraph n e = Map Node (n, [(Node,e)])
</pre>
<p>Instead, the definition of planar-graph looks more like (just considering the labelled version):</p>
<pre class="brush: plain; title: ; notranslate">
type PlanarGraph n e = ( Map Node (n, [Edge])
                       , Map Edge (Node, e, Node, Edge)
                       )
</pre>
<p>where a mapping exists between a half-edge identifier and the corresponding node that it comes from, the label of that half-edge, the node that it is going to and its inverse half-edge. This definition matches the mathematical ones stated earlier <em>much</em> more closely.</p>
<p>Now, this half-edge usage might be a requirement for a planar graph data structure, but it is also viable for non-planar graphs. First of all, if we wished to allow multiple edges between two nodes, then the traditional representation must be altered slightly:</p>
<pre class="brush: plain; title: ; notranslate">
type LabelledGraph' n e = Map Node (n, [(Node,[e])])
</pre>
<p>Each edge representation now keeps a list of edge labels, one per edge between the two nodes. Extra bookkeeping is required about what to do when that list becomes empty (and in fact previous fgl versions had an implementation where this list wasn’t considered at all and thus multiple edges would silently fail).</p>
<p>Also, consider how fgl-style graphs are implemented:</p>
<pre class="brush: plain; title: ; notranslate">
type FGLGraph n e = Map Node ([(Node,e)], n, [(Node,e)])
</pre>
<p>Here, each node stores not only the outgoing edges but also the <em>incoming</em> edges for efficiency reasons (otherwise we’d need to traverse all edges in the graph to determine what the incoming edges are). This also leads to possible data corruption issues as each edge label is stored twice.</p>
<p>However, with our half-edge implementation, neither of these points need any change: each multiple edge has its own unique identifier, and to obtain the incoming edges we just determine the inverse of all the outgoing edges (though technically this point isn’t quite valid when considering directed graphs, as planar-graph treats them differently; see the next section).</p>
<h4 id="distinguishing-between-structure-and-content">Distinguishing between structure and content</h4>
<p>Most graph implementations conflate the structure of the graph (i.e. which nodes and edges there are) with the information that graph is representing. One example is the question of graph orientation: in fgl, a graph can be considered to be undirected if each edge is represented twice; however, it is quite possible that such a graph is <strong>not</strong> undirected but just happens to have each directed edge having an inverse (e.g. some kind of flow algorithm).</p>
<p>Whilst it is not fully formalised as yet, in planar-graph the orientation of a graph is dictated by its half-edge <em>labels</em>: in my use case that prompted the development of this library, I had a need for mixed-orientation of a graph: one half-edge pairing might have had a fixed direction on one half-edge whilst its inverse had a label of &#8220;<code>InverseEdge</code>&#8220;; other pairings might both have some kind of partial edge label.</p>
<p>But the actual edge <em>identifiers</em> didn’t change: I could apply a mapping function to transform all edge labels to <code>()</code> and thus make the graph &#8220;undirected&#8221;, but I didn’t need to change the actual <em>structure</em> of the graph to do so.</p>
<p>I believe this is a much more useful way of considering graphs, where the information that the graph represents can be found in the node and edge labels, not the identifiers.</p>
<h4 id="serialisation-and-encoding">Serialisation and encoding</h4>
<p>I needed to be able to encode my planar graphs using various binary encodings (e.g. <code>PLANAR_CODE</code>, described in Appendix A <a href="http://cs.anu.edu.au/~bdm/plantri/plantri-guide.txt">here</a>). Now, I <em>could</em> have written custom encoding functions from a <code>PlanarGraph</code> to a <code>ByteString</code> for every possible encoding; however, since they all follow the same basic underlying structure, I decide to utilise an intermediary list-based representation.</p>
<p>However, I then realised that this representation could also be used for <code>Show</code> and <code>Read</code> instances for the graphs as well as pretty-printing functions. The definition of the representation is:</p>
<pre class="brush: plain; title: ; notranslate">
[( node index
 , node label
 , [( edge index
    , node index that this edge points to
    , edge label
    , inverse edge index
   )]
)]
</pre>
<p>For <code>Show</code>, <code>Read</code>, etc. this is basically a raw dump of the graph (which means it is technically open to abuse as the internals of the abstract identifiers are accessible this way, but I had to draw the line <em>somewhere</em>); the <code>deserialise</code> function that is utilised by <code>Read</code> also ended up being useful for an internal function rather than manually trying to construct a graph!</p>
<p>For encoding/decoding of binary representations, a re-numbering of the identifiers according to a breadth-first traversal is first undertaken (as many require that the identifiers be <code>0 ... n-1</code> and for decoding the order of edges for each node is important) and then the same structure is used. A class is then used to convert the graph into this representation and then convert it to the encoding of your choice.</p>
<p>However, not all of the encodings require that the graph be planar: whilst a breadth-first traversal doesn’t make as much sense for non-planar graphs, the same framework could be used for other graph types.</p>
<h3 id="plans-for-the-new-graph-library">Plans for the new graph library</h3>
<p>I haven’t even started to prototype this, as some of the ideas I’m listing below I only started to mentally flesh out over the past few days. However, I think that it should work and will provide a useful approach to dealing with graphs in Haskell.</p>
<p>The root of my idea is that we often have different properties that we want graphs to hold: should it be a directed graph? What should the identifier types be? Is there any way to automatically determine all nodes with a certain label (e.g. for graph colouring)? What kind should the graph have?</p>
<p>The current methods of dealing with such a thing is to have a graph implementation, and just live with it. This &#8220;solution&#8221; clearly has problems, not least of which is that if you try to do anything else you have to re-implement everything yourself.</p>
<p>However, consider this: we have a method of generalising monads via <em>monad transformers</em>: why not do the same thing with graphs?</p>
<p>Now, I’m not the first person to think of this; Edward Kmett has already released a <a href="http://hackage.haskell.org/package/graphs">library</a> that has this kind of characteristic (though his classes differ from how I’m planning on structure/distinguish them by having them more implementation-based than property-based IMO).</p>
<p>What <em>my</em> plans entail is this:</p>
<ul>
<li>
<p>Define a <code>GraphTransformer</code> class. Not only will graph transformers be instances of this class, but so will the actual <em>graph types</em> (with identities for the different lift/unlift functions):</p>
<pre class="brush: plain; title: ; notranslate">
class (Graph (SubGraph gt)) =&gt; GraphTransformer gt where
    type SubGraph gt :: *

    .....
</pre>
</li>
<li>
<p>The <code>Graph</code> class then requires that the instance type also be an instance of <code>GraphTransformer</code>, and has default definitions of all methods using the lift/unlift functions. These default definitions will resolve down to <code>f = f</code> definitions for actual graph types, but for transformers will just apply the function down the stack.</p>
<p>This class only defines &#8220;getters&#8221;: e.g. determine the size of the graph, get all its nodes or edges, etc.</p>
</li>
<li>
<p>Other classes are defined as sub-classes of <code>Graph</code>, again using lift/unlift functions from <code>GraphTransformer</code> for default definitions of the methods.</p>
</li>
<li>
<p>Most classes (except for where it’s necessary, e.g. a class defining mapping functions) will assume that the graph is of kind <code>*</code>.</p>
</li>
<li>
<p>Most transformers will assume that the underlying graph is of kind <code>* -&gt; * -&gt; *</code> (i.e. that you can specify node and edge labels) so that you can make the transformer an instance of any class that requires kind <code>* -&gt; * -&gt; *</code>, but it should be possible to make transformers that take in a graph of kind <code>*</code>.</p>
</li>
<li>
<p>Because of the default definitions using lift/unlift functions, most class instances for the graph transformers will be of the form <code>instance Graph (MyTransformer ExistingGraph a b)</code>; this means that if you want to newtype your graph transformer stack, writing the instances will be trivial (albeit rather repetitive and boring).</p>
<p>As such, if a transformer only effects one small aspect of graph manipulation (e.g. a transformer that keeps a <code>Map</code> of node labels to node IDs so you can more efficiently look up all nodes that have a particular label), then you only need to provide explicit definitions for those classes and methods (in this case, adding and deleting nodes and looking up node identifiers based upon labels rather than filtering on the entire list of nodes).</p>
<p>However, this does mean that any kind of unique operation you can think of (e.g. in the example above the ability to find all identifiers for nodes that have a particular label), you will need to create a new class and make appropriate instances for underlying types (if possible) and existing transformers (so that if you put extra transformers on the stack you can still use the improved definitions for this transformer).</p>
</li>
<li>
<p>Usage of the serialisation and encoding functionality for all graphs. This will provide <code>Show</code>/<code>Read</code> instances for graphs, pretty-printing, easy <code>Binary</code> instances (using the serialised form) and any available encodings specified.</p>
<p>The actual method of this may change from what I’ve described above, as whilst a breadth-first traversal of a planar graph is unique up to the first edge chosen, for non-planar graphs this isn’t the case. However, for encodings that don’t assume a planar graph this shouldn’t be a problem.</p>
</li>
<li>
<p>Whilst the provided underlying graph types might use abstract node identifiers, it will not be required for instances of <code>Graph</code> to do so (and a transformer will be provided to let you specify your own type, that under-the-hood maps to the generated abstract identifiers). However, I can’t see a way around having edges using some kind of abstract edge identifier, as it isn’t as common to attach a unique label to each edge.</p>
</li>
</ul>
<p>Generally, transformers will utilise the node and edge labels of the underlying graph stack to store extra metadata (e.g. directionality of the edges); this is why the transformers will typically require that the underlying type is of kind <code>* -&gt; * -&gt; *</code>. However, the question then arises: should users be aware of these underlying type transformations? For example, should this information leak out with a <code>Show</code> instance?</p>
<p>My current thinking is that it shouldn’t: the output from <code>Show</code>, <code>prettyPrint</code>, etc. should be as if there were <em>no</em> transformers being used. The main counter-example I can think of is to have some kind of indicator whether each listed half-edge is the &#8220;real&#8221; one or not, especially when using a transformer that makes it a directed edge (though in this case it can be solved by only listing the &#8220;primary&#8221; half-edges and not their inverses; this again works for most graph types but not planar ones, as all half-edges need to be listed for the graph to be re-created due to the embedding of edge orders).</p>
<p>Assuming this all works (I plan on starting playing with it next week), I think this approach will do quite well. As you’re writing your code, if you use a newtype/type alias for your graph type, you can just add or remove a transformer from your stack without affecting usage (in most cases: some transformers might change which classes a stack can be used in; e.g. a transformer that lets you specify node identifiers will require using a different class for adding nodes than one that generates and returns identifiers for you). Then at the end if you want to try and tweak performance, you can always go and write custom transformers (or indeed your own graph type if you want to merge all the functionality in to the actual type without using transformers) without having to change your code.</p>
<p><em>If</em> this all works as I think/hope it will… <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<br />Filed under: <a href='http://ivanmiljenovic.wordpress.com/category/graphs/'>Graphs</a>, <a href='http://ivanmiljenovic.wordpress.com/category/haskell/'>Haskell</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ivanmiljenovic.wordpress.com/192/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ivanmiljenovic.wordpress.com/192/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=192&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ivanmiljenovic.wordpress.com/2012/04/27/announcing-planar-graph/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/82401038e87257529066b9e6618d470e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ivanm</media:title>
		</media:content>
	</item>
		<item>
		<title>graphviz in vacuum</title>
		<link>http://ivanmiljenovic.wordpress.com/2011/10/16/graphviz-in-vacuum/</link>
		<comments>http://ivanmiljenovic.wordpress.com/2011/10/16/graphviz-in-vacuum/#comments</comments>
		<pubDate>Sun, 16 Oct 2011 10:49:56 +0000</pubDate>
		<dc:creator>Ivan Miljenovic</dc:creator>
				<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://ivanmiljenovic.wordpress.com/?p=186</guid>
		<description><![CDATA[During the past week, Conrad Parker announced on Google+ (though it wasn&#8217;t a public post so I can&#8217;t seem to link to it) that he had decided to take over maintainership (at least until someone else says they want to do it) of vacuum since Matt Morrow hasn&#8217;t been seen for a while. I decided [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=186&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>During the past week, <a href="https://plus.google.com/u/0/101555949501667191720">Conrad Parker</a> announced on Google+ (though it wasn&#8217;t a public post so I can&#8217;t seem to link to it) that he had decided to take over maintainership (at least until someone else says they want to do it) of <a href="http://hackage.haskell.org/package/vacuum">vacuum</a> since Matt Morrow hasn&#8217;t been seen for a while.</p>
<p>I decided to take the opportunity to replace the current explicit <code>String</code>-based (well, actually <code>Doc</code>-based) mangling used to create Dot graphs for use with <a href="http://graphviz.org">Graphviz</a> from vacuum with usage of my <a href="http://projects.haskell.org/graphviz/">graphviz</a> library.  I&#8217;ve just sent Conrad a pull request on his <a href="https://github.com/kfish/vacuum">GitHub</a> repo, and I decided that this would make a suitable &#8220;intro&#8221; tutorial on how to use <code>graphviz</code>.</p>
<p>First of all, have a look at the <a href="http://hackage.haskell.org/packages/archive/vacuum/1.0.0.1/doc/html/src/GHC-Vacuum-Pretty-Dot.html">current implementation</a> of the <code>GHC.Vacuum.Pretty.Dot</code> module.  If you read through it, it&#8217;s pretty straight-forward: convert a graph in an adjacency-list format into Dot code by mapping a transformation function over it, then attach the required header and footer.</p>
<p>Note though that this way, the layout/printing aspects are mixed in with the actual conversion part: rather than separating the creation of the Dot code from how it actually appears, it&#8217;s all done together.</p>
<p>There&#8217;s also a mistake in there that probably isn&#8217;t obvious: the &#8220;<code>arrowname=onormal</code>&#8221; part of the definition of <code>gStyle</code> is completely useless: there is no such <a href="http://www.graphviz.org/doc/info/attrs.html">attribute</a> as &#8220;arrowname&#8221;; what is probably meant there is &#8220;arrowhead&#8221; or &#8220;arrowtail&#8221;.</p>
<p>Let&#8217;s now consider the implementation using version <code>2999.12.*</code> of <code>graphviz</code> (the version is important because even whilst doing this I spotted some changes I&#8217;m likely to make in the next version for usability purposes):</p>
<pre class="brush: plain; title: ; notranslate">
{-# LANGUAGE OverloadedStrings #-}

module GHC.Vacuum.Pretty.Dot (
   graphToDot
  ,graphToDotParams
  ,vacuumParams
) where

import Data.GraphViz hiding (graphToDot)
import Data.GraphViz.Attributes.Complete( Attribute(RankDir, Splines, FontName)
                                        , RankDir(FromLeft), EdgeType(SplineEdges))

import Control.Arrow(second)

------------------------------------------------

graphToDot :: (Ord a) =&gt; [(a, [a])] -&gt; DotGraph a
graphToDot = graphToDotParams vacuumParams

graphToDotParams :: (Ord a, Ord cl) =&gt; GraphvizParams a () () cl l -&gt; [(a, [a])] -&gt; DotGraph a
graphToDotParams params nes = graphElemsToDot params ns es
  where
    ns = map (second $ const ()) nes

    es = concatMap mkEs nes
    mkEs (f,ts) = map (\t -&gt; (f,t,())) ts

------------------------------------------------

vacuumParams :: GraphvizParams a () () () ()
vacuumParams = defaultParams { globalAttributes = gStyle }

gStyle :: [GlobalAttributes]
gStyle = [ GraphAttrs [RankDir FromLeft, Splines SplineEdges, FontName &quot;courier&quot;]
         , NodeAttrs  [textLabel &quot;\\N&quot;, shape PlainText, fontColor Blue]
         , EdgeAttrs  [color Black, style dotted]
         ]
</pre>
<p>(The <code>OverloadedStrings</code> extension is needed for the <code>FontName</code> attribute.)</p>
<p>First of all, note that there is <strong>no</strong> mention or concept of the overall printing/structure of the Dot code: this is all done behind the scenes.  It&#8217;s also simpler this way to choose custom attributes: Don Stewart&#8217;s <a href="http://hackage.haskell.org/package/vacuum-cairo">vacuum-cairo</a> package ends up copying all of this and extra functions from vacuum just to have different attributes; here, you merely need to provide a custom <code>GraphvizParams</code> value!</p>
<p>So let&#8217;s have a look more at what&#8217;s being done here.  In <code>graphToDotParams</code>, the provided adjacency list representation <code>[(a,[a])]</code> is converted to explicit node and edge lists; the addition of <code>()</code> to each node/edge is because in many cases you would have some additional label attached to each node/edge, but for vacuum we don&#8217;t.  There is a <em>slight</em> possible error in this, in that there may be nodes present in an edge list but not specified directly (e.g. <code>[(1,[2])]</code> doesn&#8217;t specify the &#8220;2&#8243; node).  However, Graphviz doesn&#8217;t require explicit listing of every node if it&#8217;s also present in an edge, and we&#8217;re not specifying custom attributes for each node, so it doesn&#8217;t matter.  The actual grunt work of converting these node and edge lists is then done by <code>graphElemsToDot</code> in graphviz.</p>
<p>The type signature of <code>graphToDotParams</code> has been left loose enough so that if someone wants to specify clusters, it is possible to do so.  However, by default, <code>graphToDot</code> uses the specified <code>vacuumParams</code> which have no clusters, no specific attributes for each node or edge but <em>does</em> have top-level global attributes.  Rather than using <code>String</code>s, we have a list of <code>GlobalAttributes</code>, with one entry for each of top-level graph, node and edge attributes (the latter two applying to every node/edge respectively).  I&#8217;ve just converted over the attributes specified in the original (though dropping off the useless &#8220;arrowname&#8221; one).  Some of these attributes have more user-friendly wrappers that are re-exported by <code>Data.GraphViz</code>; the other three need to be explicitly imported from the complete list of attributes (for these cases I prefer to do explicit named imports rather than importing the entire module so I know which actual attributes I&#8217;m using).  I am adding more attributes to the &#8220;user-friendly&#8221; module all the time; <code>RankDir</code> will probably make it&#8217;s way over there for the next release, with a better name and documentation (and thus not requiring any more imports).</p>
<p>Now, you might be wondering how I&#8217;ve managed to avoid a <code>(a -&gt; String)</code> or similar function like the original implementation had.  That&#8217;s because the actual conversion uses the <a href="http://hackage.haskell.org/packages/archive/graphviz/2999.12.0.3/doc/html/Data-GraphViz-Printing.html#t:PrintDot">PrintDot</a> class (which is going to have a nicer export location in the next version of graphviz).  As such, as long as a type has an instance &#8211; and ones like <code>String</code>, <code>Int</code>, etc. all do &#8211; then it will be printed when the actual Dot code is created from the <code>DotGraph a</code> value.</p>
<p>So how to actually use this?  In the original source, there&#8217;s a commented out function to produce a <code>png</code> image file.  This is achieved by saving the Dot code to a file, then explicitly calling the <code>dot</code> command and saving the output as an image.  Here&#8217;s the version using <code>graphviz</code>:</p>
<pre class="brush: plain; title: ; notranslate">
{-# LANGUAGE ScopedTypeVariables #-}

import GHC.Vacuum.Pretty.Dot
import Data.GraphViz.Exception

graphToDotPng :: FilePath -&gt; [(String,[String])] -&gt; IO Bool
graphToDotPng fpre g = handle (\(e::GraphvizException) -&gt; return False)
                       $ addExtension (runGraphviz (graphToDot g)) Png fpre &gt;&gt; return True
</pre>
<p>(Note: The exception-handling stuff is just used to provide the same <code>IO Bool</code> result as the original.)</p>
<p>I hope you&#8217;ve seen how convenient graphviz can be rather than manually trying to produce Dot code and calling the Graphviz tools to visualise it.  There are still some cludgy spots in the API (e.g. I would be more tempted now to have the graph to visualise be the last parameter; at the time I was considering more about using different image outputs for the same graph), so I appreciate people telling me how the API can be improved (including which attributes are commonly used).</p>
<br />Filed under: <a href='http://ivanmiljenovic.wordpress.com/category/graphs/'>Graphs</a>, <a href='http://ivanmiljenovic.wordpress.com/category/haskell/'>Haskell</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ivanmiljenovic.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ivanmiljenovic.wordpress.com/186/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=186&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ivanmiljenovic.wordpress.com/2011/10/16/graphviz-in-vacuum/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/82401038e87257529066b9e6618d470e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ivanm</media:title>
		</media:content>
	</item>
		<item>
		<title>A crazy idea about graph visualisation</title>
		<link>http://ivanmiljenovic.wordpress.com/2011/01/25/a-crazy-idea-about-graph-visualisation/</link>
		<comments>http://ivanmiljenovic.wordpress.com/2011/01/25/a-crazy-idea-about-graph-visualisation/#comments</comments>
		<pubDate>Tue, 25 Jan 2011 03:23:05 +0000</pubDate>
		<dc:creator>Ivan Miljenovic</dc:creator>
				<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[linux.conf.au]]></category>

		<guid isPermaLink="false">http://ivanmiljenovic.wordpress.com/?p=179</guid>
		<description><![CDATA[I&#8217;m currently at linux.conf.au, and this morning I went to a talk by Adam Harvey entitled Visualising Scientific Data with HTML5. Now, one of the packages I maintain is graphviz which suffices at what it does: use Graphviz to visualise graphs using static images. Despite its various problems, I keep using Graphviz because &#8211; unlike [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=179&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I&#8217;m currently at <a href="http://linux.conf.au">linux.conf.au</a>, and this morning I went to a talk by Adam Harvey entitled <a href="http://conf.linux.org.au/wiki/Miniconfs/ResearchAndStudentInnovationMiniconf/VisualisingScientificDataWithHtml5">Visualising Scientific Data with HTML5</a>.</p>
<p>Now, one of the packages I maintain is <a href="http://projects.haskell.org/graphviz/">graphviz</a> which suffices at what it does: use <a href="http://graphviz.org/">Graphviz</a> to visualise graphs using static images.  Despite its various <a href="https://ivanmiljenovic.wordpress.com/wp-admin/post.php?post=70">problems</a>, I keep using Graphviz because &#8211; unlike most of the flashier graph visualisation programs that I&#8217;ve found &#8211; it doesn&#8217;t require a fancy GUI just to convert a pre-existing graph into an image (admittedly, others may have library versions, but most seem to be written in Java and Python, which do not seem as useful in terms of writing Haskell bindings).  However, one thing that Graphviz <i>cannot</i> do is let you <strong>dynamically</strong> visualise graphs, which is especially useful for extremely large graphs (e.g. <a href="http://code.haskell.org/~ivanm/Sample_SourceGraph/SourceGraph/graphs/code.svg">call graphs</a>).</p>
<p>One of the visualisation toolkits that Adam talked about was the <a href="http://thejit.org/">JavaScript InfoVis Toolkit</a>, which seemed quite nice in how you can dynamically interact with the graphs.  The graphs are represented using JSON, and the <a href="http://thejit.org/static/v20/Docs/files/Options/Options-Node-js.html">format</a> looks relatively straightforward.</p>
<p>So here&#8217;s my possibly crazy idea: does it make sense to create a companion library for graphviz to convert its <a href="http://hackage.haskell.org/packages/archive/graphviz/2999.11.0.0/doc/html/Data-GraphViz-Types.html#t:DotRepr">DotRepr</a> values into JIT-compatible JSON, possibly with some extensions to assist with the visualisation?  We already have various libraries for interacting with JavaScript and JSON on HackageDB, so it may be possible to abstract most of the pain of visualising and interacting with graphs on the web into our preferred language.  I&#8217;m not quite sure how to deal with incompatible/differing attribute values for Dot vs JIT&#8217;s JSON, but is this type of avenue worth considering?  Such a conversion library would save having to doubly-convert graphs (in case you want static image versions of the visualisations as well).</p>
<p>So, how crazy am I?</p>
<br />Filed under: <a href='http://ivanmiljenovic.wordpress.com/category/graphs/'>Graphs</a>, <a href='http://ivanmiljenovic.wordpress.com/category/haskell/'>Haskell</a>, <a href='http://ivanmiljenovic.wordpress.com/category/linux-conf-au/'>linux.conf.au</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ivanmiljenovic.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ivanmiljenovic.wordpress.com/179/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=179&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ivanmiljenovic.wordpress.com/2011/01/25/a-crazy-idea-about-graph-visualisation/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/82401038e87257529066b9e6618d470e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ivanm</media:title>
		</media:content>
	</item>
		<item>
		<title>LCA bid process opens &#8211; Canberra at the ready!</title>
		<link>http://ivanmiljenovic.wordpress.com/2011/01/24/lca-bid-process-opens-canberra-at-the-ready/</link>
		<comments>http://ivanmiljenovic.wordpress.com/2011/01/24/lca-bid-process-opens-canberra-at-the-ready/#comments</comments>
		<pubDate>Mon, 24 Jan 2011 00:37:18 +0000</pubDate>
		<dc:creator>Ivan Miljenovic</dc:creator>
				<category><![CDATA[linux.conf.au]]></category>

		<guid isPermaLink="false">http://ivanmiljenovic.wordpress.com/?p=173</guid>
		<description><![CDATA[Disclaimers: sorry, Haskellers: no Haskell or graph theory in this blog post. Instead this is about linux.conf.au (aka LCA). For the last several months, a small group of people in Canberra including myself have been preparing a bid for LCA 2013. This is not just to give us more time to make the conference the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=173&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><i>Disclaimers: sorry, Haskellers: no Haskell or graph theory in this blog post.  Instead this is about <a href="http://linux.conf.au">linux.conf.au</a> (aka LCA).</i></p>
<p>For the last several months, a small group of people in Canberra including myself have been preparing a bid for <a href="http://linux.conf.au">LCA</a> 2013. This is not just to give us more time to make the conference the most awesome, froody LCA you&#8217;ve ever been to. No &#8211; 2013 is also the centenary of the founding of Canberra as the nation&#8217;s capital. It&#8217;s a very significant year for us and we&#8217;d all be thrilled if we could show the attendees of LCA our great city and Canberrans the great work the FOSS community does to improve everyone&#8217;s lives.</p>
<p>So we&#8217;re really stoked that the bidding process is going to be opened early, and I think it&#8217;ll lead to a really interesting competition that will result, whoever wins, in the best LCA ever!</p>
<p>If you&#8217;re interested in getting involved, join the <a href="http://lists.clug.org.au/listinfo/canberra2013">mailing list</a>! </p>
<br />Filed under: <a href='http://ivanmiljenovic.wordpress.com/category/linux-conf-au/'>linux.conf.au</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ivanmiljenovic.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ivanmiljenovic.wordpress.com/173/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=173&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ivanmiljenovic.wordpress.com/2011/01/24/lca-bid-process-opens-canberra-at-the-ready/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/82401038e87257529066b9e6618d470e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ivanm</media:title>
		</media:content>
	</item>
		<item>
		<title>Graph labels redux and overall plan</title>
		<link>http://ivanmiljenovic.wordpress.com/2011/01/17/graph-labels-redux-and-overall-plan/</link>
		<comments>http://ivanmiljenovic.wordpress.com/2011/01/17/graph-labels-redux-and-overall-plan/#comments</comments>
		<pubDate>Mon, 17 Jan 2011 12:49:54 +0000</pubDate>
		<dc:creator>Ivan Miljenovic</dc:creator>
				<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://ivanmiljenovic.wordpress.com/?p=169</guid>
		<description><![CDATA[This is a continuation of my previous post on my thoughts and plans for writing generic graph classes. Overall Idea The overall thing I want to do with these generic graph classes is to be able to deal with the vast majority of graph-like data structures in as common a way as possible. Note that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=169&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><i>This is a continuation of my <a href="http://ivanmiljenovic.wordpress.com/2010/12/30/graphs-and-labels/">previous post</a> on my thoughts and plans for writing generic graph classes.</i></p>
<h3>Overall Idea</h3>
<p>The overall thing I want to do with these generic graph classes is to be able to deal with the vast majority of graph-like data structures in as common a way as possible.  Note that I say <i>graph-like</i>: I&#8217;m distinguishing here between data structures that match the <a href="http://en.wikipedia.org/wiki/Graph_%28mathematics%29">mathematic</a> definition of a graph (that is, a collection of distinguished objects, where pairs of these objects may be connected in some fashion) from what is usually considered as a graph <a href="http://en.wikipedia.org/wiki/Graph_%28data_structure%29">data structure</a>: the difference mainly arises in that we have notions of expected operations on graph data structures that may not be applicable on our graph-like data types.  These operations can either be ones that are forbidden (e.g. adding a node to a static type) or partially forbidden (e.g. adding a cycle to a tree).</p>
<p>As such, the classes as they currently stand are mainly <i>informational</i>: what can we determine from this graph-like type?  Do we know specific properties about it (e.g. is it an instance of the class that specifies whether or not the graph is meant to be directed)?  There will, of course, be classes for graph manipulation, but I see those as secondary components: for example, it doesn&#8217;t make sense to consider using standard graph manipulation functions to add or delete values from a <a href="http://hackage.haskell.org/packages/archive/Cabal/latest/doc/html/Distribution-Simple-PackageIndex.html#t:PackageIndex"><code>PackageIndex</code></a> as we can&#8217;t arbitrarily add values to it.</p>
<p>Such a collection of classes will by necessity be subject to compromise: it is not possible to have a fully-featured set of classes that comprehensively covers every single possible type of graph-like data structure whilst also being small and easy enough to use.  After all, there&#8217;s no point in writing such classes if no-one uses them because they&#8217;re too difficult!</p>
<h3>More on graph labels</h3>
<p>In my <a href="http://ivanmiljenovic.wordpress.com/2010/12/30/graphs-and-labels/">previous post</a>, I said that the best way of dealing with labels is similar to the way that FGL currently does: force all graph-like types to have both node and edge labels (but not require types to have kind <code>* -&gt; * -&gt; *</code> like FGL does).  A few people objected, notably Sjoerd Visscher said that labels should be optional for both nodes and edges, and ideally be part of the overall node and edge types.</p>
<p>In theory, this solution is great (and I actually worked for a while trying to get something like it to work).  However, as I stated in the comments, it fails one notable requirement: we now have to specialise functions on graphs to whether or not the graph has labels or not, and if so which ones.  Specifically, if the behaviour of a function may change depending upon whether or not labels are present, such a solution may require <i>four</i> implementations:</p>
<ol>
<li>No labels;</li>
<li>Node labels only;</li>
<li>Edge labels only;</li>
<li>Node <i>and</i> edge labels.</li>
</ol>
<p>Probably the best example I can think of for this is from my <a href="http://projects.haskell.org/graphviz/">graphviz</a> library: consider the <a href="http://hackage.haskell.org/packages/archive/graphviz/2999.11.0.0/doc/html/Data-GraphViz.html#v:preview"><code>preview</code></a> function as it is currently defined for FGL graphs:</p>
<pre class="brush: plain; title: ; notranslate">
preview   :: (Ord el, Graph gr, Labellable nl, Labellable el) =&gt; gr nl el -&gt; IO ()
preview g = ign $ forkIO (ign $ runGraphvizCanvas' dg Xlib)
  where
    dg = setDirectedness graphToDot params g
    params = nonClusteredParams { fmtNode = \ (_,l) -&gt; [toLabel l]
                                , fmtEdge = \ (_, _, l) -&gt; [toLabel l]
                                }
    ign = (&gt;&gt; return ())
</pre>
<p>This is a relatively simple function, that just sets some defaults for the main functions in graphviz.  To change this to my proposed layout of compulsory labels mainly requires changes to the type signature (the only implementation change would be the way edges are defined).  But with optional labels, then either four variants of this function will be required or else the user will have to specify how to distinguish the node/edge identifiers from the labels (if they exist); this latter solution is not satisfactory as the whole point of this function is to provide defaults to quickly visualise a graph, and as such should not take any other parameters apart from the graph itself.</p>
<p>If an &#8220;<code>isInstanceOf</code>&#8221; function was available (to determine whether or not the graph type is an instance of the appropriate label classes without needing to specify them as explicit type constraints), then this wouldn&#8217;t be a problem: implementers of functions would just need to take into account the four possible label groupings in their code.  But as it stands, the implementation of having optional labels breaks the simplicity requirement that I&#8217;m taking into account when writing these classes.</p>
<p>Note that I would actually <i>prefer</i> to have distinct/abstract node and edge types that optionally contain labels: for the <a href="http://code.haskell.org/~ivanm/planar-graph/">planar graph</a> library that I&#8217;m working on all operations on edges are done via unique identifiers rather than a data-type isomorphic to a tuple of node identifiers (so as to avoid problems with multiple edges).  However, for most graph types such explicit differentiation between edges won&#8217;t be required, and in general it will be simpler to both instantiate and use classes when a more simple edge type is used rather than requiring in effect a new data type for each graph (as required when using data families).</p>
<h3>Naming and terminology</h3>
<p>One thing I&#8217;m still not sure about: how shall I deal with the naming of functions when I have both labelled and unlabelled variants of them?  Should I take the FGL route of prepending &#8220;<code>lab</code>&#8221; to them (e.g. <code>nodes</code> vs <code>labNodes</code>)?  I&#8217;m not sure I like this solution, as I want to try and shift focus to making the <i>labelled</i> versions the defaults (or at least not as clumsy to use): does it make sense to adopt a policy of priming functions to distinguish between labelled and unlabelled (e.g. <code>nodes</code> vs <code>nodes'</code>)?  Or should some other naming policy be used?</p>
<br />Filed under: <a href='http://ivanmiljenovic.wordpress.com/category/graphs/'>Graphs</a>, <a href='http://ivanmiljenovic.wordpress.com/category/haskell/'>Haskell</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ivanmiljenovic.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ivanmiljenovic.wordpress.com/169/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=169&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ivanmiljenovic.wordpress.com/2011/01/17/graph-labels-redux-and-overall-plan/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/82401038e87257529066b9e6618d470e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ivanm</media:title>
		</media:content>
	</item>
		<item>
		<title>Graphs and Labels</title>
		<link>http://ivanmiljenovic.wordpress.com/2010/12/30/graphs-and-labels/</link>
		<comments>http://ivanmiljenovic.wordpress.com/2010/12/30/graphs-and-labels/#comments</comments>
		<pubDate>Thu, 30 Dec 2010 11:20:56 +0000</pubDate>
		<dc:creator>Ivan Miljenovic</dc:creator>
				<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://ivanmiljenovic.wordpress.com/?p=164</guid>
		<description><![CDATA[As some of you may be aware, I&#8217;ve been working on and off on a new library to define what graphs are in Haskell. This is the first part of a series on some of the thought processes involved in trying to define classes that fit the vast majority of graphs. One of the first [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=164&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><i>As some of you may be aware, I&#8217;ve been working on and off on a new library to define what <a href="http://en.wikipedia.org/wiki/Graph_%28data_structure%29">graphs</a> are in Haskell.  This is the first part of a series on some of the thought processes involved in trying to define classes that fit the vast majority of graphs.</i></p>
<p>One of the first things I&#8217;ve been considering how to deal with in the new graph classes that I&#8217;m working on is how to deal with node and edge labels in graphs.  My point of view is that graphs contain two separate but related types of information:</p>
<ol>
<li>The structure of the graph.</li>
<li>The information explaining what the structure means.</li>
</ol>
<p>As an example, consider <a href="http://en.wikipedia.org/wiki/Graph_colouring">graph colouring</a>: we have the actual structure of the graph and then the colours attached to individual vertices (or edges, depending how you&#8217;re doing the colouring).  Another example is a <a href="http://en.wikipedia.org/wiki/Flow_graph">flow graph</a>, where the distances/weights are not an actual &#8220;physical&#8221; part of the graph structure yet nevertheless form an important part of the overall graph.</p>
<p>Yet there are times when the extra labelling/information is an inherent part of the structure: either we are concerning ourselves solely with some graph structural problem (e.g. <a href="http://en.wikipedia.org/wiki/Connected_component_%28graph_theory%29">connected components</a>) or &#8211; more commonly when programming &#8211; the information about the structure is embedded <i>within</i> the structure (for example, Cabal&#8217;s <a href="http://hackage.haskell.org/packages/archive/Cabal/latest/doc/html/Distribution-Simple-PackageIndex.html#t:PackageIndex"><code>PackageIndex</code></a> type: this is simplistically equivalent to an unlabelled graph with <code>PackageIndexID</code> as the node type).</p>
<p>As such, I&#8217;ve come up with at least three different ways of dealing with graph labels:</p>
<ol>
<li>A graph can choose whether or not it has node or edge labels (if I understand correctly, this is the approach taken by the <a href="http://www.boost.org/doc/libs/1_45_0/libs/graph/doc/index.html">Boost Graph Library</a> for C++).</li>
<li>A graph either has no labels or it has both node and edge labels.</li>
<li>All graphs <i>must</i> have both node and edge labels (even if they&#8217;re just implicit labels of type <code>()</code>).
</li>
</ol>
<p>Something along the lines of the first two options is very tempting: there is no requirement to force graphs that don&#8217;t have or need labels to pretend to have them just to fit the constraints of some class.  Furthermore, different graph types can thus be more specific in terms of which graph classes they are instances of.</p>
<p>However, there is a problem here: <strong>duplication</strong>.  Let us consider a simplified set of graph classes that fit the second criteria:</p>
<pre class="brush: plain; title: ; notranslate">
class Graph g where
  type Node g

  nodes :: g -&gt; [Node g]

  edges :: g -&gt; [Edge g]

type Edge g = (Node g, Node g)

class (Graph g) =&gt; LabelledGraph g where
  type NLabel g

  type ELabel g

  labNodes :: g -&gt; [(Node g, NLabel g)]

  labEdges :: g -&gt; [(Edge g, ELabel g)]
</pre>
<p>So if some graph type wants to be an instance of <code>LabelledGraph</code>, it must specify <i>two</i> ways of getting all of the nodes available (admittedly, it will probably have something along the lines of <code>nodes = map fst labNodes</code>, but wouldn&#8217;t it be nice if this could be done <i>automatically</i>?).</p>
<p>But OK, writing a set of classes and then instances for those classes is a one-off cost.  Let&#8217;s say we accept that cost: the problems don&#8217;t stop there.  First of all, consider something as simple as adding a node to the graph.  There is no way (in general) that the two classifications (labelled and unlabelled) can share in the slightest a method to add a node, etc.  Furthermore, this segregation would spread to other aspects of using a graph: almost all algorithms/functions on graphs would thus need to be duplicated (if possible).  Since one of the main criteria I have for designing this library is that it should be possible to use <a href="http://projects.haskell.org/graphviz/">graphviz</a> to visualise the <code>PackageIndex</code> type, this kind of split is not something I think would be beneficial.</p>
<p>As such, the only real viable choice is to enforce usage of labels for all graphs.  This might be to the detriment of graphs without labels, but I&#8217;m planning on adding various functions that let you ignore labels (e.g. a variant of <code>addNode</code> that uses <code>mempty</code> for the graph label, which means it&#8217;s usable by graphs that have <code>()</code> as the label type).  The distinction between <code>nodes</code> and <code>labNodes</code> above could also be made automatic, with only the latter being a class method and the former being a top-level function.</p>
<p>This solution isn&#8217;t perfect: to ensure it works for all suitable graph types, it has to be kind <code>*</code>.  But this means that no <code>Functor</code>-like mapping ability will be available, at least without really ugly type signatures (which the current experimental definition uses) at least until <a href="http://hackage.haskell.org/trac/ghc/ticket/2715">superclass constraints</a> become available (or possibly some kind of kind polymorphism, no pun intended).  However, this is still the best available solution that I can come up with at this stage.</p>
<br />Filed under: <a href='http://ivanmiljenovic.wordpress.com/category/graphs/'>Graphs</a>, <a href='http://ivanmiljenovic.wordpress.com/category/haskell/'>Haskell</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ivanmiljenovic.wordpress.com/164/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ivanmiljenovic.wordpress.com/164/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=164&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ivanmiljenovic.wordpress.com/2010/12/30/graphs-and-labels/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/82401038e87257529066b9e6618d470e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ivanm</media:title>
		</media:content>
	</item>
		<item>
		<title>Test dependencies in Cabal</title>
		<link>http://ivanmiljenovic.wordpress.com/2010/09/03/test-dependencies-in-cabal/</link>
		<comments>http://ivanmiljenovic.wordpress.com/2010/09/03/test-dependencies-in-cabal/#comments</comments>
		<pubDate>Fri, 03 Sep 2010 09:51:55 +0000</pubDate>
		<dc:creator>Ivan Miljenovic</dc:creator>
				<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://ivanmiljenovic.wordpress.com/?p=159</guid>
		<description><![CDATA[I&#8217;ve previously written about my annoyance with Hackage packages that have compulsory testing dependencies (note that I&#8217;ve since modified my position from that post, as noted by the presence of optional testing modules for graphviz). However, the situation is definitely getting better: even my old bugbear hmatrix has made the testing dependencies and modules optional [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=159&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve <a href="http://ivanmiljenovic.wordpress.com/2009/11/17/">previously written</a> about my annoyance with Hackage packages that have compulsory testing dependencies (note that I&#8217;ve since modified my position from that post, as noted by the presence of optional testing modules for <a href="http://hackage.haskell.org/package/graphviz">graphviz</a>).  However, the situation is definitely getting better: even my old bugbear <a href="http://hackage.haskell.org/package/hmatrix">hmatrix</a> has made the testing dependencies and modules optional by using a Cabal flag of <code>tests</code>.</p>
<p>However, several package maintainers seem to be unaware of a minor subtlety of how Cabal parses dependencies.</p>
<p>Let us consider a simple example: we have a package <code>foo</code> which is primarily a library but also contains a testing executable which uses <a href="http://hackage.haskell.org/package/QuickCheck">QuickCheck</a>.  The relevant parts of the <code>.cabal</code> file look something like this:</p>
<pre class="brush: plain; title: ; notranslate">
...
Flag test
     Description: Build the test suite, including an executable to run it.
     Default: False

Library
    Build-Depends: base == 4.*, containers == 0.3.*
    Exposed-Modules: Data.Foo

Executable foo-tester
    if flag(test)
        Buildable: True
    else
        Buildable: False

    Main-Is: FooTester.hs

    Build-Depends: QuickCheck &gt;= 2.1 &amp;&amp; &lt; 2.1.2
</pre>
<p>So, we have an optional testing executable called <code>foo-tester</code> and bonus points for defaulting the testing of this executable to <code>false</code>.</p>
<p>However, this doesn&#8217;t quite behave as expected: if we try to build it as-is without enabling the <code>test</code> flag, then Cabal will <i>still</i> make <code>foo</code> depend upon <code>QuickCheck</code>.  Why?  Because the dependency is not optional (I&#8217;m not saying that this behaviour is correct, just that this is how Cabal acts).  This became noticeable when <a href="http://hackage.haskell.org/package/QuickCheck-2.2">QuickCheck-2.2</a> came out, I upgraded to it and then <code>ghc-pkg check</code> complained that some packages were now broken.</p>
<p>I&#8217;ve pointed out the correct way of doing this to individual maintainers in the past when I noticed it in their packages; now I&#8217;m doing it in this blog post in the hope that maintainers of all affected packages will remedy this.  To ensure that testing dependencies are only considered when we are indeed building the testing executable, just shift it inside the if-statement:</p>
<pre class="brush: plain; title: ; notranslate">
...
Executable foo-tester
    if flag(test)
        Buildable: True
        Build-Depends: QuickCheck &gt;= 2.1 &amp;&amp; &lt; 2.1.2
    else
        Buildable: False

    Main-Is: FooTester.hs
</pre>
<p>Now <code>QuickCheck</code> will only be brought in when you&#8217;re building tests.</p>
<p>This doesn&#8217;t also apply to testing executables, but to any conditional dependencies.  See for example how I have testing modules built and exported in <a href="http://hackage.haskell.org/packages/archive/graphviz/2999.10.0.1/graphviz.cabal">graphviz&#8217;s <code>.cabal</code> file</a>.</p>
<br />Filed under: <a href='http://ivanmiljenovic.wordpress.com/category/haskell/'>Haskell</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ivanmiljenovic.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ivanmiljenovic.wordpress.com/159/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=159&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ivanmiljenovic.wordpress.com/2010/09/03/test-dependencies-in-cabal/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/82401038e87257529066b9e6618d470e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ivanm</media:title>
		</media:content>
	</item>
		<item>
		<title>Results of FGL naming survey</title>
		<link>http://ivanmiljenovic.wordpress.com/2010/07/25/results-of-fgl-naming-survey/</link>
		<comments>http://ivanmiljenovic.wordpress.com/2010/07/25/results-of-fgl-naming-survey/#comments</comments>
		<pubDate>Sat, 24 Jul 2010 14:26:33 +0000</pubDate>
		<dc:creator>Ivan Miljenovic</dc:creator>
				<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://ivanmiljenovic.wordpress.com/?p=155</guid>
		<description><![CDATA[Eleven days ago I set up a survey to help determine what the community thought the new version of FGL that Thomas Bereknyei and I are working on should be called. This post is about the results from this survey. About the survey People that took the survey were asked four things: What name did [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=155&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Eleven days ago <a href="https://ivanmiljenovic.wordpress.com/2010/07/14/data-oriented-hierarchies/">I set up a survey</a> to help determine what the community thought the new version of <a href="http://hackage.haskell.org/package/fgl">FGL</a> that Thomas Bereknyei and I are working on should be called.  This post is about the results from this survey.</p>
<h3>About the survey</h3>
<p>People that took the survey were asked four things:</p>
<ul>
<li>What name did they prefer: &#8220;<code>fgl</code>&#8221; or &#8220;<code>inductive-graphs</code>&#8220;;</li>
<li>Did they actually do any graph-related programming (not necessarily using FGL);</li>
<li>Any other comments they might have had;</li>
<li>Optionally, their name and email address.</li>
<li>
</li>
</ul>
<h3>Response to comments</h3>
<p>Several people had some questions/comments regarding the survey both in the survey itself and on the <a href="http://www.reddit.com/r/haskell/comments/cp50y/should_the_new_graph_library_be_called_fgl_or/">Haskell Reddit</a>.  Here are some responses:</p>
<ul>
<li><strong>Why is there only the option of &#8220;fgl&#8221; and &#8220;inductive-graphs&#8221;?</strong>
<p>Because we couldn&#8217;t think of any better names.  The former is what the library is already called, the latter describes exactly what the library is about (implementing and using graphs in an inductive fashion).  Any other names such as &#8220;<code>boxes-and-arrows</code>&#8221; are, we feel, rather silly and don&#8217;t make sense.  We did ask, but didn&#8217;t hear any other names that were relevant.</li>
<li><strong>Why should you even consider using the name &#8220;fgl&#8221; if this is a new library?</strong>
<p>I don&#8217;t want to go through the whole thing all over again, but I&#8217;ll summarise.  This isn&#8217;t a completely new library; it&#8217;s just a new <i>implementation</i> (e.g. same as going from QuickCheck-1 to QuickCheck-2; the point of the library is the same, the concepts are the same, the implementation is different and the APIs are incompatible).  As for the API incompatibility, that&#8217;s what <a href="http://www.haskell.org/haskellwiki/Package_versioning_policy">version numbers</a> are for.</li>
<li><strong>FGL is a silly name anyway/Acronyms are bad in a package name/The word &#8220;graph&#8221; should appear in the package name/etc.</strong>
<p>Agreed.  However, the package name &#8220;fgl&#8221; already exists, and I don&#8217;t believe in gratuitous proliferation of package names on Hackage as its hard enough to navigate as it is.  Most people in the Haskell community already know that &#8220;fgl&#8221; is a graph library, etc.  Also see the response to the previous question.</li>
<li><strong>You&#8217;re the maintainers; why are you bothering to even ask what the name should be?</strong>
<p>Because when we announced our plans, there was a number of vocal people that complained about our &#8220;usurpation&#8221; (my word, not theirs) of the FGL name for our own library.</li>
<li><strong>Why are you planning on using the same module namespace as FGL even if you change the package name?  Won&#8217;t that cause problems ala <a href="http://hackage.haskell.org/package/mtl">mtl</a> and <a href="http://hackage.haskell.org/package/monads-fd">monads-fd</a>?</strong>
<p>Say what you like about the name of the package (I for one agree that it isn&#8217;t an ideal name, especially in the world of &#8220;modern&#8221; Haskell with Hackage, etc.), I think the module namespace is exactly right.  And unless we decide to skip the &#8220;<code>Data</code>&#8221; prefix and just have a stand-alone <code>Graph.*</code> namespace, there isn&#8217;t a better namespace available for a package that defines and uses graphs in an inductive fashion.  Again, this is a case of &#8220;You don&#8217;t like it?  Fine: pick a better name and if it truly is better we&#8217;ll use it.&#8221;.</li>
<li><strong>If you have to change the API, please provide a compatibility API like Parsec-3 has for Parsec-2.</strong>
<p>This isn&#8217;t going to happen for several reasons (and these are just the ones I could think of whilst writing this blog post):</p>
<ul>
<li>Even with the compatibility API, Parsec-3 was slow to be taken up.  Admittedly, this was due to a performance regression, but it still doesn&#8217;t bode well for how well compatibility APIs fare.</li>
<li>Parsec-3 could have a compatibility API because they defined a new module namespace for the new API; we don&#8217;t plan or want to do that.</li>
<li>If we have a compatibility API now, we&#8217;ll be forced to keep using and maintaining it when we&#8217;d much prefer people to use the nice new shinier API instead.</li>
<li>We plan on providing upgrade paths, such as versions of fgl in the <code>5.x</code> series that get closer and closer to the new API and various migration guides/tutorials.</li>
<li>Most of the function and class names are going to be pretty similar specifically to make porting easier (because of this I&#8217;m even planning on using FGL-like terminology for my currently-still-vapourware generic graph library that will eventually provide super-classes for FGL, rather than the more correct graph-theory terminology; e.g. <code>Vertex</code> rather than <a href="http://hackage.haskell.org/packages/archive/fgl/5.4.2.3/doc/html/Data-Graph-Inductive-Graph.html#t%3ANode"><code>Node</code></a>).</li>
</ul>
<p>We might have <i>some</i> compatibility APIs to help with the transition process (e.g. the <code>noNodes</code> function is going to be replaced with <code>order</code>, which is the proper terminology, but we might define <code>noNodes</code> as an alias), but these will probably be in a different module and it will still not be possible to have code that will work with both the <code>5.x</code> series of FGL and the new library.</li>
</ul>
<h3>Survey results</h3>
<p>Here is the initial overall results from the survey:</p>
<ul>
<li>66 people responded (Google Spreadsheets keeps lying to me and claiming 67, but it seems to be counting the header row as an actual response&#8230;).</li>
<li>27 (&asymp; 40.9%) people said they preferred &#8220;FGL&#8221;; the other 39 (&asymp;59.1%) prefer &#8220;inductive-graphs&#8221;.</li>
<li>40 (&asymp; 60.6%) of the respondees said they wrote code dealing with graphs.</li>
<li>There were 26 (&asymp; 39.4%) extra comments.</li>
<li>Only 23 (&asymp; 34.8%) of respondees were brave enough to add their name to the response (and one of these was only a single name without an email address).</li>
</ul>
<p>If we only consider the 40 people who claimed to write code dealing with graphs, only 16 (&asymp; 40%) of them preferred FGL; as such, actual usage of fgl or other graph libraries does not seem to change the overall opinion of the community (if my vague recollection of how to do statistics is correct, and this is indeed a representative sample of the community).</p>
<h4>Other interesting tidbits</h4>
<ul>
<li><a href="http://web.engr.oregonstate.edu/~erwig/">Martin Erwig</a> (i.e. he-who-wrote-the-original-version-of-FGL) says we should keep using the name &#8220;FGL&#8221;, laying to rest potential problems that some people have raised.</li>
<li>Two people didn&#8217;t seem to get the point of the survey: one person indicated that they didn&#8217;t care, another made an unrelated comment regarding immature equines.  However, they partially cancelled each other out: the former claimed to write graph code and voted for fgl, the latter said they didn&#8217;t write any graph code and voted for inductive-graphs.</li>
</ul>
<h4>In the raw</h4>
<p>For those that want it, a sanitised (in that the email addresses and names have been removed) copy of the results is <a href="http://code.haskell.org/~ivanm/Sanitised%20FGL%20Naming%20Survey%20Results.csv">available</a> (I would have hosted them on wordpress.com with the blog, but it doesn&#8217;t allow text files to be uploaded, and I don&#8217;t see the point of creating a full blown word processor document &#8211; since spreadsheets can&#8217;t be uploaded &#8211; just for some CSV data).</p>
<h3>And so the decision is?</h3>
<p>Well&#8230;. there isn&#8217;t one.  A 60% preference is too close to even for me to categorically say that the Haskell community prefers one name over another.  As such, unless someone presents a really good reason otherwise we&#8217;re going to stick with FGL (due to inertia if nothing else).</p>
<h4>My take on all this</h4>
<p>After all this debate, I&#8217;d like to point out that I&#8217;m more and more agreeing that &#8220;inductive-graphs&#8221; would make a much better library name.  However, as I&#8217;ve stated previously (including above), I would prefer to use the &#8220;fgl&#8221; name <i>somehow</i> if nothing else because it&#8217;s already there (so a few years from now when &#8211; hopefully &#8211; the new graph libraries are available and widely used, we don&#8217;t have a useless library sitting around confusing people, especially when it used to be present in GHC&#8217;s extralibs and the Haskell Platform).</p>
<h4>Yet Another Compromise Proposal (or two)</h4>
<p>However, I just thought of two possible solutions which may be satisfactory to all involved:</p>
<p>What about if we call the library we&#8217;re working on &#8220;inductive-graphs&#8221;, but then create a meta-library called &#8220;FGL&#8221; that isn&#8217;t just limited to inductive graphs?  That is, once I&#8217;ve worked out my generic graph API library, then we take a large subset of the modules defined in the libraries contained within <a href="http://ivanmiljenovic.files.wordpress.com/2010/07/intendedgraphhierarchy.png?w=769&amp;h=617">this figure</a> and re-export them from the FGL library.  Such a library would be analogous to how the Haskell Platform is an initial starting point of the libraries available on Hackage: an all-in-one subset of the available graph libraries in one overall API if you don&#8217;t know which libraries to use specifically, and you can then pare down your dependencies to what you actually use.</p>
<p>Another alternative (which I find less attractive) is that we make the FGL library contain the generic graph API; this way the library still exists, but then it is completely different from the <code>5.x</code> series.  I&#8217;m mainly suggesting this just to provide another alternative; I don&#8217;t think it really makes sense or is viable.</p>
<br />Filed under: <a href='http://ivanmiljenovic.wordpress.com/category/graphs/'>Graphs</a>, <a href='http://ivanmiljenovic.wordpress.com/category/haskell/'>Haskell</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ivanmiljenovic.wordpress.com/155/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ivanmiljenovic.wordpress.com/155/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=155&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ivanmiljenovic.wordpress.com/2010/07/25/results-of-fgl-naming-survey/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/82401038e87257529066b9e6618d470e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ivanm</media:title>
		</media:content>
	</item>
		<item>
		<title>Working out the container-classes API</title>
		<link>http://ivanmiljenovic.wordpress.com/2010/07/21/working-out-the-container-classes-api/</link>
		<comments>http://ivanmiljenovic.wordpress.com/2010/07/21/working-out-the-container-classes-api/#comments</comments>
		<pubDate>Wed, 21 Jul 2010 12:34:15 +0000</pubDate>
		<dc:creator>Ivan Miljenovic</dc:creator>
				<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://ivanmiljenovic.wordpress.com/?p=152</guid>
		<description><![CDATA[During AusHac, I worked on the container hierarchy I discussed in my previous post, which culminated in the initial release of container-classes. I had initially (and naively) thought I would have been able to whip something like this together on the Friday afternoon and spend the rest of the weekend working on graph libraries; in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=152&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>During <a href="http://www.haskell.org/haskellwiki/AusHac2010">AusHac</a>, I worked on the container hierarchy I discussed in my <a href="http://ivanmiljenovic.wordpress.com/2010/07/14/data-oriented-hierarchies/">previous post</a>, which culminated in the initial release of <a href="http://hackage.haskell.org/package/container-classes">container-classes</a>.  I had initially (and naively) thought I would have been able to whip something like this together on the Friday afternoon and spend the rest of the weekend working on graph libraries; in the end I just managed to release an initial draft version before we had to pack up on Sunday.</p>
<p>Now, I&#8217;m not saying this current setup is perfect; it&#8217;s basically a direct copy of all list-oriented functions from the <code>Prelude</code> along with a couple of functions from <code>Data.List</code> split into a generic <code>Container</code> class, a <code>Sequence</code> class for containers with a linear structure and <code>Stream</code> for infinite <code>Sequence</code>s (i.e. lists and similar structures: those for which it makes sense to define a function like <a href="http://haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/Prelude.html#v:repeat">repeat</a>).</p>
<p>First of all, here are a couple of design decisions I made with this library:</p>
<ul>
<li>I want to be able to consider types with kind <code>*</code>; as such, most pre-existing classes are of no use.</li>
<li>Even when hacking together support for types of kind <code>* -&gt; *</code> for mapping functions, etc. I couldn&#8217;t use <code>Functor</code> as it doesn&#8217;t let you constrain the type of the values being stored (for Sets, etc.).</li>
<li>To be able to have restrictions, we need to be able to specify the value type as part of the class definition.  This means the usage of either MPTCs+fundeps or an Associated Type.  I was initially using the latter, but due to the current lack of superclass constraints making the type signatures much uglier and longer, I switched to using MPTCs+fundeps instead.</li>
<li>Type signatures should be as short/nice as possible.</li>
<li>Provide as many default implementations as possible, and make those as efficient as possible.</li>
</ul>
<p>However, with these design decisions there are some considerations I have to make:</p>
<ul>
<li>How should I split up the various functions into type-classes?  e.g. does it make sense to re-define standard classes like <code>Foldable</code> so that they&#8217;ll work with values of kind <code>*</code> (where possible) and if necessary have a constrained value type?</li>
<li>At the moment, the main constraints are all inherited from the <code>Container</code> class; if I have lots of smaller classes, is there a nicer way of abstracting out the constraint without duplicating it everywhere?  <a href="http://hackage.haskell.org/package/rmonad">rmonad</a> has the <a href="http://hackage.haskell.org/packages/archive/rmonad/0.5/doc/html/Control-RMonad.html#t%3ASuitable">Suitable</a>, but in practice this seems to mean the addition of extra <code>Suitable f a</code> constraints on every function in addition; maybe this is because <code>Suitable</code> isn&#8217;t a superclass of the other classes though.</li>
<li>I&#8217;ve tried to define the default definitions of the various class methods with the eventual goal of implementing and using the <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.51.646">foldr/build rule</a>, but I&#8217;m not sure how to properly implement such a rule, let alone how well it&#8217;s going to work in practice:
<ul>
<li>If someone overrides the defaults to use custom/optimised versions (e.g. all the pre-defined list functions), then the inter-datatype optimisations will no longer be present.</li>
<li>As people may use more optimised variants of various class methods, any data type that extends another (using a newtype, etc.) will have to explicitly define each class instance rather than relying on the default definitions (if they want to keep using the optimised variants).</li>
<li>Cross-container optimisation could change some fundamental assumptions: e.g. going from a list to a <code>Seq</code> and then back to a list will typically preserve the value ordering; however if we replace the <code>Seq</code> with a <code>Set</code> then we&#8217;d expect the ordering in the final list to have changed (and be sorted); if I implement the foldr/build rule would it interfere with this ordering by removing the intermediate <code>Set</code> and the fact that it will insert values in sorted order?</li>
</ul>
</li>
<li>Benchmarking: is there a nice way of doing per-class benchmarking to be able to compare the performance of different data structures?  For example, being able to compare how long it takes to insert 100 random values into a set (by consing) compared to inserting those same values into a <code>Set</code>.</li>
</ul>
<p>So, that seems to be the battle I&#8217;ve taken upon myself.  I&#8217;d greatly appreciate any pointers people can give me either as comments here or by emailing me.</p>
<p>Oh, and a reminder: I&#8217;m going to stop collecting responses for my survey on <a href="https://spreadsheets.google.com/viewform?formkey=dGpzMmFnUWY3Uktodk5wdHlLQk5kT1E6MA">what to call the &#8220;new FGL&#8221; library</a> at about 12 PM UTC this Friday.  I&#8217;ve already got about 60 votes; more are welcome.</p>
<br />Filed under: <a href='http://ivanmiljenovic.wordpress.com/category/haskell/'>Haskell</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ivanmiljenovic.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ivanmiljenovic.wordpress.com/152/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=152&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ivanmiljenovic.wordpress.com/2010/07/21/working-out-the-container-classes-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/82401038e87257529066b9e6618d470e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ivanm</media:title>
		</media:content>
	</item>
		<item>
		<title>Data-Oriented Hierarchies</title>
		<link>http://ivanmiljenovic.wordpress.com/2010/07/14/data-oriented-hierarchies/</link>
		<comments>http://ivanmiljenovic.wordpress.com/2010/07/14/data-oriented-hierarchies/#comments</comments>
		<pubDate>Tue, 13 Jul 2010 14:24:27 +0000</pubDate>
		<dc:creator>Ivan Miljenovic</dc:creator>
				<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://ivanmiljenovic.wordpress.com/?p=142</guid>
		<description><![CDATA[In the Haskell community, there are several topics of discussion that keep coming up over and over again in terms of dealing with the hierarchies in our code. Some of these topics are: Fixing the Functor ⇒ Applicative ⇒ Monad class hierarchy (however you want to structure it); The best way to define and use [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=142&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In the Haskell community, there are several topics of discussion that keep coming up over and over again in terms of dealing with the hierarchies in our code.  Some of these topics are:</p>
<ul>
<li>Fixing the <code>Functor</code> ⇒ <code>Applicative</code> ⇒ <code>Monad</code> class hierarchy (however you want to structure it);</li>
<li>The best way to define and use monad transformers;</li>
<li>Making <code>Functor</code> more relevant; taken to the extreme by the &#8220;Caleskell&#8221; definitions used by <a href="http://haskell.org/haskellwiki/Lambdabot">lambdabot</a> on <a href="http://haskell.org/haskellwiki/IRC_channel">IRC</a>, where it seems almost everything can be expressed in terms of <code>fmap</code>.</li>
</ul>
<p>Now, I think this kind of discussion is an indication of good health in the Haskell community where we are doing our best to determine what the optimal solution to these problems are (rather than just giving up or being dictated to by a single individual).  However, something I&#8217;ve come to realise recently is that in my understanding these discussions are mainly oriented at what the best way to abstract how we <em>write code</em> rather than how we use the data structures that make up the code.  Hence, the topic of this blog post.</p>
<h3>My Goal</h3>
<p>What I want to discuss here is the concept of how we can best define class hierarchies that let us easily interchange our data structures.  The purpose of this is that currently, if I write some code using a list as my underlying data structure and then decide that a <a href="http://www.haskell.org/ghc/docs/6.12.2/html/libraries/containers-0.3.0.0/Data-Sequence.html">Sequence</a> would be a better fit because I do a lot of appends, I have to re-write every single bit of my code that knows about that particular data structure.  However, I would much prefer to just have to change a few top-level type signatures and maybe some list-specific items in my code and then the magic of type classes would take care of the rest.</p>
<h4>Avoiding Duplication</h4>
<p>The main focus of when such a hierarchy would be useful is when writing libraries: duplication is avoided by having to write a list-specific, a Sequence-specific and a Set-specific version of a function (e.g. to test if the data structure in question has at least two of the provided values).  More than that: often times we are constrained in terms of how we use libraries by what data-type the library author preferred at the time of writing.  A library function may require and then return a list, whereas we&#8217;re using Sets everywhere else.  If there is no pressing reason to use a list rather than a Set, then why should it?</p>
<h4>Is such a hierarchy already available?</h4>
<p>There are some previous attempts at something like this, including (but not limited to):</p>
<ul>
<li> <a href="http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Data-Functor.html">Functor</a> + <a href="http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Data-Foldable.html">Foldable</a> + <a href="http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Data-Traversable.html">Traversable</a>; this approach can&#8217;t deal with structures such as <a href="http://www.haskell.org/ghc/docs/6.12.2/html/libraries/containers-0.3.0.0/Data-Set.html">Sets</a> as they require an extra restriction on the parametric type.</li>
<li><a href="http://hackage.haskell.org/package/EdisonAPI-1.2.1">Edison</a> can cope with <code>Set</code>, etc. and has a nice hierarchy <em>between</em> the individual sub-classes (if anything it has too many sub-classes), but is <a href="http://bifunctor.homelinux.net/~roel/cgi-bin/hackage-scripts/revdeps/EdisonAPI-1.2.1#direct">used by very few packages</a> and has what I consider to be a few warts, such as explicitly re-exporting the data types in question in new modules, and some methods (such as <code>strict</code>) that really <a href="http://hackage.haskell.org/package/deepseq">belong elsewhere</a>.</li>
<li><a href="http://hackage.haskell.org/package/collections">collections</a> seemed to have been another attempt at this, but never seemed to have built on any version of GHC since 6.8.</li>
<li>When you only want to consider structures with a linear structure, <a href="http://hackage.haskell.org/package/ListLike">ListLike</a> is available.  However, it seems to be possibly over-busy.</li>
<li>Even more specialised than ListLike is <a href="http://haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/Data-String.html#v:IsString">IsString</a>, the point of which is to be able to use string literals in Haskell code to define Bytestrings, etc.</li>
</ul>
<p>The closest viable class/library to my ideal listed above would be a cross between <code>Edison</code> and <code>ListLike</code>; the former has an actual class hierarchy (to avoid duplication, etc.;) whereas the latter seems to be used more in actual practice.</p>
<p>My point here about a class hierarchy is this: in most aspects, any sequence (or &#8220;ListLike&#8221; data structure) can be considered a really inefficient generic collection/set: you still want to have a function to test for membership, you want to be able to add values, to know how many there are, etc.  As such, definitions should be as high up in the hierarchy as possible to let functions that use them be as generic as possible in terms of their type signatures.</p>
<h4>The Joker in the deck</h4>
<p>There is one conflicting issue in any such hierarchy: mapping.</p>
<p>Ideally, we wouldn&#8217;t want to require that instances of these types have kind <code>* -&gt; *</code> (so that we can for instance [pun not intended] make <code>Bytestring</code> an instance of these classes with a &#8220;value type&#8221; of <code>Word8</code>).  However, as soon as we do that we can no longer specify a <code>map</code> function nicely.</p>
<p>ListLike gets around this by defining a <a href="http://hackage.haskell.org/packages/archive/ListLike/1.0.1/doc/html/Data-ListLike.html#v%3Amap">map</a> function that doesn&#8217;t constrain the data structure type.  This means that it&#8217;s possible to write <code>map succ</code> with a type of <code>ByteString -&gt; [Word8]</code>.  Whilst this might be handy at times, it also provides possible type-matching problems if your overall definition when using them doesn&#8217;t force them to be the same (e.g.: <code>print $ map (*2) [1,2,3,4]</code>), and that in essence this definition of <code>map</code> does a complete fold over the data structure, whereas there may be more efficient versions if we can somehow specify at the type level that it must be constrained to the same data structure.</p>
<p>However, the problem is that technically <code>[Int]</code> and <code>[Char]</code> are two completely separate data types; as such, any map between them will require going from one type to another (since we&#8217;re not assuming kind <code>* -&gt; *</code> here).  It is possible to get around this, but it&#8217;s pretty ugly:</p>
<pre class="brush: plain; title: ; notranslate">
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}

class Collection c a | c -&gt; a where
  cons :: a -&gt; c -&gt; c

class (Collection (c a) a) =&gt; MappableCollection c a where
  cmap :: (MappableCollection c b) =&gt; (a -&gt; b) -&gt; c a -&gt; c b

instance Collection [a] a where
  cons = (:)

instance MappableCollection [] a where
  cmap = map
</pre>
<p>In essence, the whole point of the <code>MappableCollection</code> class is to force the <code>Collection</code> instance back into having to kind <code>* -&gt; *</code>.  It might be better just having <code>Collection</code> use ListLike&#8217;s <a href="http://hackage.haskell.org/packages/archive/ListLike/1.0.1/doc/html/Data-ListLike.html#v%3ArigidMap">rigidMap</a> and then leave &#8220;normal&#8221; mapping up to Functor or <a href="http://hackage.haskell.org/packages/archive/rmonad/0.5/doc/html/Control-RMonad.html#t%3ARFunctor">RFunctor</a> (which works better with the whole &#8220;class hierarchy&#8221; concept).  It&#8217;s just a shame that there&#8217;s no way of having mapping work regardless of the kind of the data type.</p>
<h4>So, what are you going to do about this?</h4>
<p>I&#8217;m going to make a stab at yet-another-collection-class-hierarchy this weekend at <a href="http://www.haskell.org/haskellwiki/AusHac2010">AusHac</a>.  I&#8217;m not sure how far we&#8217;ll get, but I&#8217;ll see.</p>
<h3>Graph Hierarchies</h3>
<p>My interest in data structure hierarchies came out <a href="http://www.haskell.org/pipermail/haskell-cafe/2009-June/063402.html">my frustration at the lack of a common reference point for graph data types</a>.  Developing a base hierarchy is going to be my main focus at AusHac (the collections classes are aimed at being used within this graph library).  My current plans look something like this (note that this doesn&#8217;t include extra packages providing specific instances, such as &#8220;vector-graph&#8221; or something):</p>
<p><a href="http://ivanmiljenovic.files.wordpress.com/2010/07/intendedgraphhierarchy.png"><img src="http://ivanmiljenovic.files.wordpress.com/2010/07/intendedgraphhierarchy.png?w=769&#038;h=617" alt="" title="Intended Graph Hierarchy" width="769" height="617" class="aligncenter size-full wp-image-143" /></a></p>
<p>That is, the actual &#8220;graph&#8221; library will also cater for other graph-like data structures, such as <a href="http://hackage.haskell.org/packages/archive/Cabal/1.8.0.6/doc/html/Distribution-Simple-PackageIndex.html#t%3APackageIndex">Cabal&#8217;s PackageIndex</a> type.  FGL (both the old and the &#8220;new&#8221; version, whatever it&#8217;ll be called) will then extend these classes to provide the notion of inductive graphs; anything that isn&#8217;t directly related to the notion of inductive graphs will be shifted down to this notion of &#8220;generic graphs&#8221;.</p>
<p>In terms of terminology, to ease the transition I&#8217;m probably going to stick to current FGL-nomenclature for the most part (unless there&#8217;s something horribly wrong/bad about it).  So we&#8217;re still going to talk about Nodes rather than Vertices, etc.</p>
<h4>Old FGL</h4>
<p>As I intimated in the <a href="http://permalink.gmane.org/gmane.comp.lang.haskell.cafe/77326">extended announcement</a> for <a href="http://hackage.haskell.org/package/fgl-5.4.2.3">fgl-5.4.2.3</a>, apart from bug-fixes we&#8217;re not going to work on the current 5.4 branch.  The 5.5 branch will be developed so as to use the generic graph classes once I&#8217;ve got them sorted out, and then that will probably be the end of it.</p>
<h4>New FGL</h4>
<p>Now, this has become a rather hot topic: should a rewrite of FGL still be called FGL?  I&#8217;ve covered this <a href="http://ivanmiljenovic.wordpress.com/2010/06/12/pre-announce-for-the-new-fgl/">earlier</a>, but I have now created a <a href="https://spreadsheets.google.com/viewform?formkey=dGpzMmFnUWY3Uktodk5wdHlLQk5kT1E6MA">survey</a> to try and find out what the community thinks it should be called (I did want an &#8220;other&#8221; option in the first drop-down menu, but Google Docs wouldn&#8217;t let me <img src='http://s0.wp.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  ).</p>
<br />Filed under: <a href='http://ivanmiljenovic.wordpress.com/category/graphs/'>Graphs</a>, <a href='http://ivanmiljenovic.wordpress.com/category/haskell/'>Haskell</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ivanmiljenovic.wordpress.com/142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ivanmiljenovic.wordpress.com/142/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ivanmiljenovic.wordpress.com&#038;blog=2244391&#038;post=142&#038;subd=ivanmiljenovic&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ivanmiljenovic.wordpress.com/2010/07/14/data-oriented-hierarchies/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/82401038e87257529066b9e6618d470e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ivanm</media:title>
		</media:content>

		<media:content url="http://ivanmiljenovic.files.wordpress.com/2010/07/intendedgraphhierarchy.png" medium="image">
			<media:title type="html">Intended Graph Hierarchy</media:title>
		</media:content>
	</item>
	</channel>
</rss>
