<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
    <channel>
        <title>Roman Cheplyaka: articles</title>
        <link>http://ro-che.info/</link>
        <description />
        
        <lastBuildDate>Sun, 31 Mar 2013 00:00:00 UT</lastBuildDate>
        <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/RomanCheplyaka" /><feedburner:info uri="romancheplyaka" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
    <title>Flavours of free applicative functors</title>
    <link>http://feedproxy.google.com/~r/RomanCheplyaka/~3/2p9BKTp4TL8/2013-03-31-flavours-of-free-applicative-functors.html</link>
    <description>&lt;p&gt;Six months ago Tom Ellis wrote the article &lt;a href="http://web.jaguarpaw.co.uk/~tom/blog/2012/09/09/towards-free-applicatives.html"&gt;Towards Free Applicatives&lt;/a&gt;, where he described his implementation of a free applicative functor. In the &lt;a href="http://www.reddit.com/r/haskell/comments/zlr0l/towards_free_applicatives/?sort=old"&gt;reddit discussion&lt;/a&gt; of that article a few more implementations were suggested.&lt;/p&gt;
&lt;p&gt;In this article I would like to look in more detail how these implementations work and how they differ from each other.&lt;/p&gt;
&lt;p&gt;The implementations are rewritten in a common style where possible, to highlight the differences and similarities. Since a picture is worth a thousand words, for each implementation there’s a diagram showing how a simple applicative expression &lt;code&gt;f &amp;lt;$&amp;gt; lift ax &amp;lt;*&amp;gt; lift ay &amp;lt;*&amp;gt; lift az&lt;/code&gt; is represented.&lt;/p&gt;
&lt;h2 id="notational-conventions"&gt;Notational conventions&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;x&lt;/code&gt;, &lt;code&gt;y&lt;/code&gt;, &lt;code&gt;z&lt;/code&gt;, &lt;code&gt;f&lt;/code&gt; — simple (non-functorial) values&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ax&lt;/code&gt;, &lt;code&gt;ay&lt;/code&gt;, &lt;code&gt;az&lt;/code&gt; — values of the base functor type&lt;/li&gt;
&lt;li&gt;&lt;code&gt;tx&lt;/code&gt;, &lt;code&gt;ty&lt;/code&gt;, &lt;code&gt;tz&lt;/code&gt; — values of the free applicative functor type&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="on-the-diagrams"&gt;On the diagrams&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;F&lt;/code&gt; — base functor&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Tx&lt;/code&gt;, &lt;code&gt;Ty&lt;/code&gt;, &lt;code&gt;Tz&lt;/code&gt; — inner types of functorial values (e.g. &lt;code&gt;ax&lt;/code&gt; has type &lt;code&gt;F   Tx&lt;/code&gt;). The function &lt;code&gt;f&lt;/code&gt; has type &lt;code&gt;Tx -&amp;gt; Ty -&amp;gt; Tz -&amp;gt; Tr&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;A square denotes unit (i.e. &lt;code&gt;()&lt;/code&gt;) as a type, term and pattern.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="ørjan-johansens-free-applicative"&gt;Ørjan Johansen’s free applicative&lt;/h2&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;data&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f a &lt;span class="kw"&gt;where&lt;/span&gt;
  &lt;span class="dt"&gt;Pure&lt;/span&gt;&lt;span class="ot"&gt; ::&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f a
  &lt;span class="dt"&gt;Ap&lt;/span&gt;&lt;span class="ot"&gt; ::&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f (a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; b) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; f a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f b

&lt;span class="kw"&gt;instance&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; (&lt;span class="dt"&gt;Free&lt;/span&gt; f) &lt;span class="kw"&gt;where&lt;/span&gt;
  &lt;span class="fu"&gt;fmap&lt;/span&gt; f (&lt;span class="dt"&gt;Pure&lt;/span&gt; x) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Pure&lt;/span&gt; &lt;span class="fu"&gt;$&lt;/span&gt; f x
  &lt;span class="fu"&gt;fmap&lt;/span&gt; f (&lt;span class="dt"&gt;Ap&lt;/span&gt; tx ay) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Ap&lt;/span&gt; ((f &lt;span class="fu"&gt;.&lt;/span&gt;) &lt;span class="fu"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; tx) ay

&lt;span class="kw"&gt;instance&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="kw"&gt;Applicative&lt;/span&gt; (&lt;span class="dt"&gt;Free&lt;/span&gt; f) &lt;span class="kw"&gt;where&lt;/span&gt;
  pure &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Pure&lt;/span&gt;
  tx &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Pure&lt;/span&gt; y &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="fu"&gt;fmap&lt;/span&gt; (&lt;span class="fu"&gt;$&lt;/span&gt; y) tx
  tx &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Ap&lt;/span&gt; ty az &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Ap&lt;/span&gt; ((&lt;span class="fu"&gt;.&lt;/span&gt;) &lt;span class="fu"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; tx &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; ty) az

&lt;span class="ot"&gt;lift ::&lt;/span&gt; f a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f a
lift &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Ap&lt;/span&gt; (&lt;span class="dt"&gt;Pure&lt;/span&gt; &lt;span class="fu"&gt;id&lt;/span&gt;)

&lt;span class="ot"&gt;lower ::&lt;/span&gt; &lt;span class="kw"&gt;Applicative&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; f a
lower (&lt;span class="dt"&gt;Pure&lt;/span&gt; x) &lt;span class="fu"&gt;=&lt;/span&gt; pure x
lower (&lt;span class="dt"&gt;Ap&lt;/span&gt; tx ay) &lt;span class="fu"&gt;=&lt;/span&gt; lower tx &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; ay&lt;/code&gt;&lt;/pre&gt;
&lt;div class="figure"&gt;
&lt;img src="/img/freeapp-0.png" /&gt;
&lt;/div&gt;
&lt;p&gt;The tree grows to the left. This can be easily seen on the diagram, and follows from the fact that the first argument of &lt;code&gt;Ap&lt;/code&gt; is a free applicative itself and the second is not. (How the tree grows depends, obviously, on the order of &lt;code&gt;Ap&lt;/code&gt;’s arguments. The convention here is that &lt;code&gt;Ap&lt;/code&gt;’s arguments are in the applicative order, so that we can meaningfully talk about the tree’s associativity.)&lt;/p&gt;
&lt;p&gt;&lt;code&gt;&amp;lt;*&amp;gt;&lt;/code&gt; pattern-matches on its right argument, effectively re-associating the tree to the left.&lt;/p&gt;
&lt;p&gt;Note that &lt;code&gt;Free f a&lt;/code&gt; is an applicative functor regardless of &lt;code&gt;f&lt;/code&gt;. It stores &lt;code&gt;f&lt;/code&gt;-values in the tree without changes. We’ll see later that this is not always the case.&lt;/p&gt;
&lt;h2 id="twan-van-laarhovens-free-applicative"&gt;Twan van Laarhoven’s free applicative&lt;/h2&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;data&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f a &lt;span class="kw"&gt;where&lt;/span&gt;
  &lt;span class="dt"&gt;Pure&lt;/span&gt;&lt;span class="ot"&gt; ::&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f a
  &lt;span class="dt"&gt;Ap&lt;/span&gt;&lt;span class="ot"&gt; ::&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f (a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; b) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; f a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f b

&lt;span class="kw"&gt;instance&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; (&lt;span class="dt"&gt;Free&lt;/span&gt; f) &lt;span class="kw"&gt;where&lt;/span&gt;
  &lt;span class="fu"&gt;fmap&lt;/span&gt; f (&lt;span class="dt"&gt;Pure&lt;/span&gt; x) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Pure&lt;/span&gt; &lt;span class="fu"&gt;$&lt;/span&gt; f x
  &lt;span class="fu"&gt;fmap&lt;/span&gt; f (&lt;span class="dt"&gt;Ap&lt;/span&gt; tx ay) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Ap&lt;/span&gt; ((f &lt;span class="fu"&gt;.&lt;/span&gt;) &lt;span class="fu"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; tx) ay

&lt;span class="kw"&gt;instance&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="kw"&gt;Applicative&lt;/span&gt; (&lt;span class="dt"&gt;Free&lt;/span&gt; f) &lt;span class="kw"&gt;where&lt;/span&gt;
  pure &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Pure&lt;/span&gt;
  &lt;span class="dt"&gt;Pure&lt;/span&gt; f &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; tx &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="fu"&gt;fmap&lt;/span&gt; f tx
  &lt;span class="dt"&gt;Ap&lt;/span&gt; tx ay &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; tz &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Ap&lt;/span&gt; (&lt;span class="fu"&gt;flip&lt;/span&gt; &lt;span class="fu"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; tx &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; tz) ay

&lt;span class="ot"&gt;lift ::&lt;/span&gt; f a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f a
lift &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Ap&lt;/span&gt; (&lt;span class="dt"&gt;Pure&lt;/span&gt; &lt;span class="fu"&gt;id&lt;/span&gt;)

&lt;span class="ot"&gt;lower ::&lt;/span&gt; &lt;span class="kw"&gt;Applicative&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; f a
lower (&lt;span class="dt"&gt;Pure&lt;/span&gt; x) &lt;span class="fu"&gt;=&lt;/span&gt; pure x
lower (&lt;span class="dt"&gt;Ap&lt;/span&gt; tx ay) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="fu"&gt;flip&lt;/span&gt; &lt;span class="fu"&gt;id&lt;/span&gt; &lt;span class="fu"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; ay &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; lower tx&lt;/code&gt;&lt;/pre&gt;
&lt;div class="figure"&gt;
&lt;img src="/img/freeapp-1.png" /&gt;
&lt;/div&gt;
&lt;p&gt;This is a variation of Ørjan’s implementation. As can be seen from the diagrams, the only difference is that it stores the values in the opposite order, and modifies the function to accept them in that order.&lt;/p&gt;
&lt;p&gt;As in Ørjan’s implementation, the tree grows to the left, but &lt;code&gt;&amp;lt;*&amp;gt;&lt;/code&gt; now pattern-matches on its left argument, in order to push its right argument to the leftmost position in the tree.&lt;/p&gt;
&lt;p&gt;The way &lt;code&gt;&amp;lt;*&amp;gt;&lt;/code&gt; does pattern matching directly affects its algorithmic complexity. Ørjan’s implementation is linear in the size of its right argument and thus works better with left-associated applicative expressions. Twan’s version is dual: it is linear in the size of its left argument and works better with right-associated expressions. In both cases, unfortunate nesting increases complexity from linear to quadratic.&lt;/p&gt;
&lt;p&gt;Also pay attention to the &lt;code&gt;lower&lt;/code&gt; function. It has to take care of the effects — the right subtree must be «executed» before the left subtree in order to restore the original value faithfully.&lt;/p&gt;
&lt;h2 id="paolo-capriottis-free-applicative"&gt;Paolo Capriotti’s free applicative&lt;/h2&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;data&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f a &lt;span class="kw"&gt;where&lt;/span&gt;
  &lt;span class="dt"&gt;Pure&lt;/span&gt;&lt;span class="ot"&gt; ::&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f a
  &lt;span class="dt"&gt;Ap&lt;/span&gt;&lt;span class="ot"&gt; ::&lt;/span&gt; f (a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; b) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f b

&lt;span class="kw"&gt;instance&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; (&lt;span class="dt"&gt;Free&lt;/span&gt; f) &lt;span class="kw"&gt;where&lt;/span&gt;
  &lt;span class="fu"&gt;fmap&lt;/span&gt; f (&lt;span class="dt"&gt;Pure&lt;/span&gt; x) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Pure&lt;/span&gt; &lt;span class="fu"&gt;$&lt;/span&gt; f x
  &lt;span class="fu"&gt;fmap&lt;/span&gt; f (&lt;span class="dt"&gt;Ap&lt;/span&gt; ax ty) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Ap&lt;/span&gt; (&lt;span class="fu"&gt;fmap&lt;/span&gt; (f&lt;span class="fu"&gt;.&lt;/span&gt;) ax) ty

&lt;span class="kw"&gt;instance&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="kw"&gt;Applicative&lt;/span&gt; (&lt;span class="dt"&gt;Free&lt;/span&gt; f) &lt;span class="kw"&gt;where&lt;/span&gt;
  pure &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Pure&lt;/span&gt;
  &lt;span class="dt"&gt;Pure&lt;/span&gt; f &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; tx &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="fu"&gt;fmap&lt;/span&gt; f tx
  &lt;span class="dt"&gt;Ap&lt;/span&gt; ax ty &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; tz &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Ap&lt;/span&gt; (&lt;span class="fu"&gt;fmap&lt;/span&gt; &lt;span class="fu"&gt;uncurry&lt;/span&gt; ax) ((,) &lt;span class="fu"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; ty &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; tz)

&lt;span class="ot"&gt;lift ::&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; f a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f a
lift ax &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Ap&lt;/span&gt; (&lt;span class="fu"&gt;const&lt;/span&gt; &lt;span class="fu"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; ax) (&lt;span class="dt"&gt;Pure&lt;/span&gt; ())

&lt;span class="ot"&gt;lower ::&lt;/span&gt; &lt;span class="kw"&gt;Applicative&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Free&lt;/span&gt; f a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; f a
lower (&lt;span class="dt"&gt;Pure&lt;/span&gt; x) &lt;span class="fu"&gt;=&lt;/span&gt; pure x
lower (&lt;span class="dt"&gt;Ap&lt;/span&gt; ax ty) &lt;span class="fu"&gt;=&lt;/span&gt; ax &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; lower ty&lt;/code&gt;&lt;/pre&gt;
&lt;div class="figure"&gt;
&lt;img src="/img/freeapp-2.png" /&gt;
&lt;/div&gt;
&lt;p&gt;The diagram looks more complicated here. The first thing to notice is that the tree here grows to the right, unlike in the previous versions. The actual application of our &lt;code&gt;f&lt;/code&gt; function happens now near the top of the tree rather than at the bottom. To make that possible, the function has to be converted to the uncurried form.&lt;/p&gt;
&lt;p&gt;All left nodes except the topmost one are functions (wrapped in the base functor). All they do is take a nested tuple of the arguments downstream and add their own value to that tuple. The topmost left node already knows the final required argument, &lt;code&gt;ax&lt;/code&gt;, and simply applies the uncurried function to the tuple.&lt;/p&gt;
&lt;p&gt;The functorial values are stored in a modified form, which requires &lt;code&gt;f&lt;/code&gt; to be an actual &lt;code&gt;Functor&lt;/code&gt;. (But note that any &lt;code&gt;f&lt;/code&gt; can be turned into a functor using &lt;a href="http://hackage.haskell.org/packages/archive/category-extras/latest/doc/html/Control-Functor-Yoneda.html"&gt;Yoneda&lt;/a&gt;.)&lt;/p&gt;
&lt;h2 id="tom-elliss-free-applicative"&gt;Tom Ellis’s free applicative&lt;/h2&gt;
&lt;p&gt;The code here is quite different from the previous versions, so I decided to reproduce it verbatim (except the &lt;code&gt;lift&lt;/code&gt; and &lt;code&gt;lower&lt;/code&gt; functions, which I’ve added myself).&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;data&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; f a b &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Single&lt;/span&gt; (f (a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; b)) &lt;span class="fu"&gt;|&lt;/span&gt; forall c&lt;span class="fu"&gt;.&lt;/span&gt; &lt;span class="dt"&gt;Many&lt;/span&gt; (f (c &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; b)) (&lt;span class="dt"&gt;ChainA&lt;/span&gt; f a c)

&lt;span class="kw"&gt;instance&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; (&lt;span class="dt"&gt;ChainA&lt;/span&gt; f a) &lt;span class="kw"&gt;where&lt;/span&gt;
    &lt;span class="fu"&gt;fmap&lt;/span&gt; f (&lt;span class="dt"&gt;Single&lt;/span&gt; t) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Single&lt;/span&gt; (&lt;span class="fu"&gt;fmap&lt;/span&gt; (f &lt;span class="fu"&gt;.&lt;/span&gt;) t)
    &lt;span class="fu"&gt;fmap&lt;/span&gt; f (&lt;span class="dt"&gt;Many&lt;/span&gt; g v) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Many&lt;/span&gt; (&lt;span class="fu"&gt;fmap&lt;/span&gt; (f &lt;span class="fu"&gt;.&lt;/span&gt;) g) v

&lt;span class="ot"&gt;chain ::&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; f b c &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; f a b &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; f a c
chain (&lt;span class="dt"&gt;Single&lt;/span&gt; t) v &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Many&lt;/span&gt; t v
chain (&lt;span class="dt"&gt;Many&lt;/span&gt; t ts) v &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Many&lt;/span&gt; t (chain ts v)

&lt;span class="kw"&gt;data&lt;/span&gt; &lt;span class="dt"&gt;FreeA&lt;/span&gt; f a &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Pure&lt;/span&gt; a &lt;span class="fu"&gt;|&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; (&lt;span class="dt"&gt;ChainA&lt;/span&gt; f () a)

