<?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; theory</title>
	<atom:link href="http://coder.bsimmons.name/blog/tag/theory/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>Do Applicative Functors generalize the S &amp; K Combinators?</title>
		<link>http://coder.bsimmons.name/blog/2011/01/do-applicative-functors-generalize-the-s-k-combinators/</link>
		<comments>http://coder.bsimmons.name/blog/2011/01/do-applicative-functors-generalize-the-s-k-combinators/#comments</comments>
		<pubDate>Sun, 02 Jan 2011 17:44:02 +0000</pubDate>
		<dc:creator>jberryman</dc:creator>
				<category><![CDATA[haskell]]></category>
		<category><![CDATA[Applicative]]></category>
		<category><![CDATA[combinator]]></category>
		<category><![CDATA[LambdaCalculus]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[theory]]></category>
		<category><![CDATA[TypeSystem]]></category>

		<guid isPermaLink="false">http://coder.bsimmons.name/blog/?p=519</guid>
		<description><![CDATA[<p>If the title hasn't scared you off yet, here's the story: I was hacking on someone else's <a href="http://hackage.haskell.org/package/fclabels-0.11.1.1">code</a> on the plane and trying to wrap my head around some <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Applicative.html#t:Applicative"><code>Applicative</code> class</a> code; in particular the code in question&#8230; <a href="http://coder.bsimmons.name/blog/2011/01/do-applicative-functors-generalize-the-s-k-combinators/" class="read_more">   [ R E A D &#124; M O R E ]</a></p>]]></description>
			<content:encoded><![CDATA[<p>If the title hasn't scared you off yet, here's the story: I was hacking on someone else's <a href="http://hackage.haskell.org/package/fclabels-0.11.1.1">code</a> on the plane and trying to wrap my head around some <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Applicative.html#t:Applicative"><code>Applicative</code> class</a> code; in particular the code in question used the Applicative instance for ((->) a) i.e. functions. This turned my brain to cream-of-wheat and I had to take a break.</p>
<p>If you aren't familiar with <strong>Applicative Functors</strong>, they are somewhere in between the familiar and simple <code>Functor</code> class and the <code>Monad</code> class; an abstraction for function application with a context. Check out <a href="http://www.haskell.org/haskellwiki/Applicative_functor">here</a> for more.<br />
<span id="more-519"></span><br />
Away from the computer I got out a pad of paper and went about trying to figure out how the <code>< *></code> method was defined over functions. Here are the types:</p>
<blockquote><p><em>The polymorphic type:</em><br />
<code>(< *>) :: (Applicative f) => f (a -> b) -> f a -> f b </code></p>
<p><em>Substitute <code>(x -> ...)</code> for <code>f</code> to get the type for the functions instance:</em><br />
<code>(< *>) :: (x -> a -> b) -> (x -> a) -> (x -> b)</code> </p></blockquote>
<p>You can try defining the instance from the type definition; there seems to be only one sensical way. When I did it I was struck by something: the definition for the function above <em>is the same as the S combinator in the SKI combinator calculus!</em></p>
<p>At that point I started looking for other connections to combinatory logic, and quickly noticed that <em>the class method pure was essentially the K combinator!</em>. Here is the actual instance definition:</p>
<blockquote><pre>instance Applicative ((->) a) where
        pure = const
        (< *>) f g x = f x (g x)</pre>
</blockquote>
<p>For those not familiar, the <strong>SK(I) Combinator Calculus</strong> is a formal system for modelling computation, much like the lambda calculus; one can express any computable function using only the three (actually only S and K are necessary) symbols and parentheses. I've written about and <a href="http://coder.bsimmons.name/blog/2010/09/designing-a-module-for-combinatory-logic-in-haskell/">implemented the combinator calculus</a>, and you can read more on the <a href="http://en.wikipedia.org/wiki/SKI_combinator_calculus">wikipedia page</a>.</p>
<h3>Exploring the Connection</h3>
<p>It's pretty astounding to me that the only two methods required to define an Applicative instance turn out to be sufficient (the details of haskell's type system aside) to define a complete combinator base, <em>capable of expressing any computable function.</em></p>
<p>At first I wondered whether this connection was the brainchild of some clever haskeller who defined the (->) instance, and therefore somewhat artificial. But it turns out that the definitions for <code>pure</code> and <code>(< *>)</code> fall out quit naturally from the type definitions. So naturally in fact that we can use <a href="http://hackage.haskell.org/package/djinn/">djinn</a> to automatically derive their definitions!:</p>
<blockquote><p><em>Djinn></em> ? (< *>) :: (x -> a -> b) -> (x -> a) -> (x -> b)<br />
(< *>) :: (x -> a -> b) -> (x -> a) -> x -> b<br />
(< *>) a b c = a c (b c)<br />
<em>Djinn></em> ? pure :: a -> (x -> a)<br />
pure :: a -> x -> a<br />
pure a _ = a
</p></blockquote>
<p>Observe how the function definitions above could have been pulled right from an explanation of the S and K combinators.</p>
<p>Now let's play with this in GHCi. We'll first define our S and K combinators as the Applicative methods (giving type hints to keep the typechecker happy), then define the I combinator in terms of S and K, then we'll express a Church numeral:</p>
<blockquote><p>
<em>Prelude></em><code> :m + Control.Applicative </code><br />
<em>Prelude Control.Applicative></em> <code>let s = (< *>) :: (x -> b -> c) -> (x -> b) -> (x -> c)</code><br />
<em>Prelude Control.Applicative></em><code> let k = pure :: a -> (x -> a)</code><br />
<em>Prelude Control.Applicative></em> <code>let i = s k k</code><br />
<em>Prelude Control.Applicative></em><br />
<em>Prelude Control.Applicative></em> <code>let two = s (s (k s) k) i</code><br />
<em>Prelude Control.Applicative></em><br />
<em>Prelude Control.Applicative></em> <code>two ('x':) []</code><br />
<strong>"xx"</strong></p></blockquote>
<p>In the last last line above we sort of "render" the church numeral by applying it to a function and value that will construct a list; remember that church numerals represent integers as <em>n-fold function composition</em>; in the lambda calculus the numerical represenatations are more straightforward: <code>two = \f x-> f (f x)</code>, but the idea is the same.</p>
<h3>Conclusion</h3>
<p>It makes a lot of sense that a general type class meant to aid programming in an "applicative" style would have some similarity with the combinator calculus (in which <em>even data</em> is function application), but I thought it was pretty exciting to see such a fundamental computer science concept seemingly emerge naturally out of a library designed to solve a very high-level problem.</p>
<p><del datetime="2011-01-02T18:02:15+00:00">I have no idea whether these observations are novel or old and obvious</del>, but would love to hear from anyone who has any thoughts on this.</p>
<p><strong>EDIT:</strong> After taking a closer look at <a href="http://www.soi.city.ac.uk/~ross/papers/Applicative.html">Conor McBride and Ross Paterson's paper</a> on Applicative Functor's, I see now that he labels his ((->) a) instance methods with "S" and "K", but does not explore the subject further. So I'm leaning towards obvious.</p>
<p>Thanks for reading :)</p>
]]></content:encoded>
			<wfw:commentRss>http://coder.bsimmons.name/blog/2011/01/do-applicative-functors-generalize-the-s-k-combinators/feed/</wfw:commentRss>
		<slash:comments>5</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>17&#215;17: some Simulated Annealing updates</title>
		<link>http://coder.bsimmons.name/blog/2010/07/17x17-some-simulated-annealing-updates/</link>
		<comments>http://coder.bsimmons.name/blog/2010/07/17x17-some-simulated-annealing-updates/#comments</comments>
		<pubDate>Sun, 01 Aug 2010 02:46:06 +0000</pubDate>
		<dc:creator>jberryman</dc:creator>
				<category><![CDATA[haskell]]></category>
		<category><![CDATA[17x17]]></category>
		<category><![CDATA[Graph Theory]]></category>
		<category><![CDATA[heuristics]]></category>
		<category><![CDATA[short]]></category>
		<category><![CDATA[theory]]></category>

		<guid isPermaLink="false">http://coder.bsimmons.name/blog/?p=459</guid>
		<description><![CDATA[<blockquote><p><em>Note: this is part of a <a href="http://coder.bsimmons.name/blog/tag/17x17/">series of posts</a> is related to the &#8220;<a href="http://blog.computationalcomplexity.org/2009/11/17x17-challenge-worth-28900-this-is-not.html">17&#215;17 Challenge</a>&#8221; posted by Bill Gasarch. The goal is to color cells of a 17 by 17 grid, using only four colors, such that no</em></p></blockquote><p>&#8230; <a href="http://coder.bsimmons.name/blog/2010/07/17x17-some-simulated-annealing-updates/" class="read_more">   [ R E A D &#124; M O R E ]</a></p>]]></description>
			<content:encoded><![CDATA[<blockquote><p><em>Note: this is part of a <a href="http://coder.bsimmons.name/blog/tag/17x17/">series of posts</a> is related to the &#8220;<a href="http://blog.computationalcomplexity.org/2009/11/17x17-challenge-worth-28900-this-is-not.html">17&#215;17 Challenge</a>&#8221; posted by Bill Gasarch. The goal is to color cells of a 17 by 17 grid, using only four colors, such that no rectangle is formed from four cells of the same color.</em></p></blockquote>
<p>Just a few follow-ups to my previous <a href="http://coder.bsimmons.name/blog/2010/07/17x17-a-simulated-annealing-approach-using-thresholds/">post in which I use a simulated annealing-type algorithm</a> to find a good (hopefully complete) cover of a grid by swapping rows and columns from four identical sub-grids of 74 colors.</p>
<h2>Easing into new thresholds</h2>
<p>I modified my algorithm so that the likelihood of jumping into the highest permitted energy level is decreased over time; thus instead of having an abrupt transition to a new threshold, resulting in a steep dive, we instead <em>ease into</em> the new energy level. </p>
<p>Here is a graph of a run with the adjusted meta-heuristic (in blue) alongside a previous abrupt threshold transition run (in black). You can check compare it to the <a href="http://coder.bsimmons.name/blog/wp-content/uploads/5-2.combined-annotated.png">graph from the previous post</a>:</p>
<p><a href="http://coder.bsimmons.name/blog/wp-content/uploads/output.10000.5.smooth_vs_jagged.png"><img src="http://coder.bsimmons.name/blog/wp-content/uploads/output.10000.5.smooth_vs_jagged-300x81.png" alt="a more smooth graph vs. a graph with abrupt changes at each threshold change" title="output.10000.5.smooth_vs_jagged" width="300" height="81" class="aligncenter size-medium wp-image-460" /></a></p>
<p><span id="more-459"></span></p>
<p>Unfortunately this change didn&#8217;t cause any improvement in the solutions generated. They still seem to flatten at a grid with 19 &#8211; 22 uncolored cells.</p>
<h2>Testing a combination of sub-grids with known good solution</h2>
<p>I wondered if the lower bound I was smacking into was caused by the fact that I was trying to find a combination of four permutations <em>of the same subset</em>, and perhaps this particular subset didn&#8217;t mesh all that well with itself.</p>
<p>In the original blog posting laying out this challenge there is four-coloring of 17&#215;17 with only one cell left un-colorable in a truly painful refactoring process, I modified my script to take four separate and distinct sub-grids and perform the same shuffling procedure.</p>
<p>Rather than find the original arrangement of the colored subsets or one nearly as good, the program settles on a solution with around 30 uncolored cells. That is worse than my original version, corresponding to the fact that there are fewer cells to work with in this latter set of colored subsets: 288 vs. 296.</p>
<h2>Conclusion</h2>
<p>This doesn&#8217;t say anything about whether a full-cover can likely be obtained by permuting four overlapping copies of a single subset of colors. It does tell us that either my code is flawed, this isn&#8217;t a particularly effective method for this kind of search, or it needs to be tuned better.</p>
]]></content:encoded>
			<wfw:commentRss>http://coder.bsimmons.name/blog/2010/07/17x17-some-simulated-annealing-updates/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 6/15 queries in 0.034 seconds using disk

Served from: coder.bsimmons.name @ 2012-02-05 12:14:46 -->
