<?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; combinator</title>
	<atom:link href="http://coder.bsimmons.name/blog/tag/combinator/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>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>An &#8220;Adaptive&#8221; Move-to-Front Algorithm</title>
		<link>http://coder.bsimmons.name/blog/2009/11/an-adaptive-move-to-front-algorithm/</link>
		<comments>http://coder.bsimmons.name/blog/2009/11/an-adaptive-move-to-front-algorithm/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 05:28:34 +0000</pubDate>
		<dc:creator>jberryman</dc:creator>
				<category><![CDATA[haskell]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[combinator]]></category>
		<category><![CDATA[compression]]></category>

		<guid isPermaLink="false">http://coder.bsimmons.name/blog/?p=273</guid>
		<description><![CDATA[<p><strong>UPDATE:</strong> <em>Thanks to <a href="http://smj.posterous.com/">steve</a> for pointing out that the scheme I describe here is essentially the same as <a href="http://www.ics.uci.edu/~dan/pubs/DC-Sec5.html#Sec_5.2">Algorithm BSTW</a>.</em></p>
<p>I came up with this variation of the <a href="http://coder.bsimmons.name/blog/2009/11/the-move-to-front-mtf-transform/">Move-to-Front transform</a> which doesn&#8217;t require that there be a&#8230; <a href="http://coder.bsimmons.name/blog/2009/11/an-adaptive-move-to-front-algorithm/" class="read_more">   [ R E A D &#124; M O R E ]</a></p>]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATE:</strong> <em>Thanks to <a href="http://smj.posterous.com/">steve</a> for pointing out that the scheme I describe here is essentially the same as <a href="http://www.ics.uci.edu/~dan/pubs/DC-Sec5.html#Sec_5.2">Algorithm BSTW</a>.</em></p>
<p>I came up with this variation of the <a href="http://coder.bsimmons.name/blog/2009/11/the-move-to-front-mtf-transform/">Move-to-Front transform</a> which doesn&#8217;t require that there be a known alphabet of symbols. Instead it builds up the alphabet as it goes along and encounters a new symbol. I&#8217;m sure that this is a known algorithm, as it&#8217;s a fairly obvious variation, but I don&#8217;t know what the proper name for it is, so I&#8217;m calling it an <a href="http://www.cs.sfu.ca/CC/365/li/squeeze/AdaptiveHuff.html">Adaptive</a> Move-to-Front. </p>
<p>I&#8217;m very interested in hearing if this is similar or identical to any other algorithms, so if anyone has any insights, please comment!</p>
<h3>Differences from the Standard MTF Transform:</h3>
<p>The <a href="http://compgt.googlepages.com/mtf">traditional MTF algorithm</a>, as I understand it, uses some known ordered alphabet of symbols (e.g. the bytes from 0-255, or the letters a-z), so presumably, one need not store this alphabet along with the encoded/compressed data. </p>
<p>With the algorithm I describe here though, the final permutation of the alphabet list, output by the encoder, must be retained to decode the message. The encoded message is identical to the output of the traditional MTF transform, <em>except</em> where a symbol is encoded which <em>has not appeared previously</em>.</p>
<p>Here we have zipped the output of the standard MTF (the <code>fst</code>) with the adaptive version (the <code>snd</code>) to make it easy to compare elements:</p>
<blockquote><p><strong>Message:</strong> <em>&#8220;the rrrrain in sssspain falls maaiinly on the plain&#8221;</em></p>
<p><strong>Output</strong> (standard MTF, adaptive):</p>
<p><code>[(116,0),(105,1),(103,2),(35,3),(115,4),(0,0),(0,0),(0,0),(101,5),(107,6),(112,7),(4,4),(2,2),(2,2),(2,2),(116,8),(0,0),(0,0),(0,0),(115,9),(5,5),(5,5),(5,5),(5,5),(109,10),(4,4),(113,11),(0,0),(7,7),(4,4),(114,12),(4,4),(0,0),(7,7),(0,0),(7,7),(6,6),(121,13),(6,6),(116,14),(4,4),(2,2),(14,14),(14,14),(14,14),(3,3),(13,13),(8,8),(10,10),(10,10),(8,8)]</code></p>
</blockquote>
<p>The standard algorithm was working with the ASCII alphabet, so each new symbol is located somewhere far back into the alphabet; it is then moved to the front. In the adaptive version, when we see a new symbol, it is automatically made the next in our running alphabet and then of course moved to the front. </p>
<p>This means that with the adaptive version, for any given stretch from the beginning of the encoded message, we are using the minimal number of different index integers to encode the stream, always choosing the next greatest integer when we require a new one. Here is the output of the adaptive version alone:</p>
<blockquote>
<p><strong>Encoded phrase:</strong><br />
<code><br />
[0,1,2,3,4,0,0,0,5,6,7,4,2,2,2,8,0,0,0,9,5,5,5,5,10,4,<br />
11,0,7,4,12,4,0,7,0,7,6,13,6,14,4,2,14,14,14,3,13,8,<br />
10,10,8]</code></p>
<p><strong>Final permutation of minimal dictionary list:</strong><br />
<code>"nialp ehtoymsfr"</code>
</p></blockquote>
<p>What these means for actual compression schemes on a binary level, I have no idea, but I would like to explore this topic much more. Without further ado, here is some code.</p>
<h3>The Encoder:</h3>
<p><div class="vimblock"><br>
<span class="Comment">&gt;</span>&nbsp;<span class="PreProc">import</span>&nbsp;Data.List<br>
<span class="Comment">&gt;</span>&nbsp;<span class="PreProc">import</span>&nbsp;Control.Arrow<br>
<br></div></p>
<p>This &#8220;adaptive move-to-front&#8221; encoder works in the same way as the standard algorithm, except that we start out with an empty alphabet list and build it up as we see new elements not yet in our list.</p>
<p>Essentially if, while searching for an element, we hit the empty list [], we pretend that the element we were looking for was at the end of the list.</p>
<p>This is exactly what happens in the traditional algorithm: when we try to encode a symbol that we haven&#8217;t yet encountered, we venture into a new part of the alphabet list that we haven&#8217;t touched yet.</p>
<p><div class="vimblock"><br>
<span class="Comment">&gt;</span>&nbsp;encode&nbsp;<span class="Statement">::</span>&nbsp;(<span class="Type">Eq</span>&nbsp;b)<span class="Statement">=&gt;</span>&nbsp;[b]&nbsp;<span class="Statement">-&gt;</span>&nbsp;([b],&nbsp;[<span class="Type">Int</span>])<br>
<span class="Comment">&gt;</span>&nbsp;encode&nbsp;<span class="Statement">=</span>&nbsp;mapAccumL&nbsp;(<span class="Identifier">flip</span>&nbsp;mtf)&nbsp;[]&nbsp;&nbsp;<span class="Type">where</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;We push the current element to the front of the lookup list...<br>
<br>
<span class="Comment">&gt;</span>&nbsp;&nbsp;&nbsp;&nbsp; mtf&nbsp;x&nbsp;<span class="Statement">=</span>&nbsp;first&nbsp;(x<span class="Statement">:</span>)&nbsp;<span class="Statement">.</span>&nbsp;enc&nbsp;<span class="Constant">0</span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="Type">where</span><br>
<br>
&nbsp;...after returning the index of the element in the list<br>
&nbsp;along with the new list with the element deleted:<br>
<br>
<span class="Comment">&gt;</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;enc&nbsp;i&nbsp;[]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Statement">=</span>&nbsp;([],i)&nbsp;&nbsp;<span class="Comment">-- &lt; index as if x was last</span><br>
<span class="Comment">&gt;</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;enc&nbsp;i&nbsp;(a<span class="Statement">:</span>as)&nbsp;<span class="Statement">|</span>&nbsp;x&nbsp;<span class="Statement">==</span>&nbsp;a&nbsp;&nbsp;&nbsp;&nbsp;<span class="Statement">=</span>&nbsp;(as,i)&nbsp;&nbsp;<span class="Comment">-- &lt; delete the x element</span><br>
<span class="Comment">&gt;</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Statement">|</span>&nbsp;<span class="Identifier">otherwise</span>&nbsp;<span class="Statement">=</span>&nbsp;first&nbsp;(a<span class="Statement">:</span>)&nbsp;<span class="Statement">$</span>&nbsp;enc&nbsp;(i<span class="Statement">+</span><span class="Constant">1</span>)&nbsp;as&nbsp;<br>
<br></div></p>
<h3>The Decoder</h3>
<p>Our decoder requires that we pass it the final permutation of the symbol list, along with the encoded list of indexes. It then simply does the reverse of the encoding function.</p>
<p>To decode we follow these steps:</p>
<ol>
<li>    Return the head of the list of symbols</li>
<li>     Re-insert the symbol into the index location specified by the head of the encoded/index list</li>
<li>Move on to the next encoded index, using the new list of symbols. go to (1)</li>
</ol>
<p><div class="vimblock"><br>
<span class="Comment">&gt;</span>&nbsp;<span class="Comment">-- our Adaptive MTF decoder:</span><br>
<span class="Comment">&gt;</span>&nbsp;decode&nbsp;<span class="Statement">::</span>&nbsp;[b]&nbsp;<span class="Statement">-&gt;</span>&nbsp;[<span class="Type">Int</span>]&nbsp;<span class="Statement">-&gt;</span>&nbsp;[b]<br>
<span class="Comment">&gt;</span>&nbsp;decode&nbsp;l&nbsp;<span class="Statement">=</span>&nbsp;<span class="Identifier">snd</span>&nbsp;<span class="Statement">.</span>&nbsp;mapAccumR&nbsp;dec&nbsp;l&nbsp;<span class="Type">where</span><br>
<br>
&nbsp;return head of alphabet and insert it back into alphabet list at <br>
&nbsp;the index given by the current element of our encoded index list:<br>
<br>
<span class="Comment">&gt;</span>&nbsp;&nbsp;&nbsp;&nbsp;dec&nbsp;(a<span class="Statement">:</span>as)&nbsp;i&nbsp;<span class="Statement">=</span>&nbsp;(insertAt&nbsp;a&nbsp;i&nbsp;as,&nbsp;a)<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;takes an element and makes it the new element at the specified index<br>
&nbsp;in the provided list. Fails if it touches a [].<br>
<br>
<span class="Comment">&gt;</span>&nbsp;&nbsp;&nbsp;&nbsp;insertAt&nbsp;<span class="Statement">::</span>&nbsp;a&nbsp;<span class="Statement">-&gt;</span>&nbsp;<span class="Type">Int</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;[a]&nbsp;<span class="Statement">-&gt;</span>&nbsp;[a]<br>
<span class="Comment">&gt;</span>&nbsp;&nbsp;&nbsp;&nbsp;insertAt&nbsp;a' i&nbsp;<span class="Statement">=</span>&nbsp;ins&nbsp;i<br>
<span class="Comment">&gt;</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="Type">where</span>&nbsp;ins&nbsp;<span class="Constant">0</span>&nbsp;as&nbsp;<span class="Statement">=</span>&nbsp;a'<span class="Statement">:</span>as<br>
<span class="Comment">&gt;</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ins&nbsp;i' (a<span class="Statement">:</span>as)&nbsp;<span class="Statement">=</span>&nbsp;a&nbsp;<span class="Statement">:</span>&nbsp;ins&nbsp;(i' <span class="Statement">-</span>&nbsp;<span class="Constant">1</span>)&nbsp;as<br>
<br></div></p>
]]></content:encoded>
			<wfw:commentRss>http://coder.bsimmons.name/blog/2009/11/an-adaptive-move-to-front-algorithm/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>The State Monad: a tutorial for the confused?</title>
		<link>http://coder.bsimmons.name/blog/2009/10/the-state-monad-a-tutorial-for-the-confused/</link>
		<comments>http://coder.bsimmons.name/blog/2009/10/the-state-monad-a-tutorial-for-the-confused/#comments</comments>
		<pubDate>Sat, 24 Oct 2009 00:16:57 +0000</pubDate>
		<dc:creator>jberryman</dc:creator>
				<category><![CDATA[haskell]]></category>
		<category><![CDATA[combinator]]></category>
		<category><![CDATA[monads]]></category>
		<category><![CDATA[state]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://coder.bsimmons.name/blog/?p=230</guid>
		<description><![CDATA[<p><em>I&#8217;ve written this <del>brief</del> tutorial on haskell&#8217;s <code>State</code> monad to help bridge some of the elusive gaps that I encountered in other explanations I&#8217;ve read, and to try to cut through all the sticky abstraction. This is written for someone</em>&#8230; <a href="http://coder.bsimmons.name/blog/2009/10/the-state-monad-a-tutorial-for-the-confused/" class="read_more">   [ R E A D &#124; M O R E ]</a></p>]]></description>
			<content:encoded><![CDATA[<p><em>I&#8217;ve written this <del>brief</del> tutorial on haskell&#8217;s <code>State</code> monad to help bridge some of the elusive gaps that I encountered in other explanations I&#8217;ve read, and to try to cut through all the sticky abstraction. This is written for someone who has a good understanding of the <code>Maybe</code> and <code>List</code> monads, but has gotten stuck trying to understand State. I hope it&#8217;s helpful!</em></p>
<h4>The Data Declaration:</h4>
<p>To understand a monad you look at it&#8217;s datatype and then at the definition for bind (<code>>>=</code>). Most monad tutorials start by showing you the data declaration of a <code>State s a</code> in passing, as if it needed no explanation:</p>
<p><blockquote class="vimblock"><br />
<span class="Type">newtype</span>&nbsp;State&nbsp;s&nbsp;a&nbsp;<span class="Statement">=</span>&nbsp;State&nbsp;{&nbsp;runState&nbsp;<span class="Statement">::</span>&nbsp;s&nbsp;<span class="Statement">-&gt;</span>&nbsp;(a,&nbsp;s)&nbsp;}<br />
<br /></blockquote></p>
<p>But this <em>does</em> need explanation! This is crazy stuff and nothing like what we&#8217;ve seen before in the list monad or the Maybe monad:</p>
<ol>
<li>The constructor <code>State</code> <strong>holds a function</strong>, not just a simple value like Maybe&#8217;s <code>Just</code>. This looks weird.</li>
<li>Furthermore there is an accessor function <code>runState</code> <strong>with a weirdly imperative-sounding name</strong>.</li>
<li>Finally, there are <strong>two free variables</strong> on the left side, not just one.</li>
</ol>
<p>Yikes! Let&#8217;s try to get our head on straight and figure this out:</p>
<p>First of all the State monad is just <strong>an abstraction for a function that takes a state and returns an intermediate value and some new state value</strong>. To formalize this abstraction in haskell, we wrap the function in the newtype <code>State</code> allowing us to define a <code>Monad</code> instance.</p>
<p>Stepping back from the abstract and conceptual, what we have is <strong>the <code>State</code> constructor acting as a container for a function <code>:: s -> (a,s)</code></strong>, while the definition for bind just provides <strong>a mechanism for &#8220;composing&#8221; a function <code>state -> (val,state)</code> within the <code>State</code> wrapper</strong>.</p>
<p>Just as you can chain together functions using <code>(.)</code> as in <code>(+1) . (*3) . head :: (Num a) => [a] -> a</code>, <strong>the state monad gives you <code>(>>=)</code> to chain together functions that look essentially like <code>:: a -> s -> (a,s) </code>into a single function <code>:: s -> (a,s)</code></strong>.</p>
<p>Let&#8217;s bring the discussion back to actual code and try to make sure we understand those three points of weirdness outlined above. Here&#8217;s a stupid example of a function that can be &#8220;contained&#8221; in our state type:</p>
<p><blockquote class="vimblock"><br />
<span class="Comment">-- look at our counter and return &quot;foo&quot; or &quot;bar&quot;</span><br />
<span class="Comment">-- along with the incremented counter:</span><br />
fromStoAandS&nbsp;<span class="Statement">::</span>&nbsp;<span class="Type">Int</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;(<span class="Type">String</span>,<span class="Type">Int</span>)<br />
fromStoAandS&nbsp;c&nbsp;<span class="Statement">|</span>&nbsp;c&nbsp;<span class="Statement">`mod`</span>&nbsp;<span class="Constant">5</span>&nbsp;<span class="Statement">==</span>&nbsp;<span class="Constant">0</span>&nbsp;<span class="Statement">=</span>&nbsp;(<span class="Constant">&quot;foo&quot;</span>,c<span class="Statement">+</span><span class="Constant">1</span>)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Statement">|</span>&nbsp;<span class="Identifier">otherwise</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="Statement">=</span>&nbsp;(<span class="Constant">&quot;bar&quot;</span>,c<span class="Statement">+</span><span class="Constant">1</span>)<br />
<br /></blockquote></p>
<p>If we just wrap that in a <code>State</code> constructor, we&#8217;re in the State monad:</p>
<p><blockquote class="vimblock"><br />
stateIntString&nbsp;<span class="Statement">::</span>&nbsp;State&nbsp;<span class="Type">Int</span>&nbsp;<span class="Type">String</span><br />
stateIntString&nbsp;<span class="Statement">=</span>&nbsp;State&nbsp;fromStoAandS<br />
<br /></blockquote></p>
<p>But what about <code>runState</code>? <strong>All that does of course is give us the &#8220;contents&#8221; of our State constructor: i.e. a single function <code>:: s -> (a,s)</code></strong>. It could have been named <code>stateFunction</code> but someone thought it would be really clever to be able to write things like:</p>
<p><blockquote class="vimblock"><br />
runState&nbsp;stateIntString&nbsp;<span class="Constant">1</span><br />
<br /></blockquote></p>
<p>See, all we&#8217;ve done there is used <code>runState</code> to take our function (<code>fromStoAandS</code>) out of the State wrapper; it is then applied it to it&#8217;s initial state (<code>1</code>). We would do this <code>runState</code> business <strong>after building up our composed function with <code>(>>=)</code>, <code>mapM</code>, etc</strong>.</p>
<p>That leaves point 3 unanswered. Let&#8217;s start exploring the instance declaration for State.</p>
<h4>The Instance Declaration</h4>
<p>We&#8217;ll start with the first line:</p>
<p><blockquote class="vimblock"><br />
<span class="Type">instance</span>&nbsp;<span class="Type">Monad</span>&nbsp;(State&nbsp;s)&nbsp;<span class="Type">where</span><br />
<br /></blockquote></p>
<p><strong>We create a Monad instance for (State s) not State</strong>. You can think of this as a <strong>partially-applied type</strong>, which is equivalent to a partially applied function: </p>
<blockquote><p><code>(State) < ==> (+)</code><br />
<code>(State s) < ==> (1+)</code><br />
<code>(State s a) < == (1+2)</code></code></p></blockquote>
<p><strong>So (<code>State s</code>) is the <code>m</code> in our <code>m a</code>.</strong> This means the <em>type</em> of our state will remain the same as we compose our function with <code>(>>=)</code>, whereas the intermediate values (the <code>a</code>s) may well change type as they move through the chain.</p>
<p>Before we move on to the meat of the instance declaration, I&#8217;d like to get your mind calibrated to look at the definitions for <code>return</code> and <code>(>>=)</code>:</p>
<p>Whenever you see <code>m a</code>, as in </p>
<blockquote><p><code>return :: (Monad m) => a -> m a</code> </p></blockquote>
<p>&#8230;remember that <code>m a</code> is actually </p>
<blockquote><p><code>State s a</code></p></blockquote>
<p>&#8230;and when you remember <code>(State s a)</code>, <em>think</em> </p>
<blockquote><p><code>(s -> (s,a))</code>. </p></blockquote>
<p><strong>So in your mind, <code>m a</code> becomes <code>function :: s -> (a,s)</code> everywhere you see it</strong>. Just forget about the silly State wrapper (<a href="http://www.haskell.org/haskellwiki/Newtype">the compiler does</a>)!</p>
<h4>The definition of return and Bind</h4>
<p>Let&#8217;s wet our feet with the definition for <code>return</code>:</p>
<p><blockquote class="vimblock"><br />
&nbsp;&nbsp;&nbsp;&nbsp;<span class="Identifier">return</span>&nbsp;a&nbsp;<span class="Statement">=</span>&nbsp;State&nbsp;<span class="Statement">$</span>&nbsp;<span class="Statement">\</span>s&nbsp;<span class="Statement">-&gt;</span>&nbsp;(a,&nbsp;s)<br />
<br /></blockquote></p>
<p>All return does is take some value a and make a function that takes a state value and returns (value, state value). If we ignore the whole State wrapping business, then return is just <code>(,) :: a -> b -> (a, b)</code></p>
<p>Now recall the definition of bind:</p>
<p><blockquote class="vimblock"><br />
(<span class="Statement">&gt;&gt;=</span>)&nbsp;<span class="Statement">::</span>&nbsp;(<span class="Type">Monad</span>&nbsp;m)&nbsp;<span class="Statement">=&gt;</span>&nbsp;m&nbsp;a&nbsp;<span class="Statement">-&gt;</span>&nbsp;(a&nbsp;<span class="Statement">-&gt;</span>&nbsp;m&nbsp;b)&nbsp;<span class="Statement">-&gt;</span>&nbsp;m&nbsp;b<br />
<br /></blockquote></p>
<p>Which in our case is:</p>
<p><blockquote class="vimblock"><br />
(<span class="Statement">&gt;&gt;=</span>)&nbsp;<span class="Statement">::</span>&nbsp;&nbsp;State&nbsp;s&nbsp;a&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="Statement">-&gt;</span>&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(a&nbsp;<span class="Statement">-&gt;</span>&nbsp;State&nbsp;s&nbsp;b)&nbsp;<span class="Statement">-&gt;</span>&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;State&nbsp;s&nbsp;b<br />
<br /></blockquote></p>
<p>And which is just a silly abstraction for the <strong>super special function composition</strong> that&#8217;s going on, which looks like:</p>
<p><blockquote class="vimblock"><br />
(<span class="Statement">&gt;&gt;=</span>)&nbsp;<span class="Statement">::</span>&nbsp;&nbsp;(s&nbsp;<span class="Statement">-&gt;</span>&nbsp;(a,s))&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Statement">-&gt;</span>&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(a&nbsp;<span class="Statement">-&gt;</span>&nbsp;s&nbsp;<span class="Statement">-&gt;</span>&nbsp;(b,s))&nbsp;&nbsp;<span class="Statement">-&gt;</span>&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(s&nbsp;<span class="Statement">-&gt;</span>&nbsp;(b,s))<br />
<br /></blockquote></p>
<p>So on the left hand side of (<code>>>=</code>) is a function that takes some initial state and produces a <code>(value,new_state)</code>. On the right hand side is a function that takes that value and that new_state and generates it&#8217;s own <code>(new_value, newer_state)</code>. <strong>The job of bind is simply to combine those two functions into one bigger function from the initial state to <code>(new_value,newer_state)</code></strong>, just like the simple function composition operator<code> (.) :: (b -> c) -> (a -> b) -> a -> c</code></p>
<p>At this point, we can show you bind&#8217;s definition:</p>
<p><blockquote class="vimblock"><br />
&nbsp;&nbsp;&nbsp;&nbsp;m&nbsp;<span class="Statement">&gt;&gt;=</span>&nbsp;k&nbsp;&nbsp;<span class="Statement">=</span>&nbsp;State&nbsp;<span class="Statement">$</span>&nbsp;<span class="Statement">\</span>s&nbsp;<span class="Statement">-&gt;</span>&nbsp;<span class="Statement">let</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(a,&nbsp;s')&nbsp;<span class="Statement">=</span>&nbsp;runState&nbsp;m&nbsp;s<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="Statement">in</span>&nbsp;runState&nbsp;(k&nbsp;a)&nbsp;s'<br />
<br /></blockquote></p>
<p>You can work through that on your own, keeping in mind that we&#8217;re doing function composition here. The main thing to remember is that the <code>s</code> at the top, right after <code>State</code>, <strong>won&#8217;t actually be bound to a value until we unwrap the function with <code>runState</code> and pass it the initial state value</strong>, at which point we can evaluate the entire chain.</p>
<h4>A Final Note About The State Monad with <code>do</code> Notation</h4>
<p><code>State</code> is often used like this:</p>
<p><blockquote class="vimblock"><br />
stateFunction&nbsp;<span class="Statement">::</span>&nbsp;State&nbsp;[a]&nbsp;()<br />
stateFunction&nbsp;<span class="Statement">=</span>&nbsp;<span class="Statement">do</span>&nbsp;x&nbsp;<span class="Statement">&lt;-</span>&nbsp;pop<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; pop<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; push&nbsp;x<br />
<br /></blockquote></p>
<p>Remember that the functions above are desugaring to <code>m >>= \a-> f... </code>or if there is no left arrow on the previous line: <code>m >>= \_-> f...</code> That <code>a</code> in there is an intermediate value, the <code>fst</code> in the tuple. The push function might look like:</p>
<p><blockquote class="vimblock"><br />
push&nbsp;<span class="Statement">::</span>&nbsp;State&nbsp;[a]&nbsp;()<br />
push&nbsp;a&nbsp;<span class="Statement">=</span>&nbsp;State&nbsp;<span class="Statement">$</span>&nbsp;<span class="Statement">\</span>as&nbsp;<span class="Statement">-&gt;</span>&nbsp;(()&nbsp;,&nbsp;a<span class="Statement">:</span>as)<br />
<br /></blockquote></p>
<p>The function doesn&#8217;t return any meaningful <code>a</code> value, so we don&#8217;t bind it by using the <code>< -</code>. For more work with do notation and some fine pictures, see <a href="http://forums.somethingawful.com/showthread.php?threadid=2841145&#038;pagenumber=6#post346173552">Bonus's post on something awful</a>.</p>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://coder.bsimmons.name/blog/2009/10/the-state-monad-a-tutorial-for-the-confused/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>The Total Recall combinator</title>
		<link>http://coder.bsimmons.name/blog/2009/04/the-total-recall-combinator/</link>
		<comments>http://coder.bsimmons.name/blog/2009/04/the-total-recall-combinator/#comments</comments>
		<pubDate>Wed, 01 Apr 2009 17:47:05 +0000</pubDate>
		<dc:creator>jberryman</dc:creator>
				<category><![CDATA[haskell]]></category>
		<category><![CDATA[combinator]]></category>
		<category><![CDATA[short]]></category>

		<guid isPermaLink="false">http://coder.bsimmons.name/blog/?p=36</guid>
		<description><![CDATA[<blockquote><pre>
infixr 9 .:

(.:) :: (b -> c) -> (a -> a1 -> b) -> a -> a1 -> c
(.:) = (.)(.)(.)
</pre>
</blockquote>
<p>This can be used to compose a string of functions with a binary function&#8230; <a href="http://coder.bsimmons.name/blog/2009/04/the-total-recall-combinator/" class="read_more">   [ R E A D &#124; M O R E ]</a></p>]]></description>
			<content:encoded><![CDATA[<blockquote><pre>
infixr 9 .:

(.:) :: (b -> c) -> (a -> a1 -> b) -> a -> a1 -> c
(.:) = (.)(.)(.)
</pre>
</blockquote>
<p>This can be used to compose a string of functions with a binary function stuck on the end. For example:</p>
<blockquote><pre>
lookupPlusOne :: (Ord k, Monad m, Num n) => k -> Map k n -> m n
lookupPlusOne = liftM (+1) .: lookup
</pre>
</blockquote>
<p>(picked up from some folks on <a href="http://www.haskell.org/haskellwiki/IRC_channel" target="_blank">#haskell</a>)</p>
]]></content:encoded>
			<wfw:commentRss>http://coder.bsimmons.name/blog/2009/04/the-total-recall-combinator/feed/</wfw:commentRss>
		<slash:comments>2</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 0.031 seconds using disk

Served from: coder.bsimmons.name @ 2012-02-05 11:35:27 -->