&lt;span class="kw"&gt;instance&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; (&lt;span class="dt"&gt;FreeA&lt;/span&gt; f) &lt;span class="kw"&gt;where&lt;/span&gt;
    &lt;span class="fu"&gt;fmap&lt;/span&gt; f (&lt;span class="dt"&gt;Pure&lt;/span&gt; a) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Pure&lt;/span&gt; (f a)
    &lt;span class="fu"&gt;fmap&lt;/span&gt; f (&lt;span class="dt"&gt;ChainA&lt;/span&gt; a) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; (&lt;span class="fu"&gt;fmap&lt;/span&gt; f a)

&lt;span class="kw"&gt;instance&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="kw"&gt;Applicative&lt;/span&gt; (&lt;span class="dt"&gt;FreeA&lt;/span&gt; f) &lt;span class="kw"&gt;where&lt;/span&gt;
    pure &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Pure&lt;/span&gt;
    &lt;span class="dt"&gt;Pure&lt;/span&gt; f &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; g &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="fu"&gt;fmap&lt;/span&gt; f g
    f &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Pure&lt;/span&gt; g &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="fu"&gt;fmap&lt;/span&gt; (&lt;span class="fu"&gt;$&lt;/span&gt; g) f
    &lt;span class="dt"&gt;ChainA&lt;/span&gt; f &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; g &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; &lt;span class="fu"&gt;$&lt;/span&gt; chain (pullUnit f) g

