<?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; state</title>
	<atom:link href="http://coder.bsimmons.name/blog/tag/state/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>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>A Befunge-93 Interpreter</title>
		<link>http://coder.bsimmons.name/blog/2010/01/a-befunge-93-interpreter/</link>
		<comments>http://coder.bsimmons.name/blog/2010/01/a-befunge-93-interpreter/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 21:13:50 +0000</pubDate>
		<dc:creator>jberryman</dc:creator>
				<category><![CDATA[haskell]]></category>
		<category><![CDATA[Array]]></category>
		<category><![CDATA[EsotericLanguages]]></category>
		<category><![CDATA[MonadTransformers]]></category>
		<category><![CDATA[release]]></category>
		<category><![CDATA[state]]></category>

		<guid isPermaLink="false">http://coder.bsimmons.name/blog/?p=302</guid>
		<description><![CDATA[<p><em>I just finished an initial release of an interpreter for the <a href="http://en.wikipedia.org/wiki/Befunge">befunge</a> programming language, based on the <a href="http://catseye.tc/projects/befunge93/">&#8217;93 spec</a>. The project was quite fun! My goal was to produce a well-designed program with performance that didn&#8217;t suck too</em>&#8230; <a href="http://coder.bsimmons.name/blog/2010/01/a-befunge-93-interpreter/" class="read_more">   [ R E A D &#124; M O R E ]</a></p>]]></description>
			<content:encoded><![CDATA[<p><em>I just finished an initial release of an interpreter for the <a href="http://en.wikipedia.org/wiki/Befunge">befunge</a> programming language, based on the <a href="http://catseye.tc/projects/befunge93/">&#8217;93 spec</a>. The project was quite fun! My goal was to produce a well-designed program with performance that didn&#8217;t suck too bad. Here are some highlights:</em></p>
<h2>Design</h2>
<p>I found that writing the core functionality of the interpreter took almost no time, once I settled on the approach I would take. I used a monad transformer for the first time, <code>StateT</code>: </p>
<p><blockquote class="vimblock"><br />
<span class="Type">type</span>&nbsp;REPL&nbsp;a&nbsp;<span class="Statement">=</span>&nbsp;StateT&nbsp;ProgramState&nbsp;<span class="Type">IO</span>&nbsp;a<br />
<br /></blockquote></p>
<p>This let me pass around the state of the computation in the <code>State</code> monad while doing IO actions. This made some potentially-awkward befunge commands really easy to implement.<br />
<span id="more-302"></span><br />
Here is an excerpt from the function <code>execute :: Char -> REPL ()</code> which reads the befunge character at our position and returns the code to execute:</p>
<p><blockquote class="vimblock"><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- Pop value and output as an integer. funge-98 spec calls for</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- integer to be followed by a space, so we'll do that too:</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Constant">'.'</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;<span class="Statement">do</span>&nbsp;i&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; liftIO&nbsp;<span class="Statement">$</span>&nbsp;<span class="Identifier">putStr</span>&nbsp;<span class="Statement">$</span>&nbsp;<span class="Identifier">show</span>&nbsp;i&nbsp;<span class="Statement">++</span><span class="Constant">&quot; &quot;</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- Pop value and output as ASCII character</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Constant">','</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;<span class="Statement">do</span>&nbsp;i&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; liftIO&nbsp;<span class="Statement">$</span>&nbsp;<span class="Identifier">putChar</span>&nbsp;<span class="Statement">$</span>&nbsp;chr&nbsp;i<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Constant">'</span><span class="Special">\\</span><span class="Constant">'</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;<span class="Statement">do</span>&nbsp;(a,b)&nbsp;<span class="Statement">&lt;-</span>&nbsp;pop2<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;push&nbsp;a<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;push&nbsp;b<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Constant">':'</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;<span class="Statement">do</span>&nbsp;a&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; replicateM_&nbsp;<span class="Constant">2</span>&nbsp;(push&nbsp;a)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;<span class="Comment">-- program flow commands: --</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Constant">' '</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;<span class="Identifier">return</span>&nbsp;()&nbsp;&nbsp;&nbsp;&nbsp;<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Constant">'&gt;'</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;setDirection&nbsp;right<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Constant">'&lt;'</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;setDirection&nbsp;left&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Constant">'^'</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;setDirection&nbsp;up<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Constant">'v'</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;setDirection&nbsp;down<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Constant">'?'</span>&nbsp;<span class="Statement">-&gt;</span>&nbsp;getRandomDirection&nbsp;<span class="Statement">&gt;&gt;=</span>&nbsp;setDirection&nbsp;<br />
<br /></blockquote></p>
<p>And here is the program state that gets passed in the monad:</p>
<p><blockquote class="vimblock"><br />
<span class="Type">data</span>&nbsp;ProgramState&nbsp;<span class="Statement">=</span>&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;ES&nbsp;{&nbsp;<span class="Comment">-- state of the code and stack:</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; code&nbsp;<span class="Statement">::</span>&nbsp;Code,&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; stack&nbsp;<span class="Statement">::</span>&nbsp;Stack,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- state of program flow:</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; position&nbsp;<span class="Statement">::</span>&nbsp;Position,&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; direction&nbsp;<span class="Statement">::</span>&nbsp;Direction,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; haltBit&nbsp;<span class="Statement">::</span>&nbsp;<span class="Type">Bool</span>,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- random generator:</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; randGen&nbsp;<span class="Statement">::</span>&nbsp;StdGen,&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- errors or other messages we collect:</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; messages&nbsp;<span class="Statement">::</span>&nbsp;[<span class="Type">String</span>],<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- should we announce messages and warnings?:</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; verbose&nbsp;<span class="Statement">::</span>&nbsp;<span class="Type">Bool</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;<br />
<br /></blockquote></p>
<p>I only use the accessor functions (as opposed to pattern matching) to reach into the state in my code, so it was easy to add another state parameter if I wanted to extend the functionality somewhere.</p>
<p>Finally here is the evaluation loop that ties the core of the interpreter together:</p>
<p><blockquote class="vimblock"><br />
evalLoop&nbsp;<span class="Statement">::</span>&nbsp;REPL&nbsp;()<br />
evalLoop&nbsp;<span class="Statement">=</span>&nbsp;<span class="Statement">do</span><br />
&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- extract the command at our position &amp; execute it:</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;getCmd&nbsp;<span class="Statement">&gt;&gt;=</span>&nbsp;execute<br />
&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- print messages in the queue (unless quiet), and clear it:</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;printMessages<br />
&nbsp;&nbsp;&nbsp;&nbsp; <span class="Comment">-- halt if @ command issued, else move and recurse:</span><br />
&nbsp;&nbsp;&nbsp;&nbsp;halting&nbsp;<span class="Statement">&lt;-</span>&nbsp;gets&nbsp;haltBit<br />
&nbsp;&nbsp;&nbsp;&nbsp;unless&nbsp;halting&nbsp;(move&nbsp;<span class="Statement">&gt;&gt;</span>&nbsp;evalLoop)&nbsp;<br />
<br /></blockquote></p>
<p>I found the most time-consuming parts of this project were in the design decisions and behaviour tweaks related to holes in the &#8217;93 spec, and tracking down a few silly bugs that came from wrong assumptions about the spec. </p>
<p>Vital in debugging were the <a href="http://users.tkk.fi/~mniemenm/befunge/ccbi.html">CCBI interpreter</a> as well as the <a href="http://mearie.org/projects/pyfunge/">pyfunge interpreter.</a> It&#8217;s difficult to debug an interpreter when you don&#8217;t whether the befunge code you are testing on is buggy or whether your interpreter is!</p>
<p>One last detail that I am proud of is the test suite that I have integrated into my darcs repo. Darcs automatically runs the befunge-93 portion of the amazing <a href="http://iki.fi/matti.niemenmaa/befunge/mycology.html">mycology test suite</a> by Matti Niemenmaa on each commit, as well as two smaller <a href="http://www.phlamethrower.co.uk/befunge/#files">test befunge programs</a> from phlamethrower, testing that the interpreter hasn&#8217;t changed behavior.</p>
<h2>Play With It</h2>
<p>You can check out the full source for the program <a href="http://coder.bsimmons.name/code/Befunge/Befunge.hs">here</a>, or get my whole darcs repository with:</p>
<blockquote><p>
<code>$ darcs get --tag=v0.2 http://coder.bsimmons.name/code/Befunge</code>
</p></blockquote>
<p>And here are a few nice programs to try out, written by folks cleverer than I, and stolen from vsync&#8217;s funge stuff <a href="http://quadium.net/funge/downloads/bef93src/">here</a>.</p>
<p><em>aturley.bf</em> by Andrew Turley:</p>
<blockquote><pre>
>84*>:#v_55+"ude.ub@yelruta">:#,_@>188*+>\02p\12p\:22p#v_$    55+,1-         v
    ^  0 v +1\                   _^#-+*<>22g02g*"_@"*-!1- #v_v>
       >:>::3g: ,\188                  ^^               -1\g21\g22
<p3 \"_":<
________________________________@_________________________________^  p3\"@":<
</pre>
</p3></pre>
</blockquote>
<p><em>life.bf</em> by Dmitry M Litvinov:</p>
<blockquote><pre>
v>>31g> ::51gg:2v++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9p BXY|-+<v3 *89<%+ *                                                      *   +
21 >98 *7^>+\-0|< + *                                                     *    +
*5 ^:+ 1pg15\,:< + *                                                     ***  +
10^  <>$25*,51g1v+                                                            +
-^ p< | -*46p15:+<+                                                            +
> 31^> 151p>92*4v+                                                            +
 ^_ ".",   ^ vp1< +                                                            +
>v >41p      >0 v+                                                            +
:5! vg-1g15-1g14< +                                                            +
+1-+>+41g1-51gg+v+                                                            +
1p-1vg+1g15-1g14< +                                                            +
g61g>+41g51g1-g+v+                                                            +
14*1v4+g+1g15g14< +                           * *                              +
5>^4>1g1+51g1-g+v+                           * *                              +
^ _^v4+gg15+1g14< +                           ***                              +
>v! >1g1+51g1+g+v+                                                            +
g8-v14/*25-*4*88< +                                                            +
19+>g51gg" "- v  +                                                            +
4*5  v< v-2:_3v+                                                            +
 >^   |!-3_$  v< -+                                                            +
^    < <      <|<+                                                         ***+
>g51gp ^ >51gp^>v+                                                            +
^14"+"< ^g14"!"<++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
</pre>
<p></v3></pre>
</blockquote>
<p><em>prime.bf</em> by Kalyna Zazelenchuk:</p>
<blockquote><pre>
222p35*89+*11p>133p                   >33g1+33p   22g33g- v>22g33g%#v_v
 o                                                        >|
  2                             v,,,,, ,,,,,.g22"is prime."< 1                            >    v^                             < ^_@#-g11g22p22+1g22,*25<,,,,,,,,,,,,,.g22"is not prime."<
</pre>
</pre>
</blockquote>
<p>There is still a lot that could be done, but I think I&#8217;m done with it for now. Thanks for looking!</p>
]]></content:encoded>
			<wfw:commentRss>http://coder.bsimmons.name/blog/2010/01/a-befunge-93-interpreter/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>
	</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.054 seconds using disk

Served from: coder.bsimmons.name @ 2012-02-05 11:12:32 -->
