<?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; NumericTypes</title>
	<atom:link href="http://coder.bsimmons.name/blog/tag/numerictypes/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>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/20 queries in 0.051 seconds using disk

Served from: coder.bsimmons.name @ 2012-02-05 12:25:18 -->