&lt;span class="ot"&gt;pullUnit ::&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; f () (b &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; f b c
pullUnit &lt;span class="fu"&gt;=&lt;/span&gt; removeUnit &lt;span class="fu"&gt;.&lt;/span&gt; pull

&lt;span class="ot"&gt;pass ::&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; f a b &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; f (a,c) (b,c)
pass (&lt;span class="dt"&gt;Single&lt;/span&gt; t) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Single&lt;/span&gt; (&lt;span class="fu"&gt;fmap&lt;/span&gt; (\f &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; \(a,c) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; (f a, c)) t)
pass (&lt;span class="dt"&gt;Many&lt;/span&gt; t ts) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Many&lt;/span&gt; (&lt;span class="fu"&gt;fmap&lt;/span&gt; (\f &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; \(a,c) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; (f a, c)) t) (pass ts)

&lt;span class="ot"&gt;pull ::&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; f a (b &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; f (a,b) c
pull (&lt;span class="dt"&gt;Single&lt;/span&gt; t) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Single&lt;/span&gt; (&lt;span class="fu"&gt;fmap&lt;/span&gt; &lt;span class="fu"&gt;uncurry&lt;/span&gt; t)
pull (&lt;span class="dt"&gt;Many&lt;/span&gt; t ts) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Many&lt;/span&gt; (&lt;span class="fu"&gt;fmap&lt;/span&gt; &lt;span class="fu"&gt;uncurry&lt;/span&gt; t) (pass ts)

&lt;span class="ot"&gt;removeUnit ::&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; f ((), a) b &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; f a b
removeUnit (&lt;span class="dt"&gt;Single&lt;/span&gt; t) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Single&lt;/span&gt; (&lt;span class="fu"&gt;fmap&lt;/span&gt; (\f &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; \a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; f ((),a)) t)
removeUnit (&lt;span class="dt"&gt;Many&lt;/span&gt; t ts) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Many&lt;/span&gt; t (removeUnit ts)

&lt;span class="ot"&gt;lift ::&lt;/span&gt; &lt;span class="kw"&gt;Functor&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; f a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;FreeA&lt;/span&gt; f a
lift ax &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; &lt;span class="fu"&gt;$&lt;/span&gt; &lt;span class="dt"&gt;Single&lt;/span&gt; &lt;span class="fu"&gt;$&lt;/span&gt; &lt;span class="fu"&gt;const&lt;/span&gt; &lt;span class="fu"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; ax

&lt;span class="ot"&gt;lower ::&lt;/span&gt; &lt;span class="kw"&gt;Applicative&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;FreeA&lt;/span&gt; f a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; f a
lower (&lt;span class="dt"&gt;Pure&lt;/span&gt; x) &lt;span class="fu"&gt;=&lt;/span&gt; pure x
lower (&lt;span class="dt"&gt;ChainA&lt;/span&gt; chain) &lt;span class="fu"&gt;=&lt;/span&gt; lowerChain chain &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; pure ()
  &lt;span class="kw"&gt;where&lt;/span&gt;
&lt;span class="ot"&gt;    lowerChain ::&lt;/span&gt; &lt;span class="kw"&gt;Applicative&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;ChainA&lt;/span&gt; f x y &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; f (x &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; y)
    lowerChain (&lt;span class="dt"&gt;Single&lt;/span&gt; ax) &lt;span class="fu"&gt;=&lt;/span&gt; ax
    lowerChain (&lt;span class="dt"&gt;Many&lt;/span&gt; ax ty) &lt;span class="fu"&gt;=&lt;/span&gt; (&lt;span class="fu"&gt;.&lt;/span&gt;) &lt;span class="fu"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; ax &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; lowerChain ty&lt;/code&gt;&lt;/pre&gt;
&lt;div class="figure"&gt;
&lt;img src="/img/freeapp-3.png" /&gt;
&lt;/div&gt;
&lt;p&gt;Despite the superficial dissimilarity of the code, this is really a variation on Paolo’s implementation. The only difference is that unit is not passed as a part of the nested tuples. Two-level types and auxiliary functions are really just the cost of eliminating that unit.&lt;/p&gt;
&lt;h2 id="which-one-to-use"&gt;Which one to use?&lt;/h2&gt;
&lt;p&gt;I regard Ørjan’s version as the principal one. It is simple, powerful (doesn’t require &lt;code&gt;f&lt;/code&gt; to be a functor) and straightforward (doesn’t change the arguments order).&lt;/p&gt;
&lt;p&gt;The &lt;a href="http://hackage.haskell.org/package/free"&gt;free&lt;/a&gt; package currently uses the Twan’s version, which is the reason of the reverse effect that I &lt;a href="http://ro-che.info/articles/2013-03-29-gtraverse-vs-gfoldl.html#remaining-issues"&gt;mentioned&lt;/a&gt; in the previous article. Edward Kmett &lt;a href="https://github.com/ekmett/free/issues/15"&gt;points out&lt;/a&gt; that the reason for choosing Twan’s implementation is that you can see the «next instruction» in O(1) when walking left to right, which is most common.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/RomanCheplyaka/~4/2p9BKTp4TL8" height="1" width="1"/&gt;</description>
    <pubDate>Sun, 31 Mar 2013 00:00:00 UT</pubDate>
    <guid isPermaLink="false">http://ro-che.info//articles/2013-03-31-flavours-of-free-applicative-functors.html</guid>
<feedburner:origLink>http://ro-che.info//articles/2013-03-31-flavours-of-free-applicative-functors.html</feedburner:origLink></item>
<item>
    <title>gtraverse vs gfoldl</title>
    <link>http://feedproxy.google.com/~r/RomanCheplyaka/~3/_iTMzVphvwA/2013-03-29-gtraverse-vs-gfoldl.html</link>
    <description>&lt;p&gt;In &lt;a href="http://ro-che.info/articles/2013-03-11-generalizing-gfoldl.html"&gt;Generalizing generic fold&lt;/a&gt;, I introduced the &lt;code&gt;gtraverse&lt;/code&gt; function as an alternative to &lt;code&gt;gfoldl&lt;/code&gt; for generic programming.&lt;/p&gt;
&lt;p&gt;To remind the important points:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;gtraverse&lt;/code&gt; allows more instances to be written, being more flexible about which elements can be treated as being on the same level;&lt;/li&gt;
&lt;li&gt;on the other hand, everything that is possible to do with &lt;code&gt;gfoldl&lt;/code&gt; seems to be possible to do with &lt;code&gt;gtraverse&lt;/code&gt;, too.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;It turns out that my intuition was wrong. There is a beautiful correspondence between &lt;code&gt;gfoldl&lt;/code&gt; and &lt;code&gt;gtraverse&lt;/code&gt; which shows that they are, in fact, equivalent in power. Read on to find out why, and what this means for practical generic programming.&lt;/p&gt;
&lt;h2 id="gtraverse-through-gfoldl"&gt;gtraverse through gfoldl&lt;/h2&gt;
&lt;p&gt;As a quick warm-up, let’s implement &lt;code&gt;gtraverse&lt;/code&gt; through &lt;code&gt;gfoldl&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;For simplicity, let’s assume that &lt;code&gt;gfoldl&lt;/code&gt; and &lt;code&gt;gtraverse&lt;/code&gt; are both methods of the same class, &lt;code&gt;Data&lt;/code&gt;:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="ot"&gt;{-# LANGUAGE RankNTypes, GADTs, NoMonoLocalBinds #-}&lt;/span&gt;

&lt;span class="kw"&gt;class&lt;/span&gt; &lt;span class="dt"&gt;Data&lt;/span&gt; a &lt;span class="kw"&gt;where&lt;/span&gt;
  gfoldl
&lt;span class="ot"&gt;    ::&lt;/span&gt; (forall d b&lt;span class="fu"&gt;.&lt;/span&gt; &lt;span class="dt"&gt;Data&lt;/span&gt; d &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; c (d &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; b) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; d &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c b)
    &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; (forall g&lt;span class="fu"&gt;.&lt;/span&gt; g &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c g)
    &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c a

  gtraverse
&lt;span class="ot"&gt;    ::&lt;/span&gt; &lt;span class="kw"&gt;Applicative&lt;/span&gt; w
    &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; (forall d &lt;span class="fu"&gt;.&lt;/span&gt; &lt;span class="dt"&gt;Data&lt;/span&gt; d &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; d &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; w d)
    &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; w a&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;gtraverse f &lt;span class="fu"&gt;=&lt;/span&gt; gfoldl g pure
  &lt;span class="kw"&gt;where&lt;/span&gt;
    g acc x &lt;span class="fu"&gt;=&lt;/span&gt; acc &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; f x&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In plain English, when folding, we inject each element into &lt;code&gt;c&lt;/code&gt; using the supplied function &lt;code&gt;f&lt;/code&gt;, and then combine it with the accumulator using &lt;code&gt;&amp;lt;*&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id="gfoldl-through-gtraverse"&gt;gfoldl through gtraverse&lt;/h2&gt;
&lt;p&gt;It turns out that &lt;code&gt;gfoldl&lt;/code&gt; can also be interpreted as an applicative traversal for a particular functor — namely, the &lt;em&gt;free applicative functor&lt;/em&gt;. We’ll use the one from the &lt;a href="http://www.iai.uni-bonn.de/~jv/mpc08.pdf"&gt;free&lt;/a&gt; package for now.&lt;/p&gt;
&lt;p&gt;If we run &lt;code&gt;gtraverse&lt;/code&gt; with &lt;code&gt;liftAp Identity&lt;/code&gt; (where &lt;code&gt;Identity&lt;/code&gt; wraps its element into a trivial applicative functor), we’ll get a &lt;em&gt;list&lt;/em&gt; rather than a &lt;em&gt;tree&lt;/em&gt;, which can be easily folded in a &lt;code&gt;gfoldl&lt;/code&gt;-like fashion.&lt;/p&gt;
&lt;p&gt;One minor issue is that &lt;code&gt;Identity&lt;/code&gt; has to capture the &lt;code&gt;Data&lt;/code&gt; dictionary of the elements. We can easily achieve that using a GADT&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;data&lt;/span&gt; &lt;span class="dt"&gt;I&lt;/span&gt; a &lt;span class="kw"&gt;where&lt;/span&gt; &lt;span class="dt"&gt;I&lt;/span&gt;&lt;span class="ot"&gt; ::&lt;/span&gt; forall a &lt;span class="fu"&gt;.&lt;/span&gt; &lt;span class="dt"&gt;Data&lt;/span&gt; a &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;I&lt;/span&gt; a&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, &lt;code&gt;gtraverse (liftAp . I)&lt;/code&gt; has type &lt;code&gt;Data a =&amp;gt; a -&amp;gt; Ap I a&lt;/code&gt;. It transforms any value for which &lt;code&gt;gtraverse&lt;/code&gt; is defined to a (heterogeneous) list &lt;code&gt;Ap I a&lt;/code&gt;, which contains all immediate children of that value, together with their &lt;code&gt;Data&lt;/code&gt; dictionaries.&lt;/p&gt;
&lt;p&gt;The next step is to fold that list:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;foldAp
&lt;span class="ot"&gt;  ::&lt;/span&gt; (forall d b&lt;span class="fu"&gt;.&lt;/span&gt; &lt;span class="dt"&gt;Data&lt;/span&gt; d &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; c (d &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; b) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; d &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c b)
  &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; (forall g&lt;span class="fu"&gt;.&lt;/span&gt; g &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c g)
  &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Ap&lt;/span&gt; &lt;span class="dt"&gt;I&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c a
foldAp f z (&lt;span class="dt"&gt;Pure&lt;/span&gt; x) &lt;span class="fu"&gt;=&lt;/span&gt; z x
foldAp f z (&lt;span class="dt"&gt;Ap&lt;/span&gt; (&lt;span class="dt"&gt;I&lt;/span&gt; x) k) &lt;span class="fu"&gt;=&lt;/span&gt; (foldAp f z k) &lt;span class="ot"&gt;`f`&lt;/span&gt; x&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;foldAp&lt;/code&gt; takes the same two functional arguments as &lt;code&gt;gfoldl&lt;/code&gt;. But instead of working on the original value, it works on the flattened &lt;code&gt;Ap&lt;/code&gt;-list.&lt;/p&gt;
&lt;p&gt;After gluing the two steps together, we get&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;gfoldl f z &lt;span class="fu"&gt;=&lt;/span&gt; foldAp f z &lt;span class="fu"&gt;.&lt;/span&gt; gtraverse (liftAp &lt;span class="fu"&gt;.&lt;/span&gt; &lt;span class="dt"&gt;I&lt;/span&gt;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Nice!&lt;/p&gt;
&lt;h2 id="consequences"&gt;Consequences&lt;/h2&gt;
&lt;p&gt;So, what does this mean? Do you not need &lt;code&gt;gtraverse&lt;/code&gt; since &lt;code&gt;gfoldl&lt;/code&gt; can do all the same things?&lt;/p&gt;
&lt;p&gt;No!&lt;/p&gt;
&lt;p&gt;It is much easier to write instances for your data types using &lt;code&gt;gtraverse&lt;/code&gt;, especially when you want to present an alternative view on the type from what is directly implied by its definition. (If you doubt it, you can still try to encode the uniform &lt;code&gt;Data&lt;/code&gt; instance for lists and compare it with the &lt;a href="http://ro-che.info/articles/2013-03-11-generalizing-gfoldl.html"&gt;&lt;code&gt;gtraverse&lt;/code&gt;-based&lt;/a&gt; one.)&lt;/p&gt;
&lt;p&gt;On the other hand, it is nice to know that we don’t really lose any power by adopting &lt;code&gt;gtraverse&lt;/code&gt; instead of &lt;code&gt;gfoldl&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;You can try it out right now: I’ve just uploaded the first version of &lt;a href="https://github.com/feuerbach/traverse-with-class"&gt;traverse-with-class&lt;/a&gt; on &lt;a href="http://hackage.haskell.org/package/traverse-with-class"&gt;hackage&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id="remaining-issues"&gt;Remaining issues&lt;/h2&gt;
&lt;p&gt;There are a couple of issues in our &lt;code&gt;gfoldl&lt;/code&gt; implementation above&lt;sup&gt;&lt;a href="#fn1" class="footnoteRef" id="fnref1"&gt;1&lt;/a&gt;&lt;/sup&gt;:&lt;/p&gt;
&lt;ol style="list-style-type: decimal"&gt;
&lt;li&gt;Because of the free applicative functor usage, it has the same quadratic complexity problems as &lt;a href="http://www.iai.uni-bonn.de/~jv/mpc08.pdf"&gt;free monads&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Because of &lt;a href="http://ro-che.info/articles/2013-03-31-flavours-of-free-applicative-functors.html"&gt;the way this free applicative works&lt;/a&gt;, our &lt;code&gt;gfoldl&lt;/code&gt; is really a &lt;code&gt;gfoldr&lt;/code&gt;: it traverses the elements in the reverse order.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;I’ll talk more about these in subsequent articles.&lt;/p&gt;
&lt;div class="footnotes"&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id="fn1"&gt;&lt;p&gt;to make it clear, there are no such issues in the library, because it doesn’t provide a &lt;code&gt;gfoldl&lt;/code&gt; function. It provides unrelated functions &lt;code&gt;gfoldl'&lt;/code&gt; and &lt;code&gt;gfoldr&lt;/code&gt; with different types.&lt;a href="#fnref1"&gt;↩&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/RomanCheplyaka/~4/_iTMzVphvwA" height="1" width="1"/&gt;</description>
    <pubDate>Fri, 29 Mar 2013 00:00:00 UT</pubDate>
    <guid isPermaLink="false">http://ro-che.info//articles/2013-03-29-gtraverse-vs-gfoldl.html</guid>
<feedburner:origLink>http://ro-che.info//articles/2013-03-29-gtraverse-vs-gfoldl.html</feedburner:origLink></item>
<item>
    <title>Ergative verbs in programming</title>
    <link>http://feedproxy.google.com/~r/RomanCheplyaka/~3/8yraGwkgwLs/2013-03-14-ergative-verbs-in-programming.html</link>
    <description>&lt;p&gt;For a long time I felt uncomfortable with phrases like «my program doesn’t compile».&lt;/p&gt;
&lt;p&gt;Of course it doesn’t compile, stupid! &lt;em&gt;It’s not a compiler!&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;I understood that this phrase was supposed to mean «The compiler fails to compile my program». But nevertheless it seemed like a wrong usage of the verb «compile».&lt;/p&gt;
&lt;p&gt;Well, today I learned (thanks to &lt;a href="http://english.stackexchange.com/a/107292/2978"&gt;Edwin Ashworth&lt;/a&gt;) that this is a common phenomenon in English. It’s called &lt;a href="http://en.wikipedia.org/wiki/Ergative_verb"&gt;ergative usage&lt;/a&gt;. There is a &lt;a href="http://en.wiktionary.org/w/index.php?title=Category:English_ergative_verbs"&gt;long list of ergative verbs&lt;/a&gt; on Wiktionary, and «&lt;a href="http://en.wiktionary.org/wiki/compile#English"&gt;compile&lt;/a&gt;» is there!&lt;/p&gt;
&lt;p&gt;This is a list of programming-related verbs that I’ve seen being used ergatively:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;parse&lt;/li&gt;
&lt;li&gt;type-check&lt;/li&gt;
&lt;li&gt;compile&lt;/li&gt;
&lt;li&gt;build&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You can notice that they all follow the same pattern — something that one program (usually a compiler) does to another program. I’d be curious to find computing-related ergative verbs that do not fall into this pattern.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/RomanCheplyaka/~4/8yraGwkgwLs" height="1" width="1"/&gt;</description>
    <pubDate>Thu, 14 Mar 2013 00:00:00 UT</pubDate>
    <guid isPermaLink="false">http://ro-che.info//articles/2013-03-14-ergative-verbs-in-programming.html</guid>
<feedburner:origLink>http://ro-che.info//articles/2013-03-14-ergative-verbs-in-programming.html</feedburner:origLink></item>
<item>
    <title>Generalizing generic fold</title>
    <link>http://feedproxy.google.com/~r/RomanCheplyaka/~3/TFVXVw0Hkew/2013-03-11-generalizing-gfoldl.html</link>
    <description>&lt;h2 id="uniform-folding"&gt;Uniform folding&lt;/h2&gt;
&lt;p&gt;Suppose we’ve created a new container data structure in Haskell, such as &lt;code&gt;Data.Sequence.Seq&lt;/code&gt;. We now want to write a &lt;code&gt;Data&lt;/code&gt; instance for it, to allow generic queries and transforms inside our container.&lt;/p&gt;
&lt;p&gt;Let’s recall &lt;code&gt;gfoldl&lt;/code&gt; definition for lists:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;gfoldl f z [] &lt;span class="fu"&gt;=&lt;/span&gt; z []
gfoldl f z (x&lt;span class="fu"&gt;:&lt;/span&gt;xs) &lt;span class="fu"&gt;=&lt;/span&gt; z (&lt;span class="fu"&gt;:&lt;/span&gt;) &lt;span class="ot"&gt;`f`&lt;/span&gt; x &lt;span class="ot"&gt;`f`&lt;/span&gt; xs&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can define &lt;code&gt;gfoldl&lt;/code&gt; similarly for sequences (in fact, this is the precise definition from &lt;code&gt;Data.Sequence&lt;/code&gt;):&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;gfoldl f z s &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="kw"&gt;case&lt;/span&gt; viewl s &lt;span class="kw"&gt;of&lt;/span&gt;
  &lt;span class="dt"&gt;EmptyL&lt;/span&gt;  &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; z empty
  x &lt;span class="fu"&gt;:&amp;lt;&lt;/span&gt; xs &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; z (&lt;span class="fu"&gt;&amp;lt;|&lt;/span&gt;) &lt;span class="ot"&gt;`f`&lt;/span&gt; x &lt;span class="ot"&gt;`f`&lt;/span&gt; xs&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There are, however, downsides to this definition:&lt;/p&gt;
&lt;ol style="list-style-type: decimal"&gt;
&lt;li&gt;&lt;p&gt;Generic map over our container would be less efficient than hand-written map, even if we ignore the costs associated with run-time type casts.&lt;/p&gt;
&lt;p&gt;Indeed, in the generic definition we do not take advantage of the fact that we already have a proper container structure for our elements. Instead, we construct the structure from scratch, adding elements one by one. This overhead may be small for &lt;code&gt;Seq&lt;/code&gt;, whose cons is O(1). But in case of an array-based structure, such as &lt;code&gt;Vector&lt;/code&gt;, we’re out of luck.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If we only care about the &lt;em&gt;closed recursion&lt;/em&gt; combinators, such as &lt;code&gt;everywhere&lt;/code&gt;, we wouldn’t know the difference. But when &lt;em&gt;open recursion&lt;/em&gt; is needed (e.g. &lt;code&gt;gmapT&lt;/code&gt;), the semantics is not the one we’d expect. The intuition is that &lt;code&gt;gmapT&lt;/code&gt; maps over the immediate «subterms» of an expression. One might expect that the subterms of &lt;code&gt;Seq a&lt;/code&gt; are all of its elements (of type &lt;code&gt;a&lt;/code&gt;). But no, we’re forced into this recursive list mindset, where the immediate subterms of a sequence are its head and tail.&lt;/p&gt;
&lt;p&gt;(To be fair, it does make sense if we imagine data structures really being inductively-defined terms. But it is a very limited worldview.)&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Can we define &lt;code&gt;gfoldl&lt;/code&gt; in the uniform fashion, folding over all the elements at once? Try this yourself to understand better why it’s not easy.&lt;/p&gt;
&lt;p&gt;I haven’t actually done it, but I think it’s achievable using some amount of type class hackery. Anyway, having to come up with such hacks defeats the point of an easy-to-use generic programming library.&lt;/p&gt;
&lt;p&gt;In essence, the limitation of &lt;code&gt;gfoldl&lt;/code&gt; is that it forces us to know the number of elements in advance. We cannot (easily) construct the result of the fold by recursive computation.&lt;/p&gt;
&lt;h2 id="generic-traversals"&gt;Generic traversals&lt;/h2&gt;
&lt;p&gt;In order to resolve the problem stated above, we need to &lt;em&gt;restrict&lt;/em&gt; the type of &lt;code&gt;gfoldl&lt;/code&gt;&lt;sup&gt;&lt;a href="#fn1" class="footnoteRef" id="fnref1"&gt;1&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;
&lt;p&gt;Recall its type:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="ot"&gt;gfoldl ::&lt;/span&gt; (forall d b&lt;span class="fu"&gt;.&lt;/span&gt; &lt;span class="dt"&gt;Data&lt;/span&gt; d &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; c (d &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; b) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; d &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c b)
       &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; (forall g&lt;span class="fu"&gt;.&lt;/span&gt; g &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c g)
       &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c a&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What might the first functional argument of &lt;code&gt;gfoldl&lt;/code&gt; do? It &lt;em&gt;probably&lt;/em&gt; transforms &lt;code&gt;d&lt;/code&gt; to something like &lt;code&gt;c d&lt;/code&gt; by using its &lt;code&gt;Data&lt;/code&gt; instance, and then combines &lt;code&gt;c (d -&amp;gt; b)&lt;/code&gt; with &lt;code&gt;c d&lt;/code&gt; to obtain &lt;code&gt;c b&lt;/code&gt;. This is not a sure thing, of course: the caller of &lt;code&gt;gfoldl&lt;/code&gt; knows what &lt;code&gt;c&lt;/code&gt; exactly is, so it might combine them in unexpected ways. Let us proceed with this assumption, however; as I said above, we need to restrict the caller in order to give more power to the callee.&lt;/p&gt;
&lt;p&gt;So, if our guess is correct, we can separate the two activities into two different functions:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="ot"&gt;gfoldl ::&lt;/span&gt; (forall d&lt;span class="fu"&gt;.&lt;/span&gt; &lt;span class="dt"&gt;Data&lt;/span&gt; d &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; d &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c d)
       &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; (forall d b&lt;span class="fu"&gt;.&lt;/span&gt; c (d &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; b) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c d &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c b)
       &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; (forall g&lt;span class="fu"&gt;.&lt;/span&gt; g &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c g)
       &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c a&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The whole thing now suddenly becomes very familiar: &lt;code&gt;c&lt;/code&gt; is an applicative functor! The second and third arguments are &lt;code&gt;&amp;lt;*&amp;gt;&lt;/code&gt; and &lt;code&gt;pure&lt;/code&gt;, respectively. And the applicative laws had better hold — there are now many ways to express the same thing, and we don’t expect there to be a difference.&lt;/p&gt;
&lt;p&gt;Using the &lt;code&gt;Applicative&lt;/code&gt; class, we can rewrite the type as&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="ot"&gt;gtraverse ::&lt;/span&gt; &lt;span class="kw"&gt;Applicative&lt;/span&gt; c &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; (forall d &lt;span class="fu"&gt;.&lt;/span&gt; &lt;span class="dt"&gt;GTraversable&lt;/span&gt; d &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; d &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c d) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c a&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that I took this chance to rename our restricted &lt;code&gt;gfoldl&lt;/code&gt; to &lt;code&gt;gtraverse&lt;/code&gt; and &lt;code&gt;Data&lt;/code&gt; to &lt;code&gt;GTraversable&lt;/code&gt;. The reason is that it is a generic version of &lt;code&gt;traverse&lt;/code&gt; from &lt;code&gt;Data.Traversable&lt;/code&gt;, whose type is&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="ot"&gt;traverse ::&lt;/span&gt; &lt;span class="kw"&gt;Applicative&lt;/span&gt; c &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; (a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c b) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; t a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; c (t b)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Read the type of &lt;code&gt;gtraverse&lt;/code&gt; as «traverse this structure, applying the supplied function to the immediate subterms; then use the &lt;code&gt;Applicative&lt;/code&gt; instance to reconstruct the original structure».&lt;/p&gt;
&lt;p&gt;We can now write the uniform instance for lists (and any other algebraic data type) without a hassle:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;gtraverse f [] &lt;span class="fu"&gt;=&lt;/span&gt; pure []
gtraverse f (x&lt;span class="fu"&gt;:&lt;/span&gt;xs) &lt;span class="fu"&gt;=&lt;/span&gt; (&lt;span class="fu"&gt;:&lt;/span&gt;) &lt;span class="fu"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; f x &lt;span class="fu"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; gtraverse f xs&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But how does it restrict the caller of &lt;code&gt;gfoldl&lt;/code&gt;? Not much. All the usual combinators, such as &lt;code&gt;gmapT&lt;/code&gt;, &lt;code&gt;gmapQ&lt;/code&gt;, &lt;code&gt;gmapM&lt;/code&gt; etc. are expressible with &lt;code&gt;gtraverse&lt;/code&gt;. I’d be curious to see an application of &lt;code&gt;gfoldl&lt;/code&gt; for which &lt;code&gt;gtraverse&lt;/code&gt; is too restrictive.&lt;/p&gt;
&lt;div class="footnotes"&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id="fn1"&gt;&lt;p&gt;Yes, the article’s title is a lie. Thanks for reading this far. What we are really &lt;em&gt;generalizing&lt;/em&gt;, by allowing more instances, is the &lt;code&gt;Data&lt;/code&gt; class.&lt;a href="#fnref1"&gt;↩&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/RomanCheplyaka/~4/TFVXVw0Hkew" height="1" width="1"/&gt;</description>
    <pubDate>Mon, 11 Mar 2013 00:00:00 UT</pubDate>
    <guid isPermaLink="false">http://ro-che.info//articles/2013-03-11-generalizing-gfoldl.html</guid>
<feedburner:origLink>http://ro-che.info//articles/2013-03-11-generalizing-gfoldl.html</feedburner:origLink></item>
<item>
    <title>Open your name resolution</title>
    <link>http://feedproxy.google.com/~r/RomanCheplyaka/~3/fbILOaP7j6s/2013-03-04-open-name-resolution.html</link>
    <description>&lt;h2 id="what-is-name-resolution"&gt;What is name resolution?&lt;/h2&gt;
&lt;p&gt;Name resolution is a program analysis which for every name decides what that name refers to.&lt;/p&gt;
&lt;p&gt;Consider the following Haskell program as an example:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="ot"&gt;n ::&lt;/span&gt; &lt;span class="dt"&gt;Integer&lt;/span&gt;
n &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="kw"&gt;let&lt;/span&gt; k &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dv"&gt;10&lt;/span&gt; &lt;span class="kw"&gt;in&lt;/span&gt; k &lt;span class="fu"&gt;*&lt;/span&gt; k&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There are three names in this program: &lt;code&gt;n&lt;/code&gt;, &lt;code&gt;k&lt;/code&gt; and &lt;code&gt;Integer&lt;/code&gt;. The result of name resolution in this case would be:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;n&lt;/code&gt; refers to the global value defined in the program itself, on lines 1-2;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Integer&lt;/code&gt; refers to the type (implicitly) imported from &lt;code&gt;Prelude&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;k&lt;/code&gt; on line 2 is a local value defined on the same line.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This article is concerned with the following question: &lt;strong&gt;how should the API of a name resolution library be structured&lt;/strong&gt;?&lt;/p&gt;
&lt;h2 id="annotations"&gt;Annotations&lt;/h2&gt;
&lt;p&gt;The standard approach is a function that transforms a simple AST to the annotated AST, where every name is annotated with its binding information (just like we did above).&lt;/p&gt;
&lt;p&gt;(Note that a simple map from names to binding information won’t do: the same name can refer to different things in different parts of the program.)&lt;/p&gt;
&lt;p&gt;This is enough for most applications of name resolution, such as type checking, compilation or static analysis.&lt;/p&gt;
&lt;h3 id="significance-of-lexical-environment"&gt;Significance of lexical environment&lt;/h3&gt;
&lt;p&gt;However, simple annotations are not enough for source-to-source transformations, like the ones performed by &lt;a href="http://www.haskell.org/haskellwiki/HaRe"&gt;HaRe&lt;/a&gt; or &lt;a href="http://www.youtube.com/watch?v=Ae-6uIMQPmU"&gt;HasFix&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Such transformations typically require access to the whole symbol table to avoid variable capture. As an example, imagine that in the new version of some module &lt;code&gt;Mod&lt;/code&gt; &lt;code&gt;foo&lt;/code&gt; has been renamed to &lt;code&gt;bar&lt;/code&gt;, and we want to adapt our own code to use this new version. And our code looks like this:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;baz x &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="kw"&gt;let&lt;/span&gt; bar &lt;span class="fu"&gt;=&lt;/span&gt; x &lt;span class="fu"&gt;+&lt;/span&gt; &lt;span class="dv"&gt;1&lt;/span&gt; &lt;span class="kw"&gt;in&lt;/span&gt; foo bar&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Name resolution tells us that &lt;code&gt;foo&lt;/code&gt; on that line indeed comes from &lt;code&gt;Mod&lt;/code&gt; and should be renamed. But if we blindly apply the renaming, we’ll get&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;baz x &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="kw"&gt;let&lt;/span&gt; bar &lt;span class="fu"&gt;=&lt;/span&gt; x &lt;span class="fu"&gt;+&lt;/span&gt; &lt;span class="dv"&gt;1&lt;/span&gt; &lt;span class="kw"&gt;in&lt;/span&gt; bar bar&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;where &lt;code&gt;bar&lt;/code&gt; no longer refers to the global value imported from &lt;code&gt;Mod&lt;/code&gt; — it has been captured by &lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;let&lt;/span&gt;&lt;/code&gt;!&lt;/p&gt;
&lt;p&gt;The solution is simple: rename &lt;code&gt;foo&lt;/code&gt; to qualified name &lt;code&gt;Mod.bar&lt;/code&gt; whenever simple &lt;code&gt;bar&lt;/code&gt; is already defined in the enclosing lexical scope. It requires us, however, to know the lexical environment at every point.&lt;/p&gt;
&lt;h3 id="annotating-with-symbol-tables"&gt;Annotating with symbol tables&lt;/h3&gt;
&lt;p&gt;Why not store the whole symbol table at every point in the AST? This could work. In a lazy language this is not even as bad, time- and space-wise, as it might seem.&lt;/p&gt;
&lt;p&gt;It is cumbersome, however. Every time we replace a subtree, we need manually to re-run name resolution on the new subtree (or even on the whole tree, if there’s any possibility that other annotations may become invalid as a result of the replacement).&lt;/p&gt;
&lt;h2 id="open-recursion"&gt;Open recursion&lt;/h2&gt;
&lt;p&gt;In order to maintain the symbol table during the traversal, we can try to keep track of the local bindings ourselves, only to discover that it’s not that trivial, and that we’re replicating a large part of the resolution code.&lt;/p&gt;
&lt;p&gt;The core of the problem is that the name resolution algorithm is one big-step tree traversal, and we can only observe its final result (or a trace of its execution in the form of annotations).&lt;/p&gt;
&lt;p&gt;If we could split it up into small-step, one layer at a time, resolution functions, we could use them in our own traversals and interleave them with transformations. Another name for this approach is &lt;em&gt;open recursion&lt;/em&gt;, hence the article’s title.&lt;/p&gt;
&lt;h3 id="single-sorted-ast"&gt;Single-sorted AST&lt;/h3&gt;
&lt;p&gt;If our AST is a single recursive data type (parameterised by the annotation type)&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;type&lt;/span&gt; &lt;span class="dt"&gt;VarName&lt;/span&gt; &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;String&lt;/span&gt;

&lt;span class="kw"&gt;data&lt;/span&gt; &lt;span class="dt"&gt;Exp&lt;/span&gt; a
  &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Var&lt;/span&gt; a &lt;span class="dt"&gt;VarName&lt;/span&gt;
  &lt;span class="fu"&gt;|&lt;/span&gt; &lt;span class="dt"&gt;App&lt;/span&gt; a (&lt;span class="dt"&gt;Exp&lt;/span&gt; a) (&lt;span class="dt"&gt;Exp&lt;/span&gt; a)
  &lt;span class="fu"&gt;|&lt;/span&gt; &lt;span class="dt"&gt;Lambda&lt;/span&gt; a &lt;span class="dt"&gt;VarName&lt;/span&gt; (&lt;span class="dt"&gt;Exp&lt;/span&gt; a)

&lt;span class="kw"&gt;type&lt;/span&gt; &lt;span class="dt"&gt;SymbolTable&lt;/span&gt; a &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Map.Map&lt;/span&gt; &lt;span class="dt"&gt;VarName&lt;/span&gt; a&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;then such a small-step resolution function would have type&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;resolve
&lt;span class="ot"&gt;  ::&lt;/span&gt; (&lt;span class="dt"&gt;SymbolTable&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Exp&lt;/span&gt; &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Exp&lt;/span&gt;)
  &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt;  &lt;span class="dt"&gt;SymbolTable&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Exp&lt;/span&gt; &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Exp&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It takes an expression, the symbol table (or &lt;em&gt;environment&lt;/em&gt;) that corresponds to the enclosing lexical context of that expression, and a transformation function. It then applies the transformation to all immediate children of the expression.&lt;/p&gt;
&lt;p&gt;Note that the transformation function is in turn parameterised by the symbol table. It is the responsibility of &lt;code&gt;resolve&lt;/code&gt; to update the symbol table accordingly before using it to transform the children.&lt;/p&gt;
&lt;p&gt;An implementation of &lt;code&gt;resolve&lt;/code&gt; might look like this&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;resolve f tbl e &lt;span class="fu"&gt;=&lt;/span&gt;
  &lt;span class="kw"&gt;case&lt;/span&gt; e &lt;span class="kw"&gt;of&lt;/span&gt;
    &lt;span class="dt"&gt;Var&lt;/span&gt; l n &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Var&lt;/span&gt; l n
    &lt;span class="dt"&gt;App&lt;/span&gt; l e1 e2 &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;App&lt;/span&gt; l (f tbl e1) (f tbl e2)
    &lt;span class="dt"&gt;Lambda&lt;/span&gt; l n body &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Lambda&lt;/span&gt; l n (f (Map.insert n l tbl) body)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now that we have &lt;code&gt;resolve&lt;/code&gt;, it is easy to tie the knot and write the big-step recursive traversal:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="ot"&gt;resolveRec ::&lt;/span&gt; &lt;span class="dt"&gt;Exp&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Exp&lt;/span&gt; a
resolveRec &lt;span class="fu"&gt;=&lt;/span&gt; fix resolve Map.empty&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;resolveRec&lt;/code&gt; doesn’t do anything interesting — it’s an identity function. But we can compose &lt;code&gt;resolve&lt;/code&gt; with an interesting transformation before “closing” the recursion:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;annotate
&lt;span class="ot"&gt;  ::&lt;/span&gt; (&lt;span class="dt"&gt;SymbolTable&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Exp&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Exp&lt;/span&gt; a)
  &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt;  &lt;span class="dt"&gt;SymbolTable&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Exp&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Exp&lt;/span&gt; a
annotate f tbl e &lt;span class="fu"&gt;=&lt;/span&gt;
  &lt;span class="kw"&gt;case&lt;/span&gt; e &lt;span class="kw"&gt;of&lt;/span&gt;
    &lt;span class="dt"&gt;Var&lt;/span&gt; _ n &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; f tbl &lt;span class="fu"&gt;$&lt;/span&gt; &lt;span class="dt"&gt;Var&lt;/span&gt; (tbl &lt;span class="fu"&gt;Map.!&lt;/span&gt; n) n
    _ &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; f tbl e

&lt;span class="ot"&gt;annotateRec ::&lt;/span&gt; &lt;span class="dt"&gt;Exp&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Exp&lt;/span&gt; a
annotateRec &lt;span class="fu"&gt;=&lt;/span&gt; fix (resolve &lt;span class="fu"&gt;.&lt;/span&gt; annotate) Map.empty&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let’s try it out:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;*Main&amp;gt; annotateRec $ Lambda 1 &amp;quot;x&amp;quot; $ App 2 (Var 3 &amp;quot;x&amp;quot;) (Var 4 &amp;quot;x&amp;quot;)
Lambda 1 &amp;quot;x&amp;quot; (App 2 (Var 1 &amp;quot;x&amp;quot;) (Var 1 &amp;quot;x&amp;quot;))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Hence, the annotation interface to a name resolution library is easy to implement given the open recursion interface. But the open recursion interface is much more powerful, allowing the transformation function to depend on the lexical environment in non-trivial ways.&lt;/p&gt;
&lt;h3 id="multi-sorted-ast"&gt;Multi-sorted AST&lt;/h3&gt;
&lt;p&gt;What if our AST is represented by a multitude of mutually recursive data types, just like in &lt;a href="http://hackage.haskell.org/packages/archive/haskell-src-exts/1.13.5/doc/html/Language-Haskell-Exts-Annotated-Syntax.html"&gt;haskell-src-exts&lt;/a&gt;? Generic programming may help here — specifically, the “Scrap your boilerplate” approach.&lt;/p&gt;
&lt;p&gt;A stock library, such as syb-with-class, might go a long way, but let’s roll out our own. It will be simpler this way, but also more flexible (for example, it’s possible to modify this presentation to allow the traversal to change the annotation type).&lt;/p&gt;
&lt;p&gt;How does the type of &lt;code&gt;resolve&lt;/code&gt; change? It now has to work for any AST node type, rather than just for &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;Exp&lt;/span&gt;&lt;/code&gt;, i.e. be polymorphic. Furthermore, the functional argument to &lt;code&gt;resolve&lt;/code&gt;, which used to have type &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;SymbolTable&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Exp&lt;/span&gt; &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Exp&lt;/span&gt;&lt;/code&gt;, also has to be polymorphic, because the types of node’s children may be different (and may differ from the node’s type itself).&lt;/p&gt;
&lt;p&gt;To encode this polymorphism, one can use either a type class or a GADT sum type (see &lt;a href="http://stackoverflow.com/q/15160470/110081"&gt;this StackOverflow entry&lt;/a&gt; for comparison of these approaches).&lt;/p&gt;
&lt;p&gt;Although we are dealing with a finite, closed universe (consisting of haskell-src-exts node types) in this case, I prefer the class-based approach because it’s more practical — it doesn’t force us to define a giant GADT.&lt;/p&gt;
&lt;p&gt;Thus, &lt;code&gt;resolve&lt;/code&gt; now becomes a class method:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;class&lt;/span&gt; &lt;span class="dt"&gt;Typeable&lt;/span&gt; a &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Resolvable&lt;/span&gt; a &lt;span class="kw"&gt;where&lt;/span&gt;
  resolve
&lt;span class="ot"&gt;    ::&lt;/span&gt; (forall b &lt;span class="fu"&gt;.&lt;/span&gt; &lt;span class="dt"&gt;Resolvable&lt;/span&gt; b &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;SymbolTable&lt;/span&gt; &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; b &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; b)
    &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt;                             &lt;span class="dt"&gt;SymbolTable&lt;/span&gt; &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; a&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;Typeable&lt;/code&gt; superclass constraint is needed here so that we can write type-specific cases (such as &lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;case&lt;/span&gt;&lt;/code&gt; for &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;Var&lt;/span&gt;&lt;/code&gt; in the &lt;code&gt;annotate&lt;/code&gt; function).&lt;/p&gt;
&lt;p&gt;Otherwise, implementing and using this approach for a multi-sorted AST is quite similar to the single-sorted case.&lt;/p&gt;
&lt;h2 id="conclusions"&gt;Conclusions&lt;/h2&gt;
&lt;p&gt;The article argues that the open recursion approach to name resolution offers more power to the user and shows how to implement it.&lt;/p&gt;
&lt;p&gt;The presentation here is simplified for the sake of clarity. A full implementation would allow queries (folds), effectful traversals and traversal that can change the annotation type.&lt;/p&gt;
&lt;p&gt;For Haskell (and haskell-src-exts AST), I’ve just started implementing this idea in &lt;a href="https://github.com/feuerbach/haskell-names"&gt;haskell-names&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/RomanCheplyaka/~4/fbILOaP7j6s" height="1" width="1"/&gt;</description>
    <pubDate>Mon, 04 Mar 2013 00:00:00 UT</pubDate>
    <guid isPermaLink="false">http://ro-che.info//articles/2013-03-04-open-name-resolution.html</guid>
<feedburner:origLink>http://ro-che.info//articles/2013-03-04-open-name-resolution.html</feedburner:origLink></item>
<item>
    <title>Announcing SmallCheck 1.0</title>
    <link>http://feedproxy.google.com/~r/RomanCheplyaka/~3/rlj1PQ7yw6c/2013-02-19-smallcheck.html</link>
    <description>&lt;p&gt;I am glad to announce a new major release of SmallCheck (&lt;a href="http://hackage.haskell.org/package/smallcheck-1.0"&gt;hackage&lt;/a&gt;).&lt;/p&gt;
&lt;h2 id="what-is-smallcheck"&gt;What is SmallCheck?&lt;/h2&gt;
&lt;p&gt;&lt;a href="https://github.com/feuerbach/smallcheck"&gt;SmallCheck&lt;/a&gt; is a property-based testing library for Haskell.&lt;/p&gt;
&lt;p&gt;If you are familiar with QuickCheck, you can think of SmallCheck as a &lt;a href="https://github.com/feuerbach/smallcheck/wiki/Comparison-with-QuickCheck"&gt;better&lt;/a&gt; QuickCheck. The main way in which it is better is that it is non-random: whether your tests pass does not depend on the roll of the dice.&lt;/p&gt;
&lt;p&gt;If you are not familiar with QuickCheck, the idea of SmallCheck is to check certain &lt;em&gt;properties&lt;/em&gt; of your functions, as opposed to unit testing, where you just check the expected outcome of some particular tests.&lt;/p&gt;
&lt;p&gt;For an introduction to property-based testing, check out &lt;a href="http://book.realworldhaskell.org/read/testing-and-quality-assurance.html"&gt;Chapter 11&lt;/a&gt; of Real World Haskell. It should be straightforward to translate all the examples there to SmallCheck.&lt;/p&gt;
&lt;h2 id="whats-new-in-1.0"&gt;What’s new in 1.0&lt;/h2&gt;
&lt;h3 id="monadic-properties"&gt;Monadic properties&lt;/h3&gt;
&lt;p&gt;Properties are now parameterised on the monad they work in.&lt;/p&gt;
&lt;p&gt;The two main ways a property can use the monad are:&lt;/p&gt;
&lt;ol style="list-style-type: decimal"&gt;
&lt;li&gt;generating test cases monadically&lt;/li&gt;
&lt;li&gt;verifying the condition monadically&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Monadic test cases generation can be used to read test cases from files. A well-known problem when testing compilers is that it is hard to enumerate or randomly generate valid programs. So here you go — just put some examples in the file system, and use them to verify some properties of your compiler.&lt;/p&gt;
&lt;p&gt;An example of monadic verification is when you want to verify your code against an external (or otherwise impure) reference implementation.&lt;/p&gt;
&lt;h3 id="quantifiers"&gt;Quantifiers&lt;/h3&gt;
&lt;p&gt;The semantics of quantifiers has changed. Previously, all variables were quantified universally by default, and a quantifier (like &lt;code&gt;exists&lt;/code&gt;) changed the quantification of the next variable.&lt;/p&gt;
&lt;p&gt;So, for example, &lt;code&gt;exists $ \x y -&amp;gt; p x y&lt;/code&gt; was interpreted as &lt;span class="math"&gt;\(\exists x: \forall y. p\ x\ y\)&lt;/span&gt;, which is probably not what one would expect.&lt;/p&gt;
&lt;p&gt;Now the quantification operators (&lt;code&gt;forAll&lt;/code&gt;, &lt;code&gt;exists&lt;/code&gt; and &lt;code&gt;existsUnique&lt;/code&gt;) set the quantification context for all subsequent variables, so the above property means &lt;span class="math"&gt;\(\exists x, y: p\ x\ y\)&lt;/span&gt;.&lt;/p&gt;
&lt;h4 id="uniqueness-quantification"&gt;Uniqueness quantification&lt;/h4&gt;
&lt;p&gt;There’s an interesting effect related to the uniqueness quantifier &lt;code&gt;existsUnique&lt;/code&gt; (which was previously called &lt;code&gt;exists1&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;There are two ways to interpret &lt;code&gt;existsUnique $ \x y -&amp;gt; p x y&lt;/code&gt;, “curried” and “uncurried”:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class="math"&gt;\(\exists ! x: \exists ! y: p\ x\ y\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class="math"&gt;\(\exists ! (x,y): p\ x\ y\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These two actually have different meaning. Suppose that &lt;span class="math"&gt;\(p\ x\ y=(|x|=|y|)\)&lt;/span&gt;, where &lt;span class="math"&gt;\(|x|\)&lt;/span&gt; denotes the absolute value of an integer &lt;span class="math"&gt;\(x\)&lt;/span&gt;. Then the first property above is true, and the second is false (be sure to check this yourself).&lt;/p&gt;
&lt;p&gt;When mathematicians write &lt;span class="math"&gt;\(\exists ! x,y:p\ x\ y\)&lt;/span&gt;, they really mean the second interpretation, so this is what SmallCheck implements (although the first interpretation would be much easier to implement).&lt;/p&gt;
&lt;h3 id="higher-order-properties"&gt;Higher-order properties&lt;/h3&gt;
&lt;p&gt;Both SmallCheck and QuickCheck have a &lt;code&gt;==&amp;gt;&lt;/code&gt; operator, which tests an implication. The left argument of &lt;code&gt;==&amp;gt;&lt;/code&gt; has type &lt;code&gt;Bool&lt;/code&gt;, and it’s usually a statement that the generated arguments satisfy some side condition (e.g. generated programs are valid).&lt;/p&gt;
&lt;p&gt;In this new version of SmallCheck, the left argument of &lt;code&gt;==&amp;gt;&lt;/code&gt; can be an arbitrary property, with its own quantifiers etc. Here’s how we could test an &lt;code&gt;isPrime&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;import&lt;/span&gt; &lt;span class="dt"&gt;Test.SmallCheck&lt;/span&gt;
&lt;span class="kw"&gt;import&lt;/span&gt; &lt;span class="dt"&gt;Test.SmallCheck.Series&lt;/span&gt;

&lt;span class="ot"&gt;isPrime ::&lt;/span&gt; &lt;span class="dt"&gt;Integer&lt;/span&gt; &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Bool&lt;/span&gt;
isPrime _ &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="kw"&gt;True&lt;/span&gt;

main &lt;span class="fu"&gt;=&lt;/span&gt; 
  smallCheck &lt;span class="dv"&gt;5&lt;/span&gt; &lt;span class="co"&gt;{- 5 is the testing depth -}&lt;/span&gt; &lt;span class="fu"&gt;$&lt;/span&gt;
    \(&lt;span class="dt"&gt;Positive&lt;/span&gt; n) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt;
      (exists &lt;span class="fu"&gt;$&lt;/span&gt; \(&lt;span class="dt"&gt;Positive&lt;/span&gt; d) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; d &lt;span class="fu"&gt;/=&lt;/span&gt; &lt;span class="dv"&gt;1&lt;/span&gt; &lt;span class="fu"&gt;&amp;amp;&amp;amp;&lt;/span&gt; d &lt;span class="fu"&gt;/=&lt;/span&gt; n &lt;span class="fu"&gt;&amp;amp;&amp;amp;&lt;/span&gt; n &lt;span class="ot"&gt;`mod`&lt;/span&gt; d &lt;span class="fu"&gt;==&lt;/span&gt; &lt;span class="dv"&gt;0&lt;/span&gt;) &lt;span class="fu"&gt;==&amp;gt;&lt;/span&gt; &lt;span class="fu"&gt;not&lt;/span&gt; (isPrime n)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Unsurprisingly, the result will be&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Failed test no. 4.
there exists 4 such that
  condition is false&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id="ordered-testing"&gt;Ordered testing&lt;/h3&gt;
&lt;p&gt;SmallCheck has just got more efficient and less annoying!&lt;/p&gt;
&lt;p&gt;Previously, if you wanted to get the &lt;em&gt;minimal&lt;/em&gt; counterexample, you used the function &lt;code&gt;smallCheck&lt;/code&gt; which tested the property first with depth 0, then with depth 1 and so on — up to the limit that you told it.&lt;/p&gt;
&lt;p&gt;The reason was that the &lt;code&gt;Serial&lt;/code&gt; instance of e.g. &lt;code&gt;Integer&lt;/code&gt; generated the following integers for depth &lt;code&gt;3&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[-3,-2,-1,0,1,2,3]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;They are tried in exactly this order, and, if all of them were counterexamples, the user would be presented with &lt;code&gt;-3&lt;/code&gt; as the first one.&lt;/p&gt;
&lt;p&gt;Now the instances generate examples in the order of increasing depth, e.g.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[0,1,-1,2,-2,3,-3]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;so there’s no need to try multiple depths.&lt;/p&gt;
&lt;h3 id="better-reporting"&gt;Better reporting&lt;/h3&gt;
&lt;p&gt;The way SmallCheck reports its findings is now greatly improved, especially in some complex cases.&lt;/p&gt;
&lt;p&gt;For example, consider the following property:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;smallCheck &lt;span class="dv"&gt;5&lt;/span&gt; &lt;span class="fu"&gt;$&lt;/span&gt; existsUnique &lt;span class="fu"&gt;$&lt;/span&gt; \x &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; (forAll &lt;span class="fu"&gt;$&lt;/span&gt; \y &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; x &lt;span class="fu"&gt;*&lt;/span&gt; y &lt;span class="fu"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="dv"&gt;0&lt;/span&gt;) &lt;span class="fu"&gt;==&amp;gt;&lt;/span&gt; (forAll &lt;span class="fu"&gt;$&lt;/span&gt; \y &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; x &lt;span class="fu"&gt;*&lt;/span&gt; y &lt;span class="fu"&gt;==&lt;/span&gt; (&lt;span class="dv"&gt;0&lt;/span&gt;&lt;span class="ot"&gt; ::&lt;/span&gt; &lt;span class="dt"&gt;Integer&lt;/span&gt;))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here’s what SmallCheck 0.6.2 reports (or, to be precise, &lt;em&gt;would&lt;/em&gt; report if it supported higher-order properties):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Depth 0:
  Completed 1 test(s) without failure.
Depth 1:
  Failed test no. 12. Test values follow.
  non-uniqueness
  -1
  0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And this is the output of SmallCheck 1.0:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Failed test no. 12.
there are at least two arguments satisfying the property:
  for 0
    condition is true
  for 1
    property is vacuously true because
      there exists -1 such that
        condition is false&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id="required-type-annotations"&gt;Required type annotations&lt;/h3&gt;
&lt;p&gt;Because the &lt;code&gt;Testable&lt;/code&gt; class is now multi-parameter (parameterised on the type and the monad), ambiguous types that involve this class do not get defaulted. To put it simply, most non-trivial properties now require some type annotations.&lt;/p&gt;
&lt;p&gt;This turned out to be a very good thing for SmallCheck (which I couldn’t envision). Defaulting for properties often works in an unexpected way. For example, here’s what an older SmallCheck would tell you if you asked it whether all things are the equal:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;gt; depthCheck 5 $ \x y -&amp;gt; x == y
Depth 5:
  Completed 1 test(s) without failure.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The result is unexpected, but at least we get some clue from the fact that there was just one test: the type of the variables got defaulted to &lt;code&gt;()&lt;/code&gt;!&lt;/p&gt;
&lt;p&gt;Alas, QuickCheck doesn’t give us even this hint:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;gt; quickCheck $ \x y -&amp;gt; x == y
+++ OK, passed 100 tests.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Luckily, with the new SmallCheck you actually get a type error:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;interactive&amp;gt;:10:26:
    No instance for (Eq a0) arising from a use of `==&amp;#39;
    The type variable `a0&amp;#39; is ambiguous
    Possible fix: add a type signature that fixes these type variable(s)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And indeed, the problem is easy to fix once you know it’s there:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;gt; smallCheck 5 $ \x y -&amp;gt; x == (y :: Integer)
Failed test no. 2.
there exist 0 1 such that
  condition is false&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id="simpler-interface"&gt;Simpler interface&lt;/h3&gt;
&lt;p&gt;I took this chance to clean the API and make it more orthogonal.&lt;/p&gt;
&lt;p&gt;Previously SmallCheck had functions like&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="ot"&gt;forAllElem ::&lt;/span&gt; (&lt;span class="kw"&gt;Show&lt;/span&gt; a, &lt;span class="dt"&gt;Testable&lt;/span&gt; b) &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; [a] &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; (a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; b) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Property&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;which did three things at once:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;made the variable universally quantified&lt;/li&gt;
&lt;li&gt;converted the list to a depth-independent series&lt;/li&gt;
&lt;li&gt;quantified the variable over that series&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;No wonder the API suffered from the combinatorial explosion. Now these things are all done separately:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="ot"&gt;generate ::&lt;/span&gt; (&lt;span class="dt"&gt;Depth&lt;/span&gt; &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; [a]) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Series&lt;/span&gt; m a&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;can be used to turn a list into a series;&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="ot"&gt;over ::&lt;/span&gt; (&lt;span class="kw"&gt;Monad&lt;/span&gt; m, &lt;span class="kw"&gt;Show&lt;/span&gt; a, &lt;span class="dt"&gt;Testable&lt;/span&gt; m b) &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Series&lt;/span&gt; m a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; (a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; b) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Property&lt;/span&gt; m&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;sets the domain of quantification; and&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="ot"&gt;forAll ::&lt;/span&gt; &lt;span class="dt"&gt;Testable&lt;/span&gt; m a &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Property&lt;/span&gt; m&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;sets the quantification context.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/RomanCheplyaka/~4/rlj1PQ7yw6c" height="1" width="1"/&gt;</description>
    <pubDate>Tue, 19 Feb 2013 00:00:00 UT</pubDate>
    <guid isPermaLink="false">http://ro-che.info//articles/2013-02-19-smallcheck.html</guid>
<feedburner:origLink>http://ro-che.info//articles/2013-02-19-smallcheck.html</feedburner:origLink></item>
<item>
    <title>Generic uncurry</title>
    <link>http://feedproxy.google.com/~r/RomanCheplyaka/~3/rXe-HQt1qOc/2013-01-29-generic-uncurry.html</link>
    <description>&lt;p&gt;For the next version of &lt;a href="https://github.com/feuerbach/smallcheck"&gt;SmallCheck&lt;/a&gt; I needed a generic uncurry function in Haskell. To my surprise, I couldn’t google anything simple and ready to use.&lt;/p&gt;
&lt;p&gt;So here it is, for future reference.&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="ot"&gt;{-# LANGUAGE TypeFamilies, DefaultSignatures, UndecidableInstances #-}&lt;/span&gt;
&lt;span class="kw"&gt;class&lt;/span&gt; &lt;span class="dt"&gt;Uncurry&lt;/span&gt; a &lt;span class="kw"&gt;where&lt;/span&gt;
  &lt;span class="kw"&gt;type&lt;/span&gt; &lt;span class="dt"&gt;Uncurried1&lt;/span&gt; b a
  &lt;span class="kw"&gt;type&lt;/span&gt; &lt;span class="dt"&gt;Uncurried1&lt;/span&gt; b a &lt;span class="fu"&gt;=&lt;/span&gt; b &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; a

&lt;span class="ot"&gt;  unc1 ::&lt;/span&gt; (b &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; a) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Uncurried1&lt;/span&gt; b a
  default&lt;span class="ot"&gt; unc1 ::&lt;/span&gt; (b &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; a) &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; (b &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; a)
  unc1 &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="fu"&gt;id&lt;/span&gt;

  &lt;span class="kw"&gt;type&lt;/span&gt; &lt;span class="dt"&gt;Uncurried&lt;/span&gt; a
  &lt;span class="kw"&gt;type&lt;/span&gt; &lt;span class="dt"&gt;Uncurried&lt;/span&gt; a &lt;span class="fu"&gt;=&lt;/span&gt; a

&lt;span class="ot"&gt;  unc ::&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Uncurried&lt;/span&gt; a
  default&lt;span class="ot"&gt; unc ::&lt;/span&gt; a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; a
  unc &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="fu"&gt;id&lt;/span&gt;

&lt;span class="kw"&gt;instance&lt;/span&gt; &lt;span class="dt"&gt;Uncurry&lt;/span&gt; y &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Uncurry&lt;/span&gt; (x &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; y) &lt;span class="kw"&gt;where&lt;/span&gt;
  &lt;span class="kw"&gt;type&lt;/span&gt; &lt;span class="dt"&gt;Uncurried1&lt;/span&gt; z (x &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; y) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Uncurried1&lt;/span&gt; (z, x) y
  unc1 &lt;span class="fu"&gt;=&lt;/span&gt; unc1 &lt;span class="fu"&gt;.&lt;/span&gt; &lt;span class="fu"&gt;uncurry&lt;/span&gt;

  &lt;span class="kw"&gt;type&lt;/span&gt; &lt;span class="dt"&gt;Uncurried&lt;/span&gt; (x &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; y) &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;Uncurried1&lt;/span&gt; x y
  unc &lt;span class="fu"&gt;=&lt;/span&gt; unc1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You also need to make the final type an instance of &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;Uncurry&lt;/span&gt;&lt;/code&gt;. For example, if you need to uncurry &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;Int&lt;/span&gt; &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Bool&lt;/span&gt; &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;Double&lt;/span&gt;&lt;/code&gt;, &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;Double&lt;/span&gt;&lt;/code&gt; has to be an instance of &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;Uncurry&lt;/span&gt;&lt;/code&gt;. But thanks to &lt;a href="http://www.haskell.org/ghc/docs/7.6.2/html/users_guide/type-class-extensions.html#class-default-signatures"&gt;default method signatures&lt;/a&gt; and &lt;a href="http://www.haskell.org/ghc/docs/7.6.2/html/users_guide/type-families.html#assoc-decl-defs"&gt;associated type synonym defaults&lt;/a&gt;, it is as easy as&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;instance&lt;/span&gt; &lt;span class="dt"&gt;Uncurry&lt;/span&gt; &lt;span class="dt"&gt;Double&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;Uncurry1&lt;/span&gt;&lt;/code&gt; and &lt;code&gt;unc1&lt;/code&gt; are implementation details. The useful parts are &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;Uncurry&lt;/span&gt;&lt;/code&gt;, which converts the type to its uncurried version, and &lt;code class="sourceCode haskell"&gt;unc&lt;/code&gt;, which uncurries the function itself.&lt;/p&gt;
&lt;p&gt;After loading the code in ghci, you can see that it works by:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;*Uncurry&amp;gt; :kind! Uncurried (Int -&amp;gt; Bool -&amp;gt; Char -&amp;gt; Double)
Uncurried (Int -&amp;gt; Bool -&amp;gt; Char -&amp;gt; Double) :: *
= ((Int, Bool), Char) -&amp;gt; Double

*Uncurry&amp;gt; :t unc $ \x y z -&amp;gt; (x + y * z :: Double)
unc $ \x y z -&amp;gt; (x + y * z :: Double)
  :: ((Double, Double), Double) -&amp;gt; Double

*Uncurry&amp;gt; unc (\x y z -&amp;gt; (x + y * z :: Double)) ((1,2),3)
7.0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I tested this with GHC 7.6, but I think it should work with GHC 7.4 as well.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/RomanCheplyaka/~4/rXe-HQt1qOc" height="1" width="1"/&gt;</description>
    <pubDate>Tue, 29 Jan 2013 00:00:00 UT</pubDate>
    <guid isPermaLink="false">http://ro-che.info//articles/2013-01-29-generic-uncurry.html</guid>
<feedburner:origLink>http://ro-che.info//articles/2013-01-29-generic-uncurry.html</feedburner:origLink></item>
<item>
    <title>Subtractable values are torsors</title>
    <link>http://feedproxy.google.com/~r/RomanCheplyaka/~3/sTtjq8i4caY/2013-01-08-torsors.html</link>
    <description>&lt;p&gt;A &lt;strong&gt;group&lt;/strong&gt; is an abstraction for things that can be «added» and «subtracted» (in some sense).&lt;/p&gt;
&lt;p&gt;Most of the groups that programmers deal with are numeric, although some interesting groups arise in &lt;a href="http://en.wikipedia.org/wiki/Rotation_group_SO(3)"&gt;graphics&lt;/a&gt; and &lt;a href="http://en.wikipedia.org/wiki/Elliptic_Curve_Cryptography"&gt;cryptography&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;If we only require that things can be added, but not subtracted, we get &lt;strong&gt;semigroups&lt;/strong&gt; and &lt;strong&gt;monoids&lt;/strong&gt; (the difference is that a monoid also has a «zero» element). These are plentiful, with applications ranging from &lt;a href="http://www.cis.upenn.edu/~byorgey/pub/monoid-pearl.pdf"&gt;diagrams&lt;/a&gt; to &lt;a href="http://jkff.info/articles/ire/"&gt;regular expressions&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The reason is, of course, that addition is very natural — we can consider any way to combine objects together an addition as soon as it is associative — while subtraction, the inverse of addition, often doesn’t make sense.&lt;/p&gt;
&lt;h2 id="dates"&gt;Dates&lt;/h2&gt;
&lt;p&gt;But there are also things that can be subtracted, but not added. The simplest example is dates. You can subtract two dates to get the time interval between them, but you cannot add two dates. It doesn’t make sense to ask what today plus tomorrow is. You could try to add the numeric values corresponding to the dates and convert the answer back to a date, but the result would depend on whether you count from the start of the Common Era, the Unix epoch, or something else.&lt;/p&gt;
&lt;p&gt;While adding two dates is not possible, it is possible to add a time interval to a date («five days from today»). This suggests that we should not confound dates and time intervals — they are different types of values.&lt;/p&gt;
&lt;p&gt;For example, in the Haskell &lt;a href="http://hackage.haskell.org/package/time"&gt;time&lt;/a&gt; package, there are types &lt;a href="http://hackage.haskell.org/packages/archive/time/1.4.0.2/doc/html/Data-Time-Clock.html#t:UTCTime"&gt;UTCTime&lt;/a&gt; and &lt;a href="http://hackage.haskell.org/packages/archive/time/1.4.0.2/doc/html/Data-Time-Clock.html#t:NominalDiffTime"&gt;NominalDiffTime&lt;/a&gt;, and the following functions:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="ot"&gt;addUTCTime ::&lt;/span&gt; &lt;span class="dt"&gt;NominalDiffTime&lt;/span&gt; &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;UTCTime&lt;/span&gt; &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;UTCTime&lt;/span&gt;
&lt;span class="ot"&gt;diffUTCTime ::&lt;/span&gt; &lt;span class="dt"&gt;UTCTime&lt;/span&gt; &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;UTCTime&lt;/span&gt; &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;NominalDiffTime&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Time intervals can also be added and subtracted, as witnessed by the &lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;Num&lt;/span&gt; &lt;span class="dt"&gt;NominalDiffTime&lt;/span&gt;&lt;/code&gt; instance.&lt;/p&gt;
&lt;h2 id="ask-mathematics"&gt;Ask mathematics&lt;/h2&gt;
&lt;p&gt;What is the mathematical notion that characterizes dates? It should involve two sets: the set &lt;em&gt;V&lt;/em&gt; of values and the set &lt;em&gt;D&lt;/em&gt; of value differences.&lt;/p&gt;
&lt;p&gt;The set &lt;em&gt;D&lt;/em&gt; must form an additive group, so that we can add and subtract the differences. (The word «additive» means that we assume that the group operation, identity element and inverse operation are called &lt;em&gt;+&lt;/em&gt;, &lt;em&gt;0&lt;/em&gt; and &lt;em&gt;−&lt;/em&gt; respectively. In group theory it is more common to call them &lt;em&gt;*&lt;/em&gt;, &lt;em&gt;1&lt;/em&gt; and &lt;em&gt;⁻¹&lt;/em&gt;.)&lt;/p&gt;
&lt;p&gt;Thus we have the “zero” difference &lt;em&gt;0∈D&lt;/em&gt; and operations &lt;em&gt;+:D×D→D&lt;/em&gt;, &lt;em&gt;−:D→D&lt;/em&gt; which satisfy the usual group laws:&lt;/p&gt;
&lt;dl&gt;
&lt;dt&gt;&lt;em&gt;+/0&lt;/em&gt; (identity element)&lt;/dt&gt;
&lt;dd&gt;&lt;p&gt;&lt;em&gt;0+x=x+0=x&lt;/em&gt;&lt;/p&gt;
&lt;/dd&gt;
&lt;dt&gt;&lt;em&gt;+/+&lt;/em&gt; (associativity)&lt;/dt&gt;
&lt;dd&gt;&lt;p&gt;&lt;em&gt;(x+y)+z=x+(y+z)&lt;/em&gt;&lt;/p&gt;
&lt;/dd&gt;
&lt;dt&gt;&lt;em&gt;+/−&lt;/em&gt; (inverse element)&lt;/dt&gt;
&lt;dd&gt;&lt;p&gt;&lt;em&gt;x+(−x)=(−x)+x=0&lt;/em&gt;&lt;/p&gt;
&lt;/dd&gt;
&lt;/dl&gt;
&lt;p&gt;(We can write &lt;em&gt;x−y&lt;/em&gt; as a shorthand for &lt;em&gt;x+(−y)&lt;/em&gt;.)&lt;/p&gt;
&lt;p&gt;We do not require &lt;em&gt;+&lt;/em&gt; to be commutative to preserve generality, even though it is commutative for our current example.&lt;/p&gt;
&lt;p&gt;We need to be able to add a difference to a value. Thus, we need a function &lt;em&gt;add:D×V→V&lt;/em&gt;. We would expect it to play well with the group structure of &lt;em&gt;D&lt;/em&gt;:&lt;/p&gt;
&lt;dl&gt;
&lt;dt&gt;&lt;em&gt;add/0&lt;/em&gt;&lt;/dt&gt;
&lt;dd&gt;&lt;p&gt;&lt;em&gt;add(0,v)=v&lt;/em&gt;&lt;/p&gt;
&lt;/dd&gt;
&lt;dt&gt;&lt;em&gt;add/+&lt;/em&gt;&lt;/dt&gt;
&lt;dd&gt;&lt;p&gt;&lt;em&gt;add(x+y,v)=add(x,add(y,v))&lt;/em&gt;&lt;/p&gt;
&lt;/dd&gt;
&lt;/dl&gt;
&lt;p&gt;An alternative view on these laws is that the curried version of &lt;em&gt;add&lt;/em&gt;, &lt;em&gt;curry(add):D→(V→V)&lt;/em&gt;, is a group homomorphism from &lt;em&gt;D&lt;/em&gt; to the group of bijections on &lt;em&gt;V&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;The mathematical abstraction corresponding to our &lt;em&gt;add&lt;/em&gt; function is an &lt;a href="http://en.wikipedia.org/wiki/Group_action"&gt;&lt;strong&gt;action&lt;/strong&gt;&lt;/a&gt; of group &lt;em&gt;D&lt;/em&gt; on the set &lt;em&gt;V&lt;/em&gt;. But it doesn’t yet capture the fact that we can subtract two values to get a difference. For that we need a function &lt;em&gt;diff:V×V→D&lt;/em&gt; inverse to &lt;em&gt;add&lt;/em&gt;:&lt;/p&gt;
&lt;dl&gt;
&lt;dt&gt;&lt;em&gt;diff/add&lt;/em&gt;&lt;/dt&gt;
&lt;dd&gt;&lt;p&gt;&lt;em&gt;diff(add(x,v),v)=x&lt;/em&gt;&lt;/p&gt;
&lt;/dd&gt;
&lt;dt&gt;&lt;em&gt;add/diff&lt;/em&gt;&lt;/dt&gt;
&lt;dd&gt;&lt;p&gt;&lt;em&gt;add(diff(u,v),v)=u&lt;/em&gt;&lt;/p&gt;
&lt;/dd&gt;
&lt;/dl&gt;
&lt;p&gt;If such a function exists, the set &lt;em&gt;V&lt;/em&gt; is called a &lt;strong&gt;torsor&lt;/strong&gt; over the group &lt;em&gt;D&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Thus, it is the mathematical notion of torsor that characterizes subtractable values.&lt;/p&gt;
&lt;p&gt;Conal Elliott &lt;a href="http://hackage.haskell.org/packages/archive/vector-space/latest/doc/html/Data-AffineSpace.html"&gt;defines&lt;/a&gt; torsors in Haskell under the name of affine spaces.&lt;/p&gt;
&lt;h2 id="other-examples"&gt;Other examples&lt;/h2&gt;
&lt;h3 id="points"&gt;Points&lt;/h3&gt;
&lt;p&gt;Another simple example of a torsor is points. In linear algebra we get used to conflating points and vectors, because we consider vectors originating at zero.&lt;/p&gt;
&lt;p&gt;But the geometrical intuition suggests that vectors do not have to be tied to zero. A vector is a directed segment which can be freely translated (shifted) on the plane (or in the space).&lt;/p&gt;
&lt;p&gt;We can subtract two points to get a vector from one point to another. We can add a vector to a point, by translating it so that its origin becomes the given point. The end point of the vector then becomes the result of addition.&lt;/p&gt;
&lt;p&gt;Vectors form an additive group, and points form a torsor over the vectors.&lt;/p&gt;
&lt;p&gt;Like with dates, results of torsor operations on points and vectors do not depend on (and do not require the existence of) a coordinate system, while the «sum» of two points will change if you change the origin.&lt;/p&gt;
&lt;h3 id="files"&gt;Files&lt;/h3&gt;
&lt;p&gt;There are also some examples that look very much like torsors, but do not satisfy all the laws.&lt;/p&gt;
&lt;p&gt;One of such examples is files. The difference of two files is what we call a patch, or a diff. We can diff two files and apply the resulting patch to a third file («cherry-picking»).&lt;/p&gt;
&lt;p&gt;Although patches do not form a group, they can be modelled as &lt;a href="http://www.math.ucla.edu/~jjacobson/patch-theory/patch-semigroups.pdf"&gt;inverse semigroups&lt;/a&gt;. This motivates us to consider &lt;a href="http://mysite.science.uottawa.ca/phofstra/semigrouptorsors.pdf"&gt;torsors based on inverse semigroups&lt;/a&gt; rather than on groups.&lt;/p&gt;
&lt;h3 id="haskell-dialects"&gt;Haskell dialects&lt;/h3&gt;
&lt;p&gt;Haskell dialects can be considered as a torsor-like structure over Haskell extensions. We can add extensions to languages, e.g. &lt;em&gt;add(RankNTypes+GADTs−MonomorphismRestriction, Haskell2010)&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;We can also subtract two languages to find out the difference between them in terms of extensions: &lt;em&gt;diff(Haskell2010, Haskell98)=DoAndIfThenElse+PatternGuards+ForeignFunctionInterface+EmptyDataDecls−NPlusKPatterns&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Extensions do not form a group. The easiest way to see that is to observe that extensions are idempotent, i.e. &lt;em&gt;X+X=X&lt;/em&gt; for any extension &lt;em&gt;X&lt;/em&gt;. However, in a group there is only one idempotent element — zero.&lt;/p&gt;
&lt;p&gt;Extensions do form an inverse semigroup, though. Thus we again arrive at inverse semigroup torsors.&lt;/p&gt;
&lt;h2 id="acknowledgements"&gt;Acknowledgements&lt;/h2&gt;
&lt;p&gt;A recent discussion with &lt;a href="http://www.nbroberg.se/"&gt;Niklas Broberg&lt;/a&gt; about Haskell extensions motivated me to explore these concepts. His &lt;a href="http://www.youtube.com/watch?v=MoxqBGaTmWQ"&gt;HIW’12 lightning talk&lt;/a&gt; on Haskell Modular Mindset is also relevant.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://oleksandrmanzyuk.wordpress.com/"&gt;Oleksandr Manzyuk&lt;/a&gt; kindly pointed me to the concept of a torsor.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/RomanCheplyaka/~4/sTtjq8i4caY" height="1" width="1"/&gt;</description>
    <pubDate>Tue, 08 Jan 2013 00:00:00 UT</pubDate>
    <guid isPermaLink="false">http://ro-che.info//articles/2013-01-08-torsors.html</guid>
<feedburner:origLink>http://ro-che.info//articles/2013-01-08-torsors.html</feedburner:origLink></item>
<item>
    <title>Monads in dynamic languages</title>
    <link>http://feedproxy.google.com/~r/RomanCheplyaka/~3/baJ6tXmXAFk/2012-12-26-monads-in-dynamic-languages.html</link>
    <description>&lt;p&gt;Are monads possible outside of Haskell?&lt;/p&gt;
&lt;p&gt;Of course, it depends on what you call a monad.&lt;/p&gt;
&lt;p&gt;The definition that is usually accepted in the Haskell context — that a monad is an instance of the particular type constructor class, &lt;code&gt;Monad&lt;/code&gt;, with two methods satisfying three laws — is very much tied to Haskell’s language features — most importantly, types, type constructors and type constructor classes. Hence, this or similar notion of monad can only exist in a language rather close to Haskell.&lt;/p&gt;
&lt;p&gt;If we drop the type constructor class requirement, then a monad is a triple consisting of a type constructor &lt;code&gt;M&lt;/code&gt; and two polymorphic functions&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;return :: forall a . a -&amp;gt; M a
(&amp;gt;&amp;gt;=) :: forall a b . M a -&amp;gt; (a -&amp;gt; M b) -&amp;gt; M b&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is the definition originally used by Wadler in &lt;a href="http://homepages.inf.ed.ac.uk/wadler/papers/essence/essence.ps"&gt;The essence of functional programming&lt;/a&gt;. By this definition, Monads can be implemented in other Hindley-Milner based languages, like Miranda and &lt;a href="http://existentialtype.wordpress.com/2011/05/01/of-course-ml-has-monads/"&gt;ML&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;But what if we take this to extreme? What if we consider a dynamically typed functional language?&lt;/p&gt;
&lt;p&gt;A dynamically typed language is &lt;a href="http://existentialtype.wordpress.com/2011/03/19/dynamic-languages-are-static-languages/"&gt;nothing else than a static language&lt;/a&gt; with a single type, which we shall call here &lt;code&gt;U&lt;/code&gt;. Thus, the signatures of &lt;code&gt;&amp;gt;&amp;gt;=&lt;/code&gt; and &lt;code&gt;return&lt;/code&gt; become&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;return :: U -&amp;gt; U
(&amp;gt;&amp;gt;=) :: U -&amp;gt; (U -&amp;gt; U) -&amp;gt; U&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;(We could as well say that &lt;code&gt;&amp;gt;&amp;gt;=&lt;/code&gt; and &lt;code&gt;return&lt;/code&gt; both have type &lt;code&gt;U&lt;/code&gt; — remember, there’s only one type!) The functions themselves are still presumed to satisfy the usual laws.&lt;/p&gt;
&lt;p&gt;This has been done &lt;a href="http://lambda-the-ultimate.org/node/1136"&gt;many times&lt;/a&gt; before, most recent example being &lt;a href="http://www.youtube.com/watch?v=dkZFtimgAcM"&gt;Douglas Crockford’s keynote at YUIConf&lt;/a&gt;. Douglas’s presentation has received a lot of criticism (and I’m not going to defend him), but some critics even have expressed the doubt that these are not «genuine» monads.&lt;/p&gt;
&lt;p&gt;To settle this, let’s turn to the category theory — after all, that’s where monads come from. Haskell’s monads are category theory monads, where the type constructor is considered as an endofunctor on Hask, the category of Haskell types and functions.&lt;/p&gt;
&lt;p&gt;What changes when we go from Haskell to a unityped language is that all the diversity of Haskell types collapses into the single type, &lt;code&gt;U&lt;/code&gt;. That doesn’t stop it from forming a category, though. Because it has a single object, we don’t need a type constructor to represent the functorial action on objects — it’s always identity. We only need to know the functorial action on arrows (called &lt;code&gt;fmap&lt;/code&gt; in Haskell) — but it is already determined by &lt;code&gt;return&lt;/code&gt; and &lt;code&gt;&amp;gt;&amp;gt;=&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;To summarize, there doesn’t seem to be any reason to think that monads are somehow impossible in dynamic functional languages. And, although Haskellers usually consider monads as something closely tied to types, in a dynamic language all you need to define a monad is to define a pair of functions satisfying the monad laws.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/RomanCheplyaka/~4/baJ6tXmXAFk" height="1" width="1"/&gt;</description>
    <pubDate>Wed, 26 Dec 2012 00:00:00 UT</pubDate>
    <guid isPermaLink="false">http://ro-che.info//articles/2012-12-26-monads-in-dynamic-languages.html</guid>
<feedburner:origLink>http://ro-che.info//articles/2012-12-26-monads-in-dynamic-languages.html</feedburner:origLink></item>
<item>
    <title>Surprises of the Haskell module system (part 1)</title>
    <link>http://feedproxy.google.com/~r/RomanCheplyaka/~3/HUDE2pDIn6M/2012-12-25-haskell-module-system-p1.html</link>
    <description>&lt;p&gt;While basics of the Haskell module system are easy to understand, there are certainly interesting corner cases and non-obvious (mis)features. In this and the following articles we will explore some curious examples.&lt;/p&gt;
&lt;p&gt;All of these are documented in the &lt;a href="http://www.haskell.org/onlinereport/haskell2010/haskellch5.html"&gt;Haskell report&lt;/a&gt;, but the tricky details are hard to notice and recognize (although the reader is encouraged to read the report nevertheless!). Another good read on this subject is &lt;a href="http://web.cecs.pdx.edu/~mpj/pubs/hsmods.pdf"&gt;A Formal Specification for the Haskell 98 Module System&lt;/a&gt; by Iavor S. Diatchki, Mark P. Jones, and Thomas Hallgren.&lt;/p&gt;
&lt;h2 id="empty-module-header"&gt;Empty module header&lt;/h2&gt;
&lt;p&gt;What happens when the export list is omitted, like in the following example?&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;module&lt;/span&gt; &lt;span class="dt"&gt;M&lt;/span&gt; &lt;span class="kw"&gt;where&lt;/span&gt;

foo &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dv"&gt;42&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This one is easy — all the locally defined types, classes and values are exported.&lt;/p&gt;
&lt;p&gt;We might presume that something similar happens when we omit the module header entirely — like if we just put&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;foo &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dv"&gt;42&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;in a file by itself.&lt;/p&gt;
&lt;p&gt;Contrary to this intuition and according to the standard, when you omit the module header, it is assumed to be &lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;module&lt;/span&gt; &lt;span class="dt"&gt;Main&lt;/span&gt;(main) &lt;span class="kw"&gt;where&lt;/span&gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Sometimes you want to check whether some Haskell snippet compile. You may put it into a file and try &lt;code&gt;ghc test.hs&lt;/code&gt;. But even if the snippet itself doesn’t contain errors, you’ll get a message&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;test.hs:1:1: The function `main&amp;#39; is not defined in module `Main&amp;#39;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The message may seem confusing at first — what’s the module &lt;code&gt;Main&lt;/code&gt; it’s talking about, and why do I need this &lt;code&gt;main&lt;/code&gt; function? Well, above is the answer.&lt;/p&gt;
&lt;h2 id="module-re-exports"&gt;Module re-exports&lt;/h2&gt;
&lt;p&gt;You probably know that you can re-export a whole module from your own module. The syntax is&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;module&lt;/span&gt; &lt;span class="dt"&gt;M&lt;/span&gt; (&lt;span class="kw"&gt;module&lt;/span&gt; &lt;span class="dt"&gt;N&lt;/span&gt;) &lt;span class="kw"&gt;where&lt;/span&gt;
&lt;span class="fu"&gt;...&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The semantics of this re-export is a bit tricky, though. For example, what can we say about the following module?&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;module&lt;/span&gt; &lt;span class="dt"&gt;M&lt;/span&gt; (&lt;span class="kw"&gt;module&lt;/span&gt; &lt;span class="dt"&gt;Data.List&lt;/span&gt;) &lt;span class="kw"&gt;where&lt;/span&gt;
&lt;span class="kw"&gt;import&lt;/span&gt; &lt;span class="kw"&gt;qualified&lt;/span&gt; &lt;span class="dt"&gt;Data.List&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You’d probably think that module &lt;code&gt;M&lt;/code&gt; now export everything that is exported by &lt;code&gt;Data.List&lt;/code&gt;. Not at all! The standard says (emphasis is mine):&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The form &lt;code&gt;module M&lt;/code&gt; names the set of all entities that are in scope with &lt;em&gt;both&lt;/em&gt; an unqualified name &lt;code&gt;e&lt;/code&gt; and a qualified name &lt;code&gt;M.e&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Since we imported &lt;code&gt;Data.List&lt;/code&gt; qualified, nothing from it is in scope under an unqualified name. So, &lt;code&gt;M&lt;/code&gt; doesn’t export anything. Right? Not quite.&lt;/p&gt;
&lt;p&gt;The last thing we need to observe here is that although the single module imported by &lt;code&gt;M&lt;/code&gt; explicitly is &lt;code&gt;Data.List&lt;/code&gt;, there’s always an implicit import — &lt;code&gt;Prelude&lt;/code&gt;. And these two share quite a lot in common — functions like &lt;code&gt;foldr&lt;/code&gt;, &lt;code&gt;map&lt;/code&gt;, &lt;code&gt;length&lt;/code&gt; etc. All these satisfy the criterion above — they are in scope with both unqualified and qualified names, although these names come from different modules.&lt;/p&gt;
&lt;p&gt;To summarize, the module &lt;code&gt;M&lt;/code&gt; defined above will export exactly the intersection of &lt;code&gt;Prelude&lt;/code&gt; and &lt;code&gt;Data.List&lt;/code&gt;, plus instances exported by either of these modules.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/RomanCheplyaka/~4/HUDE2pDIn6M" height="1" width="1"/&gt;</description>
    <pubDate>Tue, 25 Dec 2012 00:00:00 UT</pubDate>
    <guid isPermaLink="false">http://ro-che.info//articles/2012-12-25-haskell-module-system-p1.html</guid>
<feedburner:origLink>http://ro-che.info//articles/2012-12-25-haskell-module-system-p1.html</feedburner:origLink></item>
<item>
    <title>Haskell recipe: reading list of lines</title>
    <link>http://feedproxy.google.com/~r/RomanCheplyaka/~3/NxgojfAaIuw/2012-10-25-reading-list-of-lines.html</link>
    <description>&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;import&lt;/span&gt; &lt;span class="dt"&gt;Prelude&lt;/span&gt; &lt;span class="kw"&gt;hiding&lt;/span&gt; (&lt;span class="fu"&gt;readList&lt;/span&gt;)
&lt;span class="kw"&gt;import&lt;/span&gt; &lt;span class="dt"&gt;Control.Applicative&lt;/span&gt;
&lt;span class="kw"&gt;import&lt;/span&gt; &lt;span class="dt"&gt;Control.Monad&lt;/span&gt;
&lt;span class="kw"&gt;import&lt;/span&gt; &lt;span class="dt"&gt;Control.Monad.Trans&lt;/span&gt;
&lt;span class="kw"&gt;import&lt;/span&gt; &lt;span class="dt"&gt;Control.Monad.Trans.Maybe&lt;/span&gt;
&lt;span class="kw"&gt;import&lt;/span&gt; &lt;span class="dt"&gt;Data.Maybe&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Suppose we need to ask the user to enter a list of lines, terminated by an empty line. The usual way to do it is through recursion:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="fu"&gt;readList&lt;/span&gt;&lt;span class="ot"&gt; ::&lt;/span&gt; &lt;span class="dt"&gt;IO&lt;/span&gt; [&lt;span class="dt"&gt;String&lt;/span&gt;]
&lt;span class="fu"&gt;readList&lt;/span&gt; &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="kw"&gt;do&lt;/span&gt;
  l &lt;span class="ot"&gt;&amp;lt;-&lt;/span&gt; &lt;span class="fu"&gt;getLine&lt;/span&gt;
  &lt;span class="kw"&gt;if&lt;/span&gt; &lt;span class="fu"&gt;null&lt;/span&gt; l
    &lt;span class="kw"&gt;then&lt;/span&gt; &lt;span class="fu"&gt;return&lt;/span&gt; []
    &lt;span class="kw"&gt;else&lt;/span&gt; (l &lt;span class="fu"&gt;:&lt;/span&gt;) &lt;span class="fu"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; &lt;span class="fu"&gt;readList&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is fine, but can we do better?&lt;/p&gt;
&lt;p&gt;A good style in Haskell is to replace explicit recursion with high-level recursion combinators where it is possible and doesn’t harm readability.&lt;/p&gt;
&lt;p&gt;What is the pattern here? Those who are familiar with parser combinator libraries will easily recognize the &lt;code&gt;many&lt;/code&gt; combinator. It tries to recognize as many items as possible and returns the list of recognized items (in this case successful recognition means that we got a non-empty line).&lt;/p&gt;
&lt;p&gt;A generalization of the &lt;code&gt;many&lt;/code&gt; combinator works for any applicative functor which is an instance of the &lt;code&gt;Alternative&lt;/code&gt; class:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="ot"&gt;many ::&lt;/span&gt; &lt;span class="dt"&gt;Alternative&lt;/span&gt; f &lt;span class="ot"&gt;=&amp;gt;&lt;/span&gt; f a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; f [a]&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;IO&lt;/code&gt; functor is not an instance of &lt;code&gt;Alternative&lt;/code&gt;, but we can fix it by layering a &lt;code&gt;MaybeT&lt;/code&gt; transformer on top of it. &lt;code&gt;MaybeT&lt;/code&gt; will be our means to distinguish failure from success.&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="fu"&gt;readList&lt;/span&gt;&lt;span class="ot"&gt; ::&lt;/span&gt; &lt;span class="dt"&gt;IO&lt;/span&gt; [&lt;span class="dt"&gt;String&lt;/span&gt;]
&lt;span class="fu"&gt;readList&lt;/span&gt; &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="fu"&gt;fmap&lt;/span&gt; (fromMaybe []) &lt;span class="fu"&gt;$&lt;/span&gt; runMaybeT &lt;span class="fu"&gt;$&lt;/span&gt; many &lt;span class="fu"&gt;$&lt;/span&gt; &lt;span class="kw"&gt;do&lt;/span&gt;
  l &lt;span class="ot"&gt;&amp;lt;-&lt;/span&gt; lift &lt;span class="fu"&gt;getLine&lt;/span&gt;
  guard &lt;span class="fu"&gt;$&lt;/span&gt; &lt;span class="fu"&gt;not&lt;/span&gt; &lt;span class="fu"&gt;$&lt;/span&gt; &lt;span class="fu"&gt;null&lt;/span&gt; l
  &lt;span class="fu"&gt;return&lt;/span&gt; l&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The inner &lt;code&gt;do&lt;/code&gt;-block is the code which reads one line, and, depending on whether that line is null, returns it or signals about the failure.&lt;/p&gt;
&lt;p&gt;Some more details about what’s going on there.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;lift getLine&lt;/code&gt; lifts &lt;code&gt;getLine&lt;/code&gt; from &lt;code&gt;IO String&lt;/code&gt; to &lt;code&gt;MaybeT IO String&lt;/code&gt; by assuming that it always succeeds (in &lt;code&gt;MaybeT&lt;/code&gt; sense).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;guard&lt;/code&gt; is a function from the &lt;code&gt;MonadZero&lt;/code&gt; class that checks the condition and, if it does not hold, declares failure. It is somewhat similar to an &lt;code&gt;assert&lt;/code&gt; function, except it is used for control flow rather than debugging purposes.&lt;/li&gt;
&lt;li&gt;Finally, if &lt;code&gt;guard&lt;/code&gt; did not abort the computation, we get to the last line that simply returns the line we’ve just read.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;(If you want to learn more about how monad transformers work, please refer to &lt;a href="http://ro-che.info/articles/2012-01-02-composing-monads.html"&gt;Composing monadic effects&lt;/a&gt;.)&lt;/p&gt;
&lt;p&gt;The outer code does boring stuff: &lt;code&gt;runMaybeT&lt;/code&gt; transforms &lt;code&gt;MaybeT IO String&lt;/code&gt; to &lt;code&gt;IO (Maybe String)&lt;/code&gt; (which is the same thing but &lt;code&gt;newtype&lt;/code&gt;d), and &lt;code&gt;fromMaybe&lt;/code&gt; interprets &lt;code&gt;Nothing&lt;/code&gt; as the empty list.&lt;/p&gt;
&lt;p&gt;It is interesting that only the first line of &lt;code&gt;readList&lt;/code&gt; definition gives us a hint that &lt;code&gt;MaybeT&lt;/code&gt; works here. The rest of the code just uses overloaded functions &lt;code&gt;many&lt;/code&gt;, &lt;code&gt;lift&lt;/code&gt;, &lt;code&gt;guard&lt;/code&gt; and &lt;code&gt;return&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Was the rewrite worth it? It is debatable, since a function did get a bit more complicated. But in my opinion, the answer is yes — we got rid of explicit recursion, and the idea of the function became more clear.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/RomanCheplyaka/~4/NxgojfAaIuw" height="1" width="1"/&gt;</description>
    <pubDate>Thu, 25 Oct 2012 00:00:00 UT</pubDate>
    <guid isPermaLink="false">http://ro-che.info//articles/2012-10-25-reading-list-of-lines.html</guid>
<feedburner:origLink>http://ro-che.info//articles/2012-10-25-reading-list-of-lines.html</feedburner:origLink></item>
<item>
    <title>Reasoning about space usage in Haskell</title>
    <link>http://feedproxy.google.com/~r/RomanCheplyaka/~3/mR-Q3pcLxTM/2012-04-08-space-usage-reasoning.html</link>
    <description>&lt;p&gt;This article describes why it’s hard to reason about space usage of Haskell programs.&lt;/p&gt;
&lt;h2 id="operational-semantics"&gt;Operational semantics&lt;/h2&gt;
&lt;p&gt;The standard (“The Haskell Report”) does not specify an operational semantics for Haskell. Thus, in order to talk about space usage of Haskell programs, we need to fix a particular semantics. A good choice is the STG semantics as defined in the &lt;a href="http://community.haskell.org/~simonmar/papers/evalapplyjfp06.pdf"&gt;fast curry paper&lt;/a&gt;. First, it is formally defined; second, it has significant practical value, since it is used in GHC, the de-facto standard Haskell compiler.&lt;/p&gt;
&lt;p&gt;Note, however, that the STG operational semantics is defined for STG programs, not Haskell programs (STG defines its own small functional language). It’s not always obvious what STG program corresponds to a given Haskell program because of numerous optimizations performed by the compiler, but GHC allows to see the resulting STG code using the &lt;code&gt;-ddump-stg&lt;/code&gt; flag.&lt;/p&gt;
&lt;h2 id="operational-properties-are-context-dependent"&gt;Operational properties are context-dependent&lt;/h2&gt;
&lt;p&gt;In eager languages, usually we can easily express time and space complexity, e.g. using O-notation.&lt;/p&gt;
&lt;p&gt;In Haskell, operational properties are largely context-dependent, and there’s no existing framework to express them.&lt;/p&gt;
&lt;h3 id="laziness"&gt;Laziness&lt;/h3&gt;
&lt;p&gt;One source of context dependency is a direct consequence of lazy evaluation: the function result may be evaluated to different extents by different callers.&lt;/p&gt;
&lt;p&gt;For example, it may seem that &lt;code&gt;[1..n]&lt;/code&gt; requires O(n) memory, but when called from &lt;code&gt;take m [1..n]&lt;/code&gt;, it takes only O(min(m,n)) memory.&lt;/p&gt;
&lt;h3 id="garbage-collection"&gt;Garbage collection&lt;/h3&gt;
&lt;p&gt;Another source of context dependency is interaction between laziness and automatic memory management.&lt;/p&gt;
&lt;p&gt;For example, the following two functions look equivalent in terms of space usage (although the second one is somewhat less time-efficient):&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;f1 list &lt;span class="fu"&gt;=&lt;/span&gt; foldl&amp;#39; (\(&lt;span class="fu"&gt;!&lt;/span&gt;a,&lt;span class="fu"&gt;!&lt;/span&gt;b) x &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; (a &lt;span class="fu"&gt;+&lt;/span&gt; x, b &lt;span class="fu"&gt;*&lt;/span&gt; x)) (&lt;span class="dv"&gt;0&lt;/span&gt;, &lt;span class="dv"&gt;1&lt;/span&gt;) list

f2 list &lt;span class="fu"&gt;=&lt;/span&gt; (foldl&amp;#39; (\a x &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; a &lt;span class="fu"&gt;+&lt;/span&gt; x) &lt;span class="dv"&gt;0&lt;/span&gt; list, foldl&amp;#39; (\b x &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; b &lt;span class="fu"&gt;*&lt;/span&gt; x) &lt;span class="dv"&gt;1&lt;/span&gt; list)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It would seem that these functions run in constant space. Of course, by “constant space” we really mean “constant additional space” – we do not count the space occupied by the list itself, because the function doesn’t create the list. Well, in a lazy language it does!&lt;/p&gt;
&lt;p&gt;The difference becomes clear if we consider &lt;code&gt;f1 [1..n]&lt;/code&gt; and &lt;code&gt;f2 [1..n]&lt;/code&gt;: the former indeed runs in constant space, while the latter requires linear space.&lt;/p&gt;
&lt;p&gt;The reason is that &lt;code&gt;f1&lt;/code&gt; can process the list incrementally. It demands the next value from the list, updates its accumulators and throws the value away.&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;f2&lt;/code&gt;, the first fold evaluates the list, but it has to be kept in memory to be used for the second fold. As a result, by the time the first fold is evaluated, the whole list is evaluated and none of it is garbage collected.&lt;/p&gt;
&lt;h3 id="thunks"&gt;Thunks&lt;/h3&gt;
&lt;p&gt;It’s not enough to track how much space our data occupies. Another kind of heap inhabitants is thunks. When more thunks are created than necessary, we have a &lt;a href="http://blog.ezyang.com/2011/05/anatomy-of-a-thunk-leak/"&gt;thunk leak&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;By the way, how many thunks may be necessary? Are there examples where having more than O(1) thunks at some point of program execution is the best solution to the problem? I don’t know yet.&lt;/p&gt;
&lt;p&gt;In any case, we need to be able to reason about the number of thunks that are created by a function.&lt;/p&gt;
&lt;p&gt;To complicate things further, creation of thunks depends on how the function result is evaluated. For example, a function returns a (lazy) tuple. We force the first element of that tuple. During the evaluation, everything that is needed to evaluate that first element is evaluated immediately, but values needed only for the second element are stored in thunks.&lt;/p&gt;
&lt;p&gt;If we evaluated the second element, the picture would be dual, and the number of thunks probably would be different.&lt;/p&gt;
&lt;h2 id="conclusions"&gt;Conclusions&lt;/h2&gt;
&lt;p&gt;Currently, if we want to reason about space usage of Haskell programs, we need:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;study the source code of each function. A function documentation typically includes its type, denotational semantics and perhaps some O-figures, but that’s not enough, as we’ve seen;&lt;/li&gt;
&lt;li&gt;for each function, understand how its result is evaluated by all callers.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Clearly, this breaks abstraction and modularity.&lt;/p&gt;
&lt;p&gt;In practice, GHC’s strictness analyser is very smart, so most of the time we don’t notice any problems. Still, it’s very important to have a framework in which we could analyse and document functions’ operational behaviour in a modular and composable way.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/RomanCheplyaka/~4/mR-Q3pcLxTM" height="1" width="1"/&gt;</description>
    <pubDate>Sun, 08 Apr 2012 00:00:00 UT</pubDate>
    <guid isPermaLink="false">http://ro-che.info//articles/2012-04-08-space-usage-reasoning.html</guid>
<feedburner:origLink>http://ro-che.info//articles/2012-04-08-space-usage-reasoning.html</feedburner:origLink></item>
<item>
    <title>Composing monadic effects</title>
    <link>http://feedproxy.google.com/~r/RomanCheplyaka/~3/en6d_Slkd5Y/2012-01-02-composing-monads.html</link>
    <description>&lt;p&gt;In Haskell, monad transformers are used to combine effects provided by multiple monads.&lt;/p&gt;
&lt;h2 id="boring-example-writer-reader-state"&gt;Boring example: Writer, Reader, State&lt;/h2&gt;
&lt;p&gt;For instance, if we want to have a read-only environment plus a write-only logging facility, we can start with the Reader monad and add a logging facility to it with the WriterT monad transformer:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;type&lt;/span&gt; &lt;span class="dt"&gt;MyMonad&lt;/span&gt; w r a &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;WriterT&lt;/span&gt; w (&lt;span class="dt"&gt;Reader&lt;/span&gt; r) a&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Or, we could start with the Writer monad and put the ReaderT transformer on top of it:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;type&lt;/span&gt; &lt;span class="dt"&gt;MyMonad&lt;/span&gt; w r a &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;ReaderT&lt;/span&gt; r (&lt;span class="dt"&gt;Writer&lt;/span&gt; w) a&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the end, it doesn’t matter which way we choose, as both are isomorphic to&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;type&lt;/span&gt; &lt;span class="dt"&gt;MyMonad&lt;/span&gt; w r a &lt;span class="fu"&gt;=&lt;/span&gt; r &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; (a, w)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If we want to have a state as well, we can plug in the StateT transformer anywhere in the stack, and again the order doesn’t matter. The resulting monad is now isomorphic to the standard &lt;a href="http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-RWS-Lazy.html"&gt;RWS&lt;/a&gt; (Reader-Writer-State) monad.&lt;/p&gt;
&lt;p&gt;So, we say about those transformers that they &lt;em&gt;commute&lt;/em&gt; (recall that Reader is just the ReaderT transformer applied to the Identity monad).&lt;/p&gt;
&lt;h2 id="more-interesting-example-either-writer"&gt;More interesting example: Either + Writer&lt;/h2&gt;
&lt;p&gt;Not every two transformers commute, though.&lt;/p&gt;
&lt;p&gt;Suppose we want to write log messages, plus to be able to abort the computation.&lt;/p&gt;
&lt;p&gt;There are two quite different ways to compose these effects.&lt;/p&gt;
&lt;p&gt;There’s&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;type&lt;/span&gt; &lt;span class="dt"&gt;MyMonad&lt;/span&gt; e w a &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;ErrorT&lt;/span&gt; e (&lt;span class="dt"&gt;Writer&lt;/span&gt; w) a&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;isomorphic to &lt;code class="sourceCode haskell"&gt;(&lt;span class="dt"&gt;Either&lt;/span&gt; e a, w)&lt;/code&gt;, and then there’s&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;type&lt;/span&gt; &lt;span class="dt"&gt;MyMonad&lt;/span&gt; e w a &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;WriterT&lt;/span&gt; w (&lt;span class="dt"&gt;Either&lt;/span&gt; e) a&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;isomorphic to &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;Either&lt;/span&gt; r (a, w)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;We can already see the difference from the types. In the first case, the &lt;code&gt;w&lt;/code&gt; is there independently of the value of &lt;code&gt;Either&lt;/code&gt;. In the second case, if the computation failed, the whole thing is &lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;Left&lt;/span&gt; msg&lt;/code&gt;, and we don’t get our log &lt;code&gt;w&lt;/code&gt; back.&lt;/p&gt;
&lt;p&gt;Let’s try the following to confirm our expectations:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="fu"&gt;&amp;gt;&lt;/span&gt; runWriter &lt;span class="fu"&gt;$&lt;/span&gt; runErrorT &lt;span class="fu"&gt;$&lt;/span&gt; tell &lt;span class="st"&gt;&amp;quot;foo&amp;quot;&lt;/span&gt; &lt;span class="fu"&gt;&amp;gt;&amp;gt;&lt;/span&gt; throwError &lt;span class="st"&gt;&amp;quot;err&amp;quot;&lt;/span&gt; &lt;span class="fu"&gt;&amp;gt;&amp;gt;&lt;/span&gt; tell &lt;span class="st"&gt;&amp;quot;bar&amp;quot;&lt;/span&gt;
(&lt;span class="kw"&gt;Left&lt;/span&gt; &lt;span class="st"&gt;&amp;quot;err&amp;quot;&lt;/span&gt;,&lt;span class="st"&gt;&amp;quot;foo&amp;quot;&lt;/span&gt;)
&lt;span class="fu"&gt;&amp;gt;&lt;/span&gt; runErrorT &lt;span class="fu"&gt;$&lt;/span&gt; runWriterT &lt;span class="fu"&gt;$&lt;/span&gt; tell &lt;span class="st"&gt;&amp;quot;foo&amp;quot;&lt;/span&gt; &lt;span class="fu"&gt;&amp;gt;&amp;gt;&lt;/span&gt; throwError &lt;span class="st"&gt;&amp;quot;err&amp;quot;&lt;/span&gt; &lt;span class="fu"&gt;&amp;gt;&amp;gt;&lt;/span&gt; tell &lt;span class="st"&gt;&amp;quot;bar&amp;quot;&lt;/span&gt;
&lt;span class="kw"&gt;Left&lt;/span&gt; &lt;span class="st"&gt;&amp;quot;err&amp;quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="developing-intuition"&gt;Developing intuition&lt;/h2&gt;
&lt;p&gt;When reasoning about a stack of monad transformers, it’s useful to keep in mind that a transformer knows nothing about its inner monad. It has to work “inside” that monad. It has no ability to alter or cancel the effects that happened before in that monad. (It can prevent those effects from happening, though – see &lt;code class="sourceCode haskell"&gt;tell &lt;span class="st"&gt;&amp;quot;bar&amp;quot;&lt;/span&gt;&lt;/code&gt; above.)&lt;/p&gt;
&lt;p&gt;In the first example above, which corresponds to &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;ErrorT&lt;/span&gt; e (&lt;span class="dt"&gt;Writer&lt;/span&gt; w)&lt;/code&gt;, the Error monad had to work inside the Writer monad. It simply had no way to tell the writer monad to “forget” what had been told to it before.&lt;/p&gt;
&lt;p&gt;In the second example, corresponding to &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;WriterT&lt;/span&gt; w (&lt;span class="dt"&gt;Either&lt;/span&gt; e) a&lt;/code&gt;, the main monad is now &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;Either&lt;/span&gt; e&lt;/code&gt;. If it decides to fail, it will return just the error, and nothing else.&lt;/p&gt;
&lt;p&gt;The same logic answers the question why there’s no &lt;code&gt;IOT&lt;/code&gt;, an IO monad transformer. Imagine this:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;do&lt;/span&gt;
    targetHit &lt;span class="ot"&gt;&amp;lt;-&lt;/span&gt; launchMissiles
    when targetHit &lt;span class="fu"&gt;$&lt;/span&gt;
        throwError &lt;span class="st"&gt;&amp;quot;oops I did it again&amp;quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Since &lt;code&gt;throwError&lt;/code&gt; happens in the base monad, the whole thing is just &lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;Left&lt;/span&gt; &lt;span class="st"&gt;&amp;quot;oops I did it again&amp;quot;&lt;/span&gt;&lt;/code&gt; – nothing mentions any IO. But what about the missiles?&lt;/p&gt;
&lt;p&gt;If this shallow explanation is not enough to make you comfortable with transformers, I’d advise to read (or even to write) the implementation of some standard transformers.&lt;/p&gt;
&lt;h2 id="even-more-interesting-example-parsec-state"&gt;Even more interesting example: Parsec + State&lt;/h2&gt;
&lt;p&gt;The Parsec monad already allows us to have &lt;a href="http://hackage.haskell.org/packages/archive/parsec/latest/doc/html/Text-Parsec-Prim.html#v:getState"&gt;our own state&lt;/a&gt;, but let’s see how we can add one independently.&lt;/p&gt;
&lt;p&gt;Again, we have two ways to layer ParsecT and StateT transformers on top of Identity: &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;ParsecT&lt;/span&gt; s () (&lt;span class="dt"&gt;State&lt;/span&gt; u) a&lt;/code&gt; and &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;StateT&lt;/span&gt; u (&lt;span class="dt"&gt;Parsec&lt;/span&gt; s ()) a&lt;/code&gt;. Is there a difference?&lt;/p&gt;
&lt;p&gt;Recall that Parsec is a backtracking monad. It can execute one branch, fail, and then execute another branch. Do we observe the state changes that happened in the aborted branch?&lt;/p&gt;
&lt;p&gt;This will be our test code:&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;((put &lt;span class="dv"&gt;1&lt;/span&gt; &lt;span class="fu"&gt;&amp;gt;&amp;gt;&lt;/span&gt; char &lt;span class="ch"&gt;&amp;#39;b&amp;#39;&lt;/span&gt;) &lt;span class="fu"&gt;&amp;lt;|&amp;gt;&lt;/span&gt; char &lt;span class="ch"&gt;&amp;#39;a&amp;#39;&lt;/span&gt;) &lt;span class="fu"&gt;&amp;gt;&amp;gt;&lt;/span&gt; get&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We’ll try to run it with the input &lt;code class="sourceCode haskell"&gt;&lt;span class="st"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;&lt;/code&gt; and initial state &lt;code class="sourceCode haskell"&gt;&lt;span class="dv"&gt;0&lt;/span&gt;&lt;/code&gt;. First, Parsec executes the left branch of &lt;code class="sourceCode haskell"&gt;&lt;span class="fu"&gt;&amp;lt;|&amp;gt;&lt;/span&gt;&lt;/code&gt;, fails, and proceeds with the right branch. If the state is “global”, then the final result will be &lt;code class="sourceCode haskell"&gt;&lt;span class="dv"&gt;1&lt;/span&gt;&lt;/code&gt;. If the state is subject to backtracking, then we’ll see &lt;code class="sourceCode haskell"&gt;&lt;span class="dv"&gt;0&lt;/span&gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;In the &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;ParsecT&lt;/span&gt; s () (&lt;span class="dt"&gt;State&lt;/span&gt; u) a&lt;/code&gt; case, the base monad is State. ParsecT works inside that monad and cannot revert the effects that happened there. (It may seem that it could remember the state of a branch using &lt;code&gt;get&lt;/code&gt; and then restore it using &lt;code&gt;put&lt;/code&gt;; but a monad transformer has to be polymorphic in the underlying monad and thus cannot rely on existence of &lt;code&gt;get&lt;/code&gt; and &lt;code&gt;put&lt;/code&gt;.)&lt;/p&gt;
&lt;p&gt;And indeed, the code&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;import&lt;/span&gt; &lt;span class="dt"&gt;Text.Parsec&lt;/span&gt;
&lt;span class="kw"&gt;import&lt;/span&gt; &lt;span class="dt"&gt;Control.Monad.State&lt;/span&gt;

main &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="fu"&gt;print&lt;/span&gt; &lt;span class="fu"&gt;$&lt;/span&gt; &lt;span class="fu"&gt;flip&lt;/span&gt; evalState &lt;span class="dv"&gt;0&lt;/span&gt; &lt;span class="fu"&gt;$&lt;/span&gt; runParserT p () &lt;span class="st"&gt;&amp;quot;-&amp;quot;&lt;/span&gt; &lt;span class="st"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;
    &lt;span class="kw"&gt;where&lt;/span&gt; p &lt;span class="fu"&gt;=&lt;/span&gt; ((put &lt;span class="dv"&gt;1&lt;/span&gt; &lt;span class="fu"&gt;&amp;gt;&amp;gt;&lt;/span&gt; char &lt;span class="ch"&gt;&amp;#39;b&amp;#39;&lt;/span&gt;) &lt;span class="fu"&gt;&amp;lt;|&amp;gt;&lt;/span&gt; char &lt;span class="ch"&gt;&amp;#39;a&amp;#39;&lt;/span&gt;) &lt;span class="fu"&gt;&amp;gt;&amp;gt;&lt;/span&gt; get&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;prints &lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;Right&lt;/span&gt; &lt;span class="dv"&gt;1&lt;/span&gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Let’s now try the second option: layering StateT on top of Parsec. We cannot use the code above as is, because types do not match: e.g. &lt;code class="sourceCode haskell"&gt;char &lt;span class="ch"&gt;&amp;#39;b&amp;#39;&lt;/span&gt;&lt;/code&gt; has type &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;Parsec&lt;/span&gt; s () &lt;span class="dt"&gt;Char&lt;/span&gt;&lt;/code&gt;, but we need &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;StateT&lt;/span&gt; u (&lt;span class="dt"&gt;Parsec&lt;/span&gt; s ()) &lt;span class="dt"&gt;Char&lt;/span&gt;&lt;/code&gt;. Such an upgrade is done by the &lt;code&gt;lift&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;Sometimes, however, we need to “downgrade” computations from &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;StateT&lt;/span&gt; u (&lt;span class="dt"&gt;Parsec&lt;/span&gt; s ()) a&lt;/code&gt; to &lt;code class="sourceCode haskell"&gt;&lt;span class="dt"&gt;Parsec&lt;/span&gt; s () a&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;For example, to implement a &lt;code class="sourceCode haskell"&gt;&lt;span class="fu"&gt;&amp;lt;|&amp;gt;&lt;/span&gt;&lt;/code&gt; operator of type&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="ot"&gt;(&amp;lt;|&amp;gt;) ::&lt;/span&gt; &lt;span class="dt"&gt;StateT&lt;/span&gt; u (&lt;span class="dt"&gt;Parsec&lt;/span&gt; s ()) a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;StateT&lt;/span&gt; u (&lt;span class="dt"&gt;Parsec&lt;/span&gt; s ()) a &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="dt"&gt;StateT&lt;/span&gt; u (&lt;span class="dt"&gt;Parsec&lt;/span&gt; s ()) a&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;we need first to downgrade the arguments to plain Parsec computation, invoke Parsec’s own &lt;code class="sourceCode haskell"&gt;&lt;span class="fu"&gt;&amp;lt;|&amp;gt;&lt;/span&gt;&lt;/code&gt; and then upgrade the result back to StateT.&lt;/p&gt;
&lt;pre class="sourceCode haskell"&gt;&lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;import&lt;/span&gt; &lt;span class="dt"&gt;Text.Parsec&lt;/span&gt; &lt;span class="kw"&gt;as&lt;/span&gt; &lt;span class="dt"&gt;P&lt;/span&gt;
&lt;span class="kw"&gt;import&lt;/span&gt; &lt;span class="dt"&gt;Control.Monad.State&lt;/span&gt;

main &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="fu"&gt;print&lt;/span&gt; &lt;span class="fu"&gt;$&lt;/span&gt; runParser (evalStateT p &lt;span class="dv"&gt;0&lt;/span&gt;) () &lt;span class="st"&gt;&amp;quot;-&amp;quot;&lt;/span&gt; &lt;span class="st"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;
  &lt;span class="kw"&gt;where&lt;/span&gt;
    p &lt;span class="fu"&gt;=&lt;/span&gt; ((put &lt;span class="dv"&gt;1&lt;/span&gt; &lt;span class="fu"&gt;&amp;gt;&amp;gt;&lt;/span&gt; char &lt;span class="ch"&gt;&amp;#39;b&amp;#39;&lt;/span&gt;) &lt;span class="fu"&gt;&amp;lt;|&amp;gt;&lt;/span&gt; char &lt;span class="ch"&gt;&amp;#39;a&amp;#39;&lt;/span&gt;) &lt;span class="fu"&gt;&amp;gt;&amp;gt;&lt;/span&gt; get

    char &lt;span class="fu"&gt;=&lt;/span&gt; lift &lt;span class="fu"&gt;.&lt;/span&gt; P.char

    a &lt;span class="fu"&gt;&amp;lt;|&amp;gt;&lt;/span&gt; b &lt;span class="fu"&gt;=&lt;/span&gt; &lt;span class="dt"&gt;StateT&lt;/span&gt; &lt;span class="fu"&gt;$&lt;/span&gt; \s &lt;span class="ot"&gt;-&amp;gt;&lt;/span&gt;
        runStateT a s &lt;span class="fu"&gt;P.&amp;lt;|&amp;gt;&lt;/span&gt; runStateT b s&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice how we explicitly run both branches of &lt;code class="sourceCode haskell"&gt;&lt;span class="fu"&gt;&amp;lt;|&amp;gt;&lt;/span&gt;&lt;/code&gt; with the same state. It’s no surprise now that the state will be “backtracked” and the result will be &lt;code class="sourceCode haskell"&gt;&lt;span class="kw"&gt;Right&lt;/span&gt; &lt;span class="dv"&gt;0&lt;/span&gt;&lt;/code&gt;. By the way, this is the same result as would be achieved using Parsec’s internal state.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/RomanCheplyaka/~4/en6d_Slkd5Y" height="1" width="1"/&gt;</description>
    <pubDate>Mon, 02 Jan 2012 00:00:00 UT</pubDate>
    <guid isPermaLink="false">http://ro-che.info//articles/2012-01-02-composing-monads.html</guid>
<feedburner:origLink>http://ro-che.info//articles/2012-01-02-composing-monads.html</feedburner:origLink></item>

    </channel> 
</rss>
