<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>LAMBDAPHONE &#187; data</title>
	<atom:link href="http://coder.bsimmons.name/blog/tag/data/feed/" rel="self" type="application/rss+xml" />
	<link>http://coder.bsimmons.name/blog</link>
	<description>fragmentary ideas  ䷿  intellectual what-nots  ䷷  and haskell programming  ䷴</description>
	<lastBuildDate>Sun, 29 Jan 2012 17:24:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>PEZ: the Potentially-Excellent Zipper library release</title>
		<link>http://coder.bsimmons.name/blog/2011/04/pez-zipper-library-released/</link>
		<comments>http://coder.bsimmons.name/blog/2011/04/pez-zipper-library-released/#comments</comments>
		<pubDate>Tue, 19 Apr 2011 20:07:35 +0000</pubDate>
		<dc:creator>jberryman</dc:creator>
				<category><![CDATA[haskell]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[release]]></category>
		<category><![CDATA[TypeSystem]]></category>
		<category><![CDATA[zipper]]></category>

		<guid isPermaLink="false">http://coder.bsimmons.name/blog/?p=554</guid>
		<description><![CDATA[<p>I&#8217;m happy to announce the release of a <a href="http://hackage.haskell.org/package/pez">zipper library I named <strong>PEZ</strong></a>! I&#8217;ve been learning and building this silly library almost as long as I&#8217;ve been learning haskell. It&#8217;s not as great as it could be, but I&#8217;m&#8230; <a href="http://coder.bsimmons.name/blog/2011/04/pez-zipper-library-released/" class="read_more">   [ R E A D &#124; M O R E ]</a></p>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m happy to announce the release of a <a href="http://hackage.haskell.org/package/pez">zipper library I named <strong>PEZ</strong></a>! I&#8217;ve been learning and building this silly library almost as long as I&#8217;ve been learning haskell. It&#8217;s not as great as it could be, but I&#8217;m releasing it now because it&#8217;s about time.</p>
<p>You can check it out with a:</p>
<blockquote><p><code>cabal install pez</code></p></blockquote>
<p>The library provides a generic <a href="http://www.haskell.org/haskellwiki/Zipper">zipper</a> that can be used on all types in the Typeable class, for which the user defines (or generates) lenses from the excellent <a href="http://hackage.haskell.org/package/fclabels">fclabels</a> package.</p>
<p>Since <code>Typeable</code> instances are deriveable in GHC and fclabels lenses can be generated with a line of TH code, this makes for a very pain-free and intuitive zipper. </p>
<p>The <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Typeable.html">Typeable class</a> gives us the ability to move up and down through complex mutually-recursive structures, even &#8220;down through&#8221; reversible computations!</p>
<p>The lenses from &#8216;fclabels&#8217; give us a way of referring to elements in data types in a way that is composable, allowing us to store our history as continuations and provide powerful mechanisms for &#8220;saving&#8221; a path through a data structure.</p>
<p>There is more to do: in particular I haven&#8217;t yet examined any of the performance characteristics of the approach I take, but please try it out and let me know how it works for you!</p>
]]></content:encoded>
			<wfw:commentRss>http://coder.bsimmons.name/blog/2011/04/pez-zipper-library-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A State Monad with dynamically-typed state</title>
		<link>http://coder.bsimmons.name/blog/2010/12/a-state-monad-with-dynamically-typed-state/</link>
		<comments>http://coder.bsimmons.name/blog/2010/12/a-state-monad-with-dynamically-typed-state/#comments</comments>
		<pubDate>Thu, 09 Dec 2010 22:56:49 +0000</pubDate>
		<dc:creator>jberryman</dc:creator>
				<category><![CDATA[haskell]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[state]]></category>
		<category><![CDATA[theory]]></category>
		<category><![CDATA[TypeSystem]]></category>

		<guid isPermaLink="false">http://coder.bsimmons.name/blog/?p=491</guid>
		<description><![CDATA[<p>Haskell&#8217;s <a href="http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-State-Lazy.html">standard State monad types</a> allow the programmer to define a computation that works with some state in a way that looks and feels similar to using mutable state in an imperative language. However these State monad types are&#8230; <a href="http://coder.bsimmons.name/blog/2010/12/a-state-monad-with-dynamically-typed-state/" class="read_more">   [ R E A D &#124; M O R E ]</a></p>]]></description>
			<content:encoded><![CDATA[<p>Haskell&#8217;s <a href="http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-State-Lazy.html">standard State monad types</a> allow the programmer to define a computation that works with some state in a way that looks and feels similar to using mutable state in an imperative language. However these State monad types are limited in that <em>the type of the state cannot change</em> during the computation.</p>
<p>Normally this is fine, but what if we really wanted to use the mechanics of a state monad to pass some state value that changed type, e.g. some mutually-recursive tree structure we would like to traverse?:<br />
<span id="more-491"></span><br />
<blockquote class="vimblock"><br />
<span class="Type">data</span>&nbsp;EvenBranch&nbsp;<span class="Statement">=</span>&nbsp;EBranch&nbsp;OddBranch&nbsp;Int&nbsp;OddBranch<br />
<br />
<span class="Type">data</span>&nbsp;OddBranch&nbsp;<span class="Statement">=</span>&nbsp;OBranch&nbsp;EvenBranch&nbsp;EvenBranch<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Statement">|</span>&nbsp;Nil<br />
<br /></blockquote></p>
<p>Well it turns out its not only possible, but relatively simple to use the existing MonadState types with something like a dynamically-typed state, thanks to a couple really fascinating standard Haskell libraries:</p>
<h2>Introducing <code>Typeable</code> and <code>Dynamic</code></h2>
<p>The first piece of the puzzle is the <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Typeable.html">Data.Typeable library</a>. The library provides polymorphic functions for extracting <em>type information</em> (in the form of a data type called a <code>TypeRep</code>) from any object in the <code>Typeable</code> type class.</p>
<p>Try this out:</p>
<blockquote><p>
<code>Prelude Data.Dynamic> :t typeOf</code><br />
<code>typeOf :: (Typeable a) => a -> TypeRep</code><br />
<code>Prelude Data.Dynamic> typeOf 1</code><br />
<code>Integer</code><br />
<code>Prelude Data.Dynamic> typeOf 1 == typeOf 'a'</code><br />
<code>False</code><br />
<code>Prelude Data.Dynamic> typeOf 1 == typeOf 2</code><br />
<code>True</code></p></blockquote>
<p>The magic of bringing bits of the abstract type system into the world of data is known as &#8220;reification&#8221;. </p>
<p>Typeable also provides a method of &#8220;casting&#8221; any Typeable value as a fixed type, in the Maybe monad. Observe:</p>
<blockquote><p>
<code>Prelude Data.Dynamic> cast 'a' :: Maybe Int</code><br />
<code>Nothing</code><br />
<code>Prelude Data.Dynamic> cast 'a' :: Maybe Char</code><br />
<code>Just 'a'</code></p></blockquote>
<p>By using <code>cast</code> the programmer is essentially saying <em>&#8220;Compiler, I take it upon myself to deal with any runtime type errors in my code. Take the afternoon off.&#8221;</em></p>
<p>The other component is <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Dynamic.html">Data.Dynamic</a>, which uses Typeable (and in fact exports the entire Typeable module) to create a new data type called <code>Dynamic</code>. Thanks goes to Luke Palmer for pointing out the existence of this library to me.</p>
<p>This Dynamic type is like a magic bag for Typeable values:</p>
<blockquote><p><code>Prelude Data.Dynamic> :t toDyn </code><br />
<code>toDyn :: (Typeable a) => a -> Dynamic</code><br />
<code>Prelude Data.Dynamic> :t fromDynamic </code><br />
<code>fromDynamic :: (Typeable a) => Dynamic -> Maybe a</code><br />
<code>Prelude Data.Dynamic> fromDynamic (toDyn 'c') :: Maybe Char</code><br />
<code>Just 'c'</code></p></blockquote>
<p>So by encapsulating an arbitrary Typeable value in a Dynamic, it becomes a monomorphic value that we can use in lists, functions, etc.</p>
<p>A final interesting thing to note is that the existence of Typeable and Dynamic do not in any way change haskell&#8217;s static typing. For example, if the compiler cannot infer the type of a value that we cast it will complain of the ambiguity:</p>
<blockquote><pre>Prelude Data.Dynamic> cast 'a' :: (Typeable a)=>Maybe a

    Ambiguous type variable `a' in the constraint:
      `Typeable a'
        arising from an expression type signature at <interactive>:1:0-32
    Probable fix: add a type signature that fixes these type variable(s)</interactive></pre>
</blockquote>
<p>Furthermore the compiler will not allow you to do something fancy like define a function that says <em>&#8220;if the value is an Int pass it to <code>foo</code>, if it is a String, pass it to <code>bar</code>, else return Nothing&#8221;</em>. </p>
<h2>Defining the Dynamic State Monad</h2>
<p>Okay, now let&#8217;s get to the fun part and define our new state monad with dynamic state. </p>
<p><blockquote class="vimblock"><br />
<span class="Type">module</span>&nbsp;<span class="Normal">DynamicState</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;<span class="Type">where</span><br />
<br />
<span class="PreProc">import</span>&nbsp;<span class="Normal">Control.Monad.State</span><br />
<span class="PreProc">import</span>&nbsp;<span class="Normal">Data.Dynamic</span><br />
<br />
<span class="Type">type</span>&nbsp;DynamicState&nbsp;a&nbsp;<span class="Statement">=</span>&nbsp;StateT&nbsp;Dynamic&nbsp;Maybe&nbsp;a<br />
<br /></blockquote></p>
<p>As you can see our new monad is simply the StateT <a href="http://blog.sigfpe.com/2006/05/grok-haskell-monad-transformers.html">monad transformer</a>, where the state type is a Dynamic (meaning we&#8217;ll be able to marshall in and out whatever state types we like), and the inner monad is <code>Maybe</code> for catching any type threading errors. </p>
<p><blockquote class="vimblock"><br />
<span class="Comment">-- Dynamic 'get' and 'put' functions:</span><br />
<span class="Identifier">putD</span>&nbsp;::&nbsp;(Typeable&nbsp;a)<span class="Statement">=&gt;</span>&nbsp;a&nbsp;<span class="Statement">-&gt;</span>&nbsp;DynamicState&nbsp;()<br />
<span class="Identifier">putD</span>&nbsp;<span class="Statement">=</span>&nbsp;put&nbsp;<span class="Statement">.</span>&nbsp;toDyn<br />
<br />
<span class="Identifier">getD</span>&nbsp;::&nbsp;(Typeable&nbsp;a)<span class="Statement">=&gt;</span>&nbsp;DynamicState&nbsp;a<br />
<span class="Identifier">getD</span>&nbsp;<span class="Statement">=</span>&nbsp;get&nbsp;<span class="Statement">&gt;&gt;=</span>&nbsp;lift&nbsp;<span class="Statement">.</span>&nbsp;fromDynamic<br />
<br /></blockquote></p>
<p>Above we define our special getter and setter functions. You can see that they are both very simple: putD simply takes a Typeable state value, converts it to a Dynamic and pushes it; getD gets the Dynamic state, casts it into our requested type, and lifts this Maybe value back into the StateT transformer.</p>
<p>That&#8217;s about all there is to it, but a couple more functions are useful if we want to completely hide Dynamic from the user:</p>
<p><blockquote class="vimblock"><br />
<span class="Comment">-- Compiler will complain if we ignore the returned final state since</span><br />
<span class="Comment">-- its type is ambiguous:</span><br />
<span class="Identifier">runDState</span>&nbsp;::&nbsp;(Typeable&nbsp;s,&nbsp;Typeable&nbsp;s')<span class="Statement">=&gt;</span>&nbsp;DynamicState&nbsp;a&nbsp;<span class="Statement">-&gt;</span>&nbsp;s&nbsp;<span class="Statement">-&gt;</span>&nbsp;Maybe&nbsp;(a,&nbsp;s')<br />
<span class="Identifier">runDState</span>&nbsp;c <span class="Statement">=</span>&nbsp;(liftTypState&nbsp;<span class="Statement">=&lt;&lt;</span>)&nbsp;<span class="Statement">.</span>&nbsp;runStateT&nbsp;c&nbsp;<span class="Statement">.</span>&nbsp;toDyn<br />
&nbsp;&nbsp;&nbsp;&nbsp;<span class="Type">where</span>&nbsp;liftTypState&nbsp;(a,s)&nbsp;<span class="Statement">=</span>&nbsp;fmap&nbsp;((,)a)&nbsp;<span class="Statement">$</span>&nbsp;fromDynamic&nbsp;s<br />
<br />
<span class="Comment">-- ...instead, use this if we want to discard the final state:</span><br />
<span class="Identifier">evalDState</span>&nbsp;::&nbsp;(Typeable&nbsp;s)<span class="Statement">=&gt;</span>&nbsp;DynamicState&nbsp;a&nbsp;<span class="Statement">-&gt;</span>&nbsp;s&nbsp;<span class="Statement">-&gt;</span>&nbsp;Maybe&nbsp;a<br />
<span class="Identifier">evalDState</span>&nbsp;c <span class="Statement">=</span>&nbsp;&nbsp;evalStateT&nbsp;c&nbsp;<span class="Statement">.</span>&nbsp;toDyn<br />
<br /></blockquote></p>
<h3>Testing it Out</h3>
<p>Let&#8217;s use the example we presented above (passing a mutually-recursive data type as state) to demonstrate our new state monad. </p>
<p>To begin with, we must make our EvenBranch/OddBranch type an instance of the Typeable class. This is really easy in GHC with the DeriveDataTypeable extension. Just add this to the top of the file:</p>
<blockquote><p><code>{-# LANGUAGE DeriveDataTypeable #-}</code></p></blockquote>
<p>&#8230;and add &#8220;<code>deriving Typeable</code>&#8221; to the data declarations for those two types.</p>
<p>Now let&#8217;s see an example of a correct computation in the DynamicState monad (I&#8217;m sorry this is such a bad example, but I hope it demonstrates the point):</p>
<p><blockquote class="vimblock"><br />
&nbsp;<span class="Comment">-- a non-sensical and contrived example:</span><br />
<span class="Identifier">traverseGood</span>&nbsp;::&nbsp;DynamicState&nbsp;String<br />
<span class="Identifier">traverseGood</span>&nbsp;<span class="Statement">=</span>&nbsp;<span class="Statement">do</span><br />
&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- we &quot;get&quot; a state value of type EvenBranch</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;(EBranch&nbsp;l&nbsp;i&nbsp;r)&nbsp;<span class="Statement">&lt;-</span>&nbsp;getD<br />
&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- ...and here we &quot;put&quot; a different type (OddBranch)!</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;<span class="Statement">if</span>&nbsp;i&nbsp;<span class="Statement">==</span>&nbsp;<span class="Constant">2</span>&nbsp;&nbsp;&nbsp;&nbsp; <span class="Statement">then</span>&nbsp;putD&nbsp;r<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="Statement">else</span>&nbsp;putD&nbsp;l<br />
&nbsp;&nbsp;&nbsp;&nbsp;(OBranch&nbsp;l' _)&nbsp;&nbsp;<span class="Statement">&lt;-</span>&nbsp;getD<br />
&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- ...and the state type changes back once more:</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;putD&nbsp;l'<br />
&nbsp;&nbsp;&nbsp;&nbsp;(EBranch&nbsp;_&nbsp;i' _)&nbsp;<span class="Statement">&lt;-</span>&nbsp;getD<br />
&nbsp;&nbsp;&nbsp;&nbsp;<span class="Statement">if</span>&nbsp;i' <span class="Statement">==</span>&nbsp;<span class="Constant">3</span>&nbsp;<span class="Statement">then</span>&nbsp;return&nbsp;<span class="Constant">&quot;found 3 in tree&quot;</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Statement">else</span>&nbsp;return&nbsp;<span class="Constant">&quot;3 not found&quot;</span><br />
<br /></blockquote></p>
<p>Now we can define a little helper function to test our computation and a test EvenBranch tree we can pass as state:</p>
<p><blockquote class="vimblock"><br />
<span class="Identifier">tree</span>&nbsp;<span class="Statement">=</span>&nbsp;EBranch&nbsp;Nil&nbsp;<span class="Constant">2</span>&nbsp;(OBranch&nbsp;(EBranch&nbsp;Nil&nbsp;<span class="Constant">3</span>&nbsp;Nil)&nbsp;(EBranch&nbsp;Nil&nbsp;<span class="Constant">4</span>&nbsp;Nil))<br />
<br />
<span class="Identifier">test</span>&nbsp;::&nbsp;DynamicState&nbsp;String&nbsp;<span class="Statement">-&gt;</span>&nbsp;Maybe&nbsp;String<br />
<span class="Identifier">test</span>&nbsp;c <span class="Statement">=</span>&nbsp;evalDState&nbsp;c&nbsp;tree<br />
<br /></blockquote></p>
<p>And testing it out with GHCi:</p>
<blockquote><pre>
*DynamicState> test traverseGood
Just "found 3 in tree"</pre>
</blockquote>
<p>Cool! It seems like we got the threading of the state types correct and the algorithm did&#8230; what we wanted it to do.</p>
<p>Now let&#8217;s intentionally screw up the state, in a slight variation to the code above:</p>
<p><blockquote class="vimblock"><br />
<span class="Comment">-- sae as above but with a programmer error:</span><br />
<span class="Identifier">traverseBad</span>&nbsp;::&nbsp;DynamicState&nbsp;String<br />
<span class="Identifier">traverseBad</span>&nbsp;<span class="Statement">=</span>&nbsp;<span class="Statement">do</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;(EBranch&nbsp;l&nbsp;i&nbsp;r)&nbsp;<span class="Statement">&lt;-</span>&nbsp;getD<br />
&nbsp;&nbsp;&nbsp;&nbsp;<span class="Statement">if</span>&nbsp;i&nbsp;<span class="Statement">==</span>&nbsp;<span class="Constant">2</span>&nbsp;&nbsp;&nbsp;&nbsp; <span class="Statement">then</span>&nbsp;putD&nbsp;r<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="Statement">else</span>&nbsp;putD&nbsp;l<br />
&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- Oops! This is not the type of our state at this point!:</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;(EBranch&nbsp;l' _&nbsp;_)&nbsp;&nbsp;<span class="Statement">&lt;-</span>&nbsp;getD<br />
&nbsp;&nbsp;&nbsp;&nbsp;putD&nbsp;l'<br />
&nbsp;&nbsp;&nbsp;&nbsp;(EBranch&nbsp;_&nbsp;i' _)&nbsp;<span class="Statement">&lt;-</span>&nbsp;getD<br />
&nbsp;&nbsp;&nbsp;&nbsp;<span class="Statement">if</span>&nbsp;i' <span class="Statement">==</span>&nbsp;<span class="Constant">3</span>&nbsp;<span class="Statement">then</span>&nbsp;return&nbsp;<span class="Constant">&quot;found 3 in tree&quot;</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Statement">else</span>&nbsp;return&nbsp;<span class="Constant">&quot;3 not found&quot;</span><br />
<br /></blockquote></p>
<p>And testing running this computation:</p>
<blockquote><pre>*DynamicState> test traverseBad
Nothing</pre>
</blockquote>
<p>This time a casting error was caught in our inner Maybe monad and running the computation simply returned Nothing.</p>
<h2>Philosophical Conclusion</h2>
<p>The existence of Data.Dynamic allows for library designers to implement some pretty cool things that wouldn&#8217;t normally be possible in a statically-typed language. But I wonder to what extent its use is not simply &#8220;passing the buck&#8221; so to speak. </p>
<p>In other words to what extent can a haskell programmer really handle potential type failure at runtime? If Nothings raised by cast et al. failing eventually simply percolate up into an error message thrown in the user&#8217;s face, then Typeable seems not much more than a shim to work around haskell&#8217;s type system. </p>
]]></content:encoded>
			<wfw:commentRss>http://coder.bsimmons.name/blog/2010/12/a-state-monad-with-dynamically-typed-state/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New version of &#8216;thrist&#8217; package released</title>
		<link>http://coder.bsimmons.name/blog/2010/11/new-version-of-thrist-package-released/</link>
		<comments>http://coder.bsimmons.name/blog/2010/11/new-version-of-thrist-package-released/#comments</comments>
		<pubDate>Sat, 13 Nov 2010 16:48:47 +0000</pubDate>
		<dc:creator>jberryman</dc:creator>
				<category><![CDATA[haskell]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[hackage]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[release]]></category>
		<category><![CDATA[theory]]></category>

		<guid isPermaLink="false">http://coder.bsimmons.name/blog/?p=478</guid>
		<description><![CDATA[<p>I&#8217;ve been collaborating with Gabor Greif on a <a href="http://hackage.haskell.org/package/thrist">new version of his &#8216;thrist&#8217; module</a>, which was just released last night! I approached Gabor with some new ideas that came to me as I was writing a module that uses&#8230; <a href="http://coder.bsimmons.name/blog/2010/11/new-version-of-thrist-package-released/" class="read_more">   [ R E A D &#124; M O R E ]</a></p>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been collaborating with Gabor Greif on a <a href="http://hackage.haskell.org/package/thrist">new version of his &#8216;thrist&#8217; module</a>, which was just released last night! I approached Gabor with some new ideas that came to me as I was writing a module that uses Thrists heavily, and he invited me to co-author this version. (See <a href="#thrist_primer">below</a> for a brief explanation of Thrists).</p>
<p>I noticed that in the previous version, the function <code>foldThrist</code> was essentially a <code>foldr</code> with a type signature that was overly restrictive. </p>
<p>For instance, one <em>could not</em> define an identity function on Thrists in terms of the foldThrist function, the way one can with regular lists, e.g.:</p>
<blockquote><p><code>
<pre>foldr (:) [] [1..4] == [1,2,3,4]</pre>
<p></code></p></blockquote>
<p>Other additions followed as I tried to define the Thrist equivalent of many useful list functions. For example I wanted to define a <code>foldl</code>-like function that we could use to reverse a Thrist.</p>
<p>Check out <a href="http://heisenbug.blogspot.com/2010/11/cooperation.html">the release announcement</a> on Gabor&#8217;s blog, along with his <a href="http://www.opendylan.org/~gabor/Thrist-draft-2008-07-18.pdf">draft paper on Thrists.</a><br />
<span id="more-478"></span></p>
<h3>A Brief Thrist Primer<a name="thrist_primer"></a></h3>
<p>A Thrist is a <strong>type-threaded list</strong>. This is easiest explained with an example:</p>
<blockquote><p><code><br />
*Data.Thrist> :t Cons (True,'z')$ Cons ('a',"bar")$ Cons ("foo",3.14) Nil<br />
<strong>Cons (True,'z')$ Cons ('a',"bar")$ Cons ("foo",3.14) Nil<br />
  :: (Fractional c) => Thrist (,) Bool c</strong><br />
</code></p></blockquote>
<p>As you can see, unlike the regular haskell list type which takes a single type for each element, the Thrist takes a single <em>binary type</em> (in the case above we have the tuple type:<code> (,)</code>) for each element, whose type arguments are <em>chained</em> together. So the <em>second</em> type argument of one cell must be the same type as the <em>first</em> type argument of the following cell, and so on.</p>
<p>The two arguments that are visible in the outer Thrist type itself are the first argument of the first cell, and the second argument of the last cell. In the example above those would be <code>Bool</code> (taken from the <code>True</code> value fst of the head of our Thrist), and some as-yet-undetermined <code>Fractional</code> type (our 3.14 value).</p>
<p>This type of cool data structure is only possible because of <a href="http://en.wikibooks.org/wiki/Haskell/GADT">GADTs</a> which let us enforce the type-threading and allow us to have all these types <em>inside the Thrist</em> without having them show up in the type signature.</p>
<p>Here is how the Thrist GADT is defined:</p>
<p><blockquote class="vimblock"><br />
<span class="Type">data</span>&nbsp;Thrist&nbsp;<span class="Statement">::</span>&nbsp;(<span class="Statement">*</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;<span class="Statement">*</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;<span class="Statement">*</span>)&nbsp;<span class="Statement">-&gt;</span>&nbsp;<span class="Statement">*</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;<span class="Statement">*</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;<span class="Statement">*</span>&nbsp;<span class="Type">where</span><br />
&nbsp;&nbsp;Nil&nbsp;<span class="Statement">::</span>&nbsp;Thrist&nbsp;(<span class="Statement">~&gt;</span>)&nbsp;a&nbsp;a<br />
&nbsp;&nbsp;Cons&nbsp;<span class="Statement">::</span>&nbsp;(a&nbsp;<span class="Statement">~&gt;</span>&nbsp;b)&nbsp;<span class="Statement">-&gt;</span>&nbsp;Thrist&nbsp;(<span class="Statement">~&gt;</span>)&nbsp;b&nbsp;c&nbsp;<span class="Statement">-&gt;</span>&nbsp;Thrist&nbsp;(<span class="Statement">~&gt;</span>)&nbsp;a&nbsp;c<br />
<br /></blockquote></p>
<p>Here is another example of a Thrist in which the binary type element is a <em>function</em>:</p>
<blockquote><pre>
*Data.Thrist> :t Cons head $ Cons fst $ Cons not Nil
<strong>Cons head $ Cons fst $ Cons not Nil
    :: Thrist (->) [(Bool, b)] Bool</strong></pre>
</blockquote>
<p>It might look odd to see (->) used by itself as an argument to a type signature, but a Thrist of functions is actually pretty cool. We can actual fold the Thrist using function composition:</p>
<blockquote>
<p><code>*Data.Thrist> :t foldl1Thrist (flip (.)) $ Cons head $ Cons fst $ Cons not Nil<br />
<strong>foldl1Thrist (flip (.))$ Cons head $ Cons fst $ Cons not Nil<br />
  :: [(Bool, b)] -> Bool</strong></code></p></blockquote>
<p>Notice how similar the Thrist definition is to the composed function. You can see how the Thrist generalizes function composition to a certain extent.</p>
]]></content:encoded>
			<wfw:commentRss>http://coder.bsimmons.name/blog/2010/11/new-version-of-thrist-package-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Designing a Module for Combinatory Logic in Haskell</title>
		<link>http://coder.bsimmons.name/blog/2010/09/designing-a-module-for-combinatory-logic-in-haskell/</link>
		<comments>http://coder.bsimmons.name/blog/2010/09/designing-a-module-for-combinatory-logic-in-haskell/#comments</comments>
		<pubDate>Sat, 04 Sep 2010 21:28:43 +0000</pubDate>
		<dc:creator>jberryman</dc:creator>
				<category><![CDATA[haskell]]></category>
		<category><![CDATA[combinator]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[EsotericLanguages]]></category>
		<category><![CDATA[NumericTypes]]></category>
		<category><![CDATA[release]]></category>
		<category><![CDATA[sequences]]></category>
		<category><![CDATA[theory]]></category>

		<guid isPermaLink="false">http://coder.bsimmons.name/blog/?p=471</guid>
		<description><![CDATA[<p>Like the <a href="http://en.wikipedia.org/wiki/Lambda_calculus">Lambda Calculus</a> (on which Lisp is based), Combinatory Logic is a formal system that can be used to model and study computation. What makes it fascinating is that it is as powerful as the (already simple) lambda&#8230; <a href="http://coder.bsimmons.name/blog/2010/09/designing-a-module-for-combinatory-logic-in-haskell/" class="read_more">   [ R E A D &#124; M O R E ]</a></p>]]></description>
			<content:encoded><![CDATA[<p>Like the <a href="http://en.wikipedia.org/wiki/Lambda_calculus">Lambda Calculus</a> (on which Lisp is based), Combinatory Logic is a formal system that can be used to model and study computation. What makes it fascinating is that it is as powerful as the (already simple) lambda calculus, but has no need for the variables that LC requires to perform substitution!</p>
<p>Here I show how we can use Haskell&#8217;s type classes and other language features to model the Combinator Calculus. The goals of this module were:</p>
<ol>
<li>     don&#8217;t force any one evaluation strategy </li>
<li>     allow users to define new combinators without exposing the implementation</li>
<li>    allow new combinators to be defined in terms of other already-defined combinators.</li>
<li>    discourage creation of non-sensical combinator expressions, or possible mis-use of the module</li>
<li>    hide existential types and anything else exotic</li>
</ol>
<p>If you want to play with it, you can do a:</p>
<blockquote><p>
<code>$> darcs get http://coder.bsimmons.name/code/CombinatorCalculus</code>
</p></blockquote>
<p><span id="more-471"></span></p>
<h2>A Quick Combinator Calculus Primer</h2>
<p>A Combinatory Logic expression consists of a sequence of <em>combinator terms</em> and <em>sub-expressions</em>. Combinator terms are like functions which consume some arguments (themselves combinators or sub-expressions), and return a particular re-arrangement of those arguments. When no term can consume enough arguments to be &#8220;evaluated&#8221; any further, the expression is said to be in <em>normal form</em>.</p>
<p>The <a href="http://en.wikipedia.org/wiki/SKI_combinator_calculus">SKI Combinator Calculus</a> is a system that uses only three combinators (&#8216;S&#8217;, &#8216;K&#8217; and &#8216;I&#8217;) and forms a Turing Complete system. This means we can express any computation with expressions that look like <code>SK(SSS)I(S(KS)K)I</code>. It can even server as the basis of a turing complete <a href="http://www.madore.org/~david/programs/unlambda/">programming language</a>!</p>
<p>It&#8217;s a really fascinating topic, and you can get a great overview from wikipedia&#8217;s excellent <a href="http://en.wikipedia.org/wiki/Combinatory_logic">Combinatory Logic article</a>.</p>
<h2>The Design of the Module</h2>
<p>All terms in combinatory logic take some arguments and form a new expression from them, but different combinators transform their arguments in different ways. </p>
<p>We can express this in Haskell by creating a typeclass with methods that describe the behavior of a combinator. Then we can make a type (corresponding to a specific Combinator term) an instance of our class to define its behavior.</p>
<h3>The <code>Combinator</code> Class</h3>
<p>Here is how we define our <code>Combinator</code> class:</p>
<p><blockquote class="vimblock"><br />
&nbsp;<span class="Comment">-- a Class for combinators. Its methods represent a combinator's behavior on </span><br />
&nbsp;<span class="Comment">-- its arguments:</span><br />
<span class="Type">class</span>&nbsp;(Show&nbsp;c)<span class="Statement">=&gt;</span>&nbsp;Combinator&nbsp;c&nbsp;<span class="Type">where</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;takesArgs&nbsp;<span class="Statement">::</span>&nbsp;c&nbsp;<span class="Statement">-&gt;</span>&nbsp;Int<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;applyArgs&nbsp;<span class="Statement">::</span>&nbsp;c&nbsp;<span class="Statement">-&gt;</span>&nbsp;[Term]&nbsp;<span class="Statement">-&gt;</span>&nbsp;Expr<br />
&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- HIDDEN METHOD: EXPORTED AS A FUNCTION:</span><br />
&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- if a combinator takes 0 args, we assume it can be evaluated and we</span><br />
&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- say it is not in Normal Form:</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;isNormal&nbsp;<span class="Statement">::</span>&nbsp;c&nbsp;<span class="Statement">-&gt;</span>&nbsp;Bool<br />
&nbsp;&nbsp;&nbsp;&nbsp;isNormal&nbsp;<span class="Statement">=</span>&nbsp;(<span class="Statement">&gt;</span>&nbsp;<span class="Constant">0</span>)&nbsp;<span class="Statement">.</span>&nbsp;takesArgs<br />
&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- HIDDEN METHOD: user defined combinators are placed in a black box:</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;toTerm&nbsp;<span class="Statement">::</span>&nbsp;c&nbsp;<span class="Statement">-&gt;</span>&nbsp;Term<br />
&nbsp;&nbsp;&nbsp;&nbsp;toTerm&nbsp;<span class="Statement">=</span>&nbsp;Term<br />
<br /></blockquote></p>
<p>The first two methods are the only ones exported to users of the module to define an instance of <code>Combinator</code>. <code>takesArgs</code> is used to indicate how many arguments this particular combinator requires before it can be evaluated. </p>
<p><code>applyArgs</code> actually performs the transformation of those arguments; it is given a list of terms (of length equal to `takesArgs`) and returns a new expression (type Expr).</p>
<p>The third method is used to check if an expression is in normal form. It is exported <em>as a regular function</em>, meaning that users can use it in their code but <em>cannot</em> use it in their own instance declarations. Instead the default value would apply.</p>
<p>The fourth method `toTerm` is used internally to encapsulate some Combinator class item in a `Term` data type. We use this when composing combinator expressions, in order to preserve the tree structure of the expression. (see below for more on this)</p>
<h3>The <code>Term</code> and <code>Expr</code> types</h3>
<p>The module defines two new datatypes, <em>both</em> of which are instances of `Combinator`.	</p>
<p>`Expr` is a <code>newtype</code> wrapper around <code>Seq Term</code>, but we don&#8217;t export the implementation so we can change this if we don&#8217;t want to use <a href="http://hackage.haskell.org/packages/archive/containers/0.2.0.1/doc/html/Data-Sequence.html">Sequences</a>:</p>
<p><blockquote class="vimblock"><br />
<span class="Type">newtype</span>&nbsp;Expr&nbsp;<span class="Statement">=</span>&nbsp;Expr&nbsp;{&nbsp;combSeq&nbsp;<span class="Statement">::</span>&nbsp;Seq&nbsp;Term&nbsp;}<br />
<br /></blockquote></p>
<p>It simply represents a CL expression as a sequence of terms. Making it an instance of `Combinator` expresses the notion that an expression can be thought of as a combinator term whenever the need arises. In fact the distinction is simply one of <a href="http://en.wikipedia.org/wiki/Evaluation_strategy">evaluation strategy</a>.</p>
<p>`Term` is a wrapper for Combinator terms and sub-expressions. It is mutually-recursive with `Expr` and the two together form the tree structure of a combinator expression:</p>
<p><blockquote class="vimblock"><br />
<span class="Type">data</span>&nbsp;Term&nbsp;<span class="Statement">=</span>&nbsp;forall&nbsp;c<span class="Statement">.</span>&nbsp;Combinator&nbsp;c&nbsp;<span class="Statement">=&gt;</span>&nbsp;Term&nbsp;{&nbsp;unbox&nbsp;<span class="Statement">::</span>&nbsp;c&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="Statement">|</span>&nbsp;SubExpr&nbsp;&nbsp; {&nbsp;subExpr&nbsp;<span class="Statement">::</span>&nbsp;Expr&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="Statement">|</span>&nbsp;NamedExpr&nbsp;{&nbsp;subExpr&nbsp;<span class="Statement">::</span>&nbsp;Expr,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;name&nbsp;&nbsp;&nbsp;&nbsp;<span class="Statement">::</span>&nbsp;String&nbsp;}<br />
<br /></blockquote></p>
<p>All three constructors are hidden from the user. `SubExpr` simply holds an `Expr` type and represents a parenthesized sub-expression within the top level combinator sequence. `NamedExpr` is identical except that it also contains a String, which will be returned when `show` is called on that constructor. Here is the `Show` instance for `Term`:</p>
<p><blockquote class="vimblock"><br />
<span class="Type">instance</span>&nbsp;Show&nbsp;Term&nbsp;<span class="Type">where</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;show&nbsp;(NamedExpr&nbsp;_&nbsp;n)&nbsp;<span class="Statement">=</span>&nbsp;n<br />
&nbsp;&nbsp;&nbsp;&nbsp;show&nbsp;(SubExpr&nbsp;e)&nbsp;&nbsp;&nbsp;&nbsp; <span class="Statement">=</span>&nbsp;<span class="Constant">&quot;(&quot;</span><span class="Statement">++</span>&nbsp;show&nbsp;e&nbsp;<span class="Statement">++</span><span class="Constant">&quot;)&quot;</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;show&nbsp;(Term&nbsp;t)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="Statement">=</span>&nbsp;show&nbsp;t<br />
<br /></blockquote></p>
<p>The remaining constructor is the most interesting: the `Term` constructor houses an <a href="http://en.wikibooks.org/wiki/Haskell/Existentially_quantified_types">existentially-quantified type</a> and can hold <em>any</em> type value of the `Combinator` class. </p>
<p>Notice that the type variable does not appear on the left side of the <code>=</code> in the type declaration. What this means in practical terms is that the `Term` constructor becomes a &#8220;black box&#8221;; once a value is inside, the only things we can &#8220;do with it&#8221; are to apply polymorphic Combinator class functions and methods.</p>
<p>And that&#8217;s why we have the internal `toTerm` method; it allows us to wrap sub-expressions in the `SubExpr` constructor, preserving the tree structure of an expression as we compose it. Without it we would either need to export multiple functions for composing a term with an expression, an expression with an expression, a term with a term, and an expression with a term. Ugly!</p>
<h3>Exported functions</h3>
<p>Our types and classes allow us to do some neat stuff. As mentioned above, we can compose expressions using a single haskell infix function. Since all the nice ASCII combinators were taken (and since I&#8217;m the only one using this) I decided to go with a Unicode symbol, the middle dot, for composition:</p>
<p><blockquote class="vimblock"><br />
&nbsp;<span class="Comment">-- operator for composing combinator expressions. This is the Middle Dot, </span><br />
&nbsp;<span class="Comment">-- unicode character 00B7. It is easily inserted in vim using the digraph: </span><br />
&nbsp;<span class="Comment">--&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Ctrl-K '.' 'M'</span><br />
<span class="PreProc">infixl</span>&nbsp;<span class="Constant">7</span>&nbsp;·<br />
<br /></blockquote></p>
<p>&#8230;and the implementation:</p>
<p><blockquote class="vimblock"><br />
&nbsp;<span class="Comment">-- for composing Combinator expressions:</span><br />
(·)&nbsp;<span class="Statement">::</span>&nbsp;(Combinator&nbsp;c1,Combinator&nbsp;c2)<span class="Statement">=&gt;</span>&nbsp;c1&nbsp;<span class="Statement">-&gt;</span>&nbsp;c2&nbsp;<span class="Statement">-&gt;</span>&nbsp;Expr<br />
c1&nbsp;· (toTerm<span class="Statement">-&gt;</span>t2)&nbsp;<span class="Statement">=</span>&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp; <span class="Statement">case</span>&nbsp;toTerm&nbsp;c1&nbsp;<span class="Statement">of</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(SubExpr&nbsp;e)&nbsp;<span class="Statement">-&gt;</span>&nbsp;e&nbsp;<span class="Statement">`appendTerms`</span>&nbsp;singleton&nbsp;t2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- named expression or bare Term start a new sub-expression:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="Statement">-&gt;</span>&nbsp;Expr&nbsp;(singleton&nbsp;t1&nbsp;<span class="Statement">|&gt;</span>&nbsp;t2)<br />
<br /></blockquote></p>
<p>We also have the ability to define new combinators in terms of other combinators using the `named` function. Here is an example showing how `I` can be defined in terms of `S` and `K` and used to form a Combinator Calculus equivalent of the <a href="http://en.wikipedia.org/wiki/Church_numeral">Church Numeral</a> 2:</p>
<p><blockquote class="vimblock"><br />
<span class="lnr">60 </span>two&nbsp;<span class="Statement">=</span>&nbsp;S·(S·(K·S)·K)·cI<br />
<span class="lnr">61 </span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="Type">where</span>&nbsp;cI&nbsp;<span class="Statement">=</span>&nbsp;(S&nbsp;· K&nbsp;· K)&nbsp;&nbsp;<span class="Statement">`named`</span>&nbsp;<span class="Constant">&quot;I&quot;</span><br />
<br /></blockquote></p>
<h2>Playing with it</h2>
<p>The evaluation function exported in the module was written fairly hastily, but it is good enough to let us play with evaluating expressions.</p>
<p>I&#8217;ve run out of time on this post, but you can grab the darcs repo above and run the &#8216;main&#8217; function in `Examples.hs` and check out the source for more info. I&#8217;ll maybe show some cool examples in a later post.</p>
<p>Thanks for reading!</p>
]]></content:encoded>
			<wfw:commentRss>http://coder.bsimmons.name/blog/2010/09/designing-a-module-for-combinatory-logic-in-haskell/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Lazy Arithmetic in Haskell</title>
		<link>http://coder.bsimmons.name/blog/2010/03/lazy-arithmetic-in-haskell/</link>
		<comments>http://coder.bsimmons.name/blog/2010/03/lazy-arithmetic-in-haskell/#comments</comments>
		<pubDate>Wed, 24 Mar 2010 17:24:08 +0000</pubDate>
		<dc:creator>jberryman</dc:creator>
				<category><![CDATA[haskell]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[hackage]]></category>
		<category><![CDATA[laziness]]></category>
		<category><![CDATA[NumericTypes]]></category>

		<guid isPermaLink="false">http://coder.bsimmons.name/blog/?p=372</guid>
		<description><![CDATA[<p><em>We don&#8217;t usually give much thought to Numeric data types beyond whether we want to work with integers or decimal numbers. And that is a shame! In this post I&#8217;ll look at how we can actually do arithmetic operations lazily,</em>&#8230; <a href="http://coder.bsimmons.name/blog/2010/03/lazy-arithmetic-in-haskell/" class="read_more">   [ R E A D &#124; M O R E ]</a></p>]]></description>
			<content:encoded><![CDATA[<p><em>We don&#8217;t usually give much thought to Numeric data types beyond whether we want to work with integers or decimal numbers. And that is a shame! In this post I&#8217;ll look at how we can actually do arithmetic operations lazily, and in the process hopefully reveal a bit about haskell&#8217;s numeric classes.</em></p>
<p><div class="vimblock"><br />
<span class="Comment">&gt;</span>&nbsp;<span class="Type">module</span>&nbsp;LazyArithmetic<br />
<span class="Comment">&gt;</span>&nbsp;&nbsp;&nbsp;&nbsp; <span class="Type">where</span><br />
<br /></div></p>
<p>We will be using <a href="http://hackage.haskell.org/package/numbers-2009.8.9">Lennart Augustsson&#8217;s <code>numbers</code> library</a> which can be installed from hackage with <a href="http://hackage.haskell.org/trac/hackage/wiki/CabalInstall">cabal-install</a>:</p>
<blockquote><p>$> cabal install numbers</p></blockquote>
<p><div class="vimblock"><br />
<span class="Comment">&gt;</span>&nbsp;<span class="PreProc">import</span>&nbsp;Data.Number.Natural<br />
<span class="Comment">&gt;</span>&nbsp;<span class="PreProc">import</span>&nbsp;Data.List(genericLength)<br />
<br /></div></p>
<p>Consider two functions: the Prelude function <code>sum</code> and <code>genericLength</code> from the List library:</p>
<p><blockquote class="vimblock"><br />
<span class="Comment"></span>&nbsp;<span class="Identifier">genericLength</span>&nbsp;<span class="Statement">::</span>&nbsp;(<span class="Type">Num</span>&nbsp;i)&nbsp;<span class="Statement">=&gt;</span>&nbsp;[b]&nbsp;<span class="Statement">-&gt;</span>&nbsp;i<br />
<span class="Comment"></span>&nbsp;<span class="Identifier">sum</span>&nbsp;<span class="Statement">::</span>&nbsp;(<span class="Type">Num</span>&nbsp;a)&nbsp;<span class="Statement">=&gt;</span>&nbsp;[a]&nbsp;<span class="Statement">-&gt;</span>&nbsp;a<br />
<br /></blockquote></p>
<p>&#8230;two simple functions that have the potential to be very expensive, depending on the length of the list and the values of the elements.<br />
<span id="more-372"></span><br />
Say for instance that all we want is to use:</p>
<p><div class="vimblock"><br />
<span class="Comment">&gt;</span>&nbsp;sumLengths&nbsp;<span class="Statement">=</span>&nbsp;<span class="Identifier">sum</span>&nbsp;<span class="Statement">.</span>&nbsp;<span class="Identifier">map</span>&nbsp;genericLength<br />
<span class="Comment">&gt;</span><br />
<span class="Comment">&gt;</span>&nbsp;checkLengths&nbsp;as&nbsp;n&nbsp;<span class="Statement">=</span>&nbsp;(sumLengths&nbsp;as&nbsp;<span class="Statement">`div`</span>&nbsp;n)&nbsp;<span class="Statement">&gt;</span>&nbsp;<span class="Constant">2</span><br />
<br /></div></p>
<p>The <code>checkLengths</code> function above has to count every element of every element of every sub-list in order to return a <code>Bool</code> value, and if any of those lists are infinite our program will never terminate:</p>
<p><div class="vimblock"><br />
<span class="Comment">&gt;</span>&nbsp;hopeless&nbsp;<span class="Statement">=</span>&nbsp;checkLengths&nbsp;[[<span class="Constant">'a'</span><span class="Statement">..</span><span class="Constant">'z'</span>],&nbsp;[<span class="Constant">'0'</span>],&nbsp;<span class="Identifier">repeat</span>&nbsp;<span class="Constant">'Z'</span>]&nbsp;&nbsp;<span class="Constant">99</span><br />
<br /></div></p>
<p><em>&#8230;or so we might think!</em></p>
<h3>Lazy Natural Numbers</h3>
<p>It turns out we can solve our seemingly hopeless situation with a type signature:</p>
<p><div class="vimblock"><br />
<span class="Comment">&gt;</span>&nbsp;sumLengths&nbsp;<span class="Statement">::</span>&nbsp;[[b]]&nbsp;<span class="Statement">-&gt;</span>&nbsp;Natural<br />
<br /></div></p>
<p>And suddenly, as if by magic:</p>
<blockquote><p><code>*LazyArithmetic> hopeless<br />
True</code></p></blockquote>
<p>What&#8217;s going on here? Well it turns out the problem is that Haskell&#8217;s built-in numeric types are boring, old-fashioned and (in some cases) just plain wrong. But let&#8217;s step behind the curtain and look at how the Data.Numbers library defines the Natural type internally:</p>
<p><blockquote class="vimblock"><br />
<span class="Comment"></span>&nbsp;<span class="Type">data</span>&nbsp;Natural&nbsp;<span class="Statement">=</span>&nbsp;Z&nbsp;<span class="Statement">|</span>&nbsp;S&nbsp;Natural<br />
<br /></blockquote></p>
<p>We see that we&#8217;re using an abstract data type to represent non-negative integers, and it looks nearly identical to our list type <code>[]</code>. The upshot of that is we gain, in our numeric type and arithmetic operations, the same type of laziness that lists afford us!</p>
<p>So in the above example, <code>hopeless</code>, we need only carry out the operations far enough to see that the result is <code>> 2</code>.</p>
<p>The numeric type in <code>Data.List.Natural</code> are actually known as <a href="http://www.haskell.org/haskellwiki/Peano_numbers">Peano numbers</a>. They are essentially just lists of units and, as you might imagine, are not the most efficient way to represent an integer.</p>
<p>But they are exactly what we want for this application. If we failed to realize that we could solve our problem with an appropriate numeric representation, we might try to rig up something like this:</p>
<p><div class="vimblock"><br />
<span class="Comment">&gt;</span>&nbsp;checkLengthsUnclear&nbsp;as&nbsp;n&nbsp;<span class="Statement">=</span>&nbsp;<span class="Identifier">not</span>&nbsp;<span class="Statement">$</span>&nbsp;<span class="Identifier">null</span>&nbsp;<span class="Statement">$</span>&nbsp;<span class="Identifier">drop</span>&nbsp;(n<span class="Statement">*</span><span class="Constant">2</span>)&nbsp;<span class="Statement">$</span>&nbsp;<span class="Identifier">concat</span>&nbsp;as<br />
<br /></div></p>
<p>&#8230;which works identically to <code>checkLengths</code> with Peano Numbers, but completely obfuscates the intention of the function. As usual laziness gives us <em>expressive power</em> rather than an efficiency boost.</p>
<h3>Limitations, Haskell&#8217;s Numeric Type Classes, and the Numeric Prelude</h3>
<p>The <code>Data.Number.Natural</code> library is convenient because it provides Num and Integral instances so we can use the the Natural type with any function that is polymorphic on those classes.</p>
<p>The problem is <a href="http://hackage.haskell.org/packages/archive/numbers/2009.8.9/doc/html/src/Data-Number-Natural.html#line-44">the Num instance</a> is incomplete and error-prone: and that&#8217;s because a <a href="http://en.wikipedia.org/wiki/Natural_number">natural numbe</a>r type <em>shouldn&#8217;t be an instance of Num</em>! We can&#8217;t negate a Natural, which in turn makes subtraction dangerous, etc.</p>
<blockquote><p><code>*LazyArithmetic> let x = 1 :: Natural; y = 2 in x - y<br />
*** Exception: Natural: (-)</code></p></blockquote>
<p>We might wish that haskell&#8217;s Numeric type classes were more expressive, allowing for more abstract numeric types. For example it might be more &#8220;haskelly&#8221; for the length function to be defined with the type:</p>
<p><blockquote class="vimblock"><br />
<span class="Comment"></span>&nbsp;<span class="Identifier">length</span>&nbsp;<span class="Statement">::</span>&nbsp;Natural&nbsp;n&nbsp;<span class="Statement">=&gt;</span>&nbsp;[a]&nbsp;<span class="Statement">-&gt;</span>&nbsp;n<br />
<br /></blockquote></p>
<p>After all we don&#8217;t use integers for boolean values as in C; we have the abstract type <code>Bool</code>. So why return an Int when a Natural type (or class) might be more expressive? The answer of course is that that gets really complicated really fast. </p>
<p>For one approach at making haskell&#8217;s numeric class hierarchy more expressive and flexible, check out the <a href="http://www.haskell.org/haskellwiki/Numeric_Prelude">Numeric Prelude</a>. It&#8217;s <a href="http://hackage.haskell.org/package/numeric-prelude">haddock documentation</a> is very thorough and an interesting read, and you can see the sheer number of design decisions necessary for such an undertaking. </p>
<p>For some other approaches and links, see <a href="http://www.haskell.org/haskellwiki/Libraries_and_tools/Mathematics#Type_class_hierarchies">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://coder.bsimmons.name/blog/2010/03/lazy-arithmetic-in-haskell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk
Database Caching 8/15 queries in 2.765 seconds using disk

Served from: coder.bsimmons.name @ 2012-02-05 10:59:06 -->
