<?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>David R. MacIver &#187; haskell</title>
	<atom:link href="http://www.drmaciver.com/tag/haskell/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.drmaciver.com</link>
	<description></description>
	<lastBuildDate>Tue, 07 Feb 2012 11:12:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Writing things right</title>
		<link>http://www.drmaciver.com/2009/01/writing-things-right/</link>
		<comments>http://www.drmaciver.com/2009/01/writing-things-right/#comments</comments>
		<pubDate>Mon, 19 Jan 2009 11:15:14 +0000</pubDate>
		<dc:creator>david</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[programming languages]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.drmaciver.com/?p=256</guid>
		<description><![CDATA[OO has contributed many big and important innovations to programming. Among these, the foremost is that you write functions after rather than before their argument. No, really. It&#8217;s not just OO languages of course. Concatenative languages do the same thing. There&#8217;s a long history of mathematicians doing it as well (though we don&#8217;t like to [...]]]></description>
			<content:encoded><![CDATA[<p>OO has contributed many big and important innovations to programming. Among these, the foremost is that you write functions after rather than before their argument.</p>
<p>No, really.</p>
<p>It&#8217;s not just OO languages of course. Concatenative languages do the same thing. There&#8217;s a long history of mathematicians doing it as well (though we don&#8217;t like to talk about them. The cool mathematicians all write their functions on the left).</p>
<p>It&#8217;s funny how attached people get to this fact though.</p>
<p>Consider the following piece of Scala code:</p>
<pre>object StringUtils{
  /**
   * Trims whitespace from the end of s.
   */
  def rtrim(s : String) = ...
}</pre>
<p>We can invoke this as StringUtils.rtrim(myString). Or if we import StringUtils, just rtrim(myString);</p>
<p>People get very upset if you ask them to do so though, and they go to all sorts of lengths to avoid it.<br />
Consider the following three examples from different languages:</p>
<pre>
Scala:

object StringUtils{
   implicit def string2RTrim(s : String) = new { def rtrim = ...; }
}

Ruby:

class String
  def rtrim
  ...
  end
end

C#:

class StringUtils{
   public static String rtrim(this String s) {
     ...
   }
}</pre>
<p>What do these achieve over the previous version? Simple: You can write myString.rtrim instead of rtrim(myString). That&#8217;s it. (Actually the Ruby and Scala versions both *can* allow you to do different things than that. It&#8217;s just that here and in 90% of the use cases they aren&#8217;t used for anything else. The C# version literally doesn&#8217;t do anything else).</p>
<p>The thing is, while I&#8217;m making fun of this to a certain degree, it&#8217;s actually a perfectly reasonable thing to want to do. Designing things in noun-verb order is a good principle of UI design, and it works for programming as well. Things chain better &#8211; when you want to add new functions to a pipeline you add them at the point your cursor is naturally at and it matches well with thinking of it as a pipeline of &#8220;take this thing, do this to it, do that to it, do this other thing to it, get this value out&#8221;. Also you write far fewer brackets. :-) (compare Haskell&#8217;s foo . bar . baz $ thing idiom for a similar bracket avoidance tool).</p>
<p>Of these, I&#8217;d say that the Ruby solution is the most obvious (it just uses the fact that classes are open to add a new method to String), but it comes with the possibility of amusingly non-obvious runtime errors when someone else defines a conflicting method. The C# solution seems the best to me &#8211; it&#8217;s relatively little overhead over writing the utility method as you would otherwise and comes with the option to invoke it either as myString.rtrim or StringUtils.rtrim(myString), so when namespacing conflicts inevitably occur you have an easy fallback. But of course it uses a language feature specifically added to do this, while the other two are functions of more general language features. The Scala solution is, to my mind, decidedly the worst of the three.It&#8217;s syntactically noisy and comes with a significant additional runtime overhead.</p>
<p>But honestly I&#8217;m not particularly happy with any of these solutions. The Scala and Ruby solutions come with disproportionate costs to the benefit they give and the C# solution requires an additional language feature. Moreoever, each of these solutions requires effort at each definition site in order to make something available that you always want at the use site. Wouldn&#8217;t it be better if for every utility function you automatically had the option to write it on the right?</p>
<p>Let&#8217;s take a digression. What language is the following (rather pointless) code written in?</p>
<pre>[1, 2, 3].sort.length</pre>
<p>Ruby, right?</p>
<p>Actually, no. It&#8217;s Haskell.</p>
<p>Wait, what?</p>
<p>Well, it&#8217;s Haskell if you do something slightly evil and redefine the (.) operator (which normally means composition):</p>
<pre>Prelude Data.List&gt; let (.) x f = f x</pre>
<pre>Prelude Data.List&gt; [1, 2, 3].sort.length</pre>
<pre>3</pre>
<p>I saw this trick a while ago (the author was amusingly apologetic for it). It&#8217;s evil Haskell code because of the way it redefines an operator that normally means something else (this is totally typesafe of course &#8211; existing code will continue to use the old operator definition). But it&#8217;s a perfectly valid operator definition, and a rather nice one.</p>
<p>It works well with additional arguments to functions too:</p>
<p>Prelude Data.List&gt; [1, 2, 3].sortBy(compare).length<br />
3</p>
<p>The reason this works is that sortBy takes the list argument curried as its last argument, so sortBy(compare) gives something of type [Int] -&gt; [Int] which we can then apply as above (Haskell&#8217;s precedence rules make this work).</p>
<p>So this is a nice trick, but how is it useful to you? Well, it&#8217;s probably not. I can&#8217;t think of any low noise way of making it work in any of the other languages mentioned so far (the best I can come up with is an evil evil hack in Ruby that would make god go on a kitten killing spree and a mildly nasty hack with operators and implicit conversions in Scala that&#8217;s much too noisy to really use), and using it in Haskell will make other Haskell programmers very unhappy with you. But it&#8217;s an interesting trick, and I&#8217;ll be sure to bear it in mind if I ever get around to creating DRMacIverLang.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.drmaciver.com/2009/01/writing-things-right/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>QDBM Bindings</title>
		<link>http://www.drmaciver.com/2008/04/qdbm-bindings/</link>
		<comments>http://www.drmaciver.com/2008/04/qdbm-bindings/#comments</comments>
		<pubDate>Sun, 27 Apr 2008 14:46:29 +0000</pubDate>
		<dc:creator>david</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://www.drmaciver.com/?p=114</guid>
		<description><![CDATA[&#8220;So&#8221;, I thought to myself, &#8220;I feel like learning how to use the Haskell Foreign Function Interface. I think I&#8217;ll write a binding to a C library&#8221; As one does. Seeing as both my Haskell and my C are less than stellar this proved to be an interesting challenge, but I rose to it and [...]]]></description>
			<content:encoded><![CDATA[<p>&#8220;So&#8221;, I thought to myself, &#8220;I feel like learning how to use the Haskell Foreign Function Interface. I think I&#8217;ll write a binding to a C library&#8221;</p>
<p>As one does.</p>
<p>Seeing as both my Haskell and my C are less than stellar this proved to be an interesting challenge, but I rose to it and put together a basic set of bindings for <a href="http://qdbm.sourceforge.net/">QDBM</a>&#8216;s Depot library. It&#8217;s only lightly tested and very incomplete, but seems to work and if you want something along these lines it will probably do the job. You can get it from <a href="http://freehg.org/u/DRMacIver/misc/">my misc HG repository</a>. The resulting code is extremely imperative to use, but otherwise not too bad.</p>
<p>This post is a literate Haskell file with a demo of how to use it.</p>
<p>We&#8217;re going to write a bulk file importer. It will get its data from stdin and will read a bunch of records formated as &#8220;key = value&#8221;, ignoring blank lines and lines starting with #. It will import them into a qdbm Depot database file, printing out a message for every value it overwrites.</p>
<pre><font color=Cyan>&gt;</font> <font color=Green><u>module</u></font> Main <font color=Green><u>where</u></font>
<font color=Cyan>&gt;</font> <font color=Green><u>import</u></font> <font color=Green><u>qualified</u></font> Data<font color=Cyan>.</font>ByteString <font color=Green><u>as</u></font> ByteString
<font color=Cyan>&gt;</font> <font color=Green><u>import</u></font> Data<font color=Cyan>.</font>ByteString <font color=Cyan>(</font>ByteString<font color=Cyan>)</font>
</pre>
<p>The library is based around strict ByteStrings, both because of the way it interoperates with C and for performance reasons.</p>
<pre><font color=Cyan>&gt;</font> <font color=Green><u>import</u></font> <font color=Green><u>qualified</u></font> Data<font color=Cyan>.</font>ByteString<font color=Cyan>.</font>Char8 <font color=Green><u>as</u></font> Char8
<font color=Cyan>&gt;</font> <font color=Green><u>import</u></font> Data<font color=Cyan>.</font>ByteString<font color=Cyan>.</font>Char8 <font color=Cyan>(</font>pack<font color=Cyan>,</font> unpack<font color=Cyan>)</font>
</pre>
<p>In order to convert between ByteStrings and normal Haskell Strings</p>
<pre><font color=Cyan>&gt;</font> <font color=Green><u>import</u></font> System<font color=Cyan>.</font>Environment
<font color=Cyan>&gt;</font> <font color=Green><u>import</u></font> System<font color=Cyan>.</font>IO
<font color=Cyan>&gt;</font> <font color=Green><u>import</u></font> Text<font color=Cyan>.</font>Printf
</pre>
<p>Just some random useful imports</p>
<pre><font color=Cyan>&gt;</font> <font color=Green><u>import</u></font> QDBM<font color=Cyan>.</font>Depot
</pre>
<p>And of course we need to import the QDBM module itself.</p>
<pre><font color=Cyan>&gt;</font> main <font color=Red>=</font> <font color=Green><u>do</u></font> args <font color=Red>&lt;-</font> getArgs
<font color=Cyan>&gt;</font>           <font color=Green><u>case</u></font> args <font color=Green><u>of</u></font>
<font color=Cyan>&gt;</font>             <font color=Red>[</font>dbname<font color=Cyan>,</font> importfile<font color=Red>]</font> <font color=Red>-&gt;</font> importInto <font color=Cyan>(</font>pack dbname<font color=Cyan>)</font> importfile
<font color=Cyan>&gt;</font>             x <font color=Red>-&gt;</font> putStrLn <font color=Magenta>"Expected usage: bulkimport dbname importfile"</font>
</pre>
<p>Boring, and woefully inadequate, argument processing.</p>
<pre><font color=Cyan>&gt;</font>   <font color=Green><u>where</u></font> importInto dbname importfile <font color=Red>=</font>
<font color=Cyan>&gt;</font>           <font color=Green><u>do</u></font> db <font color=Red>&lt;-</font> openDepot dbname Write
</pre>
<p>Open a handle on the database in write mode.</p>
<pre><font color=Cyan>&gt;</font>              eachLine importfile <font color=Cyan>$</font> processLine db
</pre>
<p>I&#8217;m pretty sure the Haskell Cabal will want my blood for writing a foreach in Haskell. But anyway, this should be fairly self explanatory.</p>
<pre><font color=Cyan>&gt;</font>              closeDepot db
</pre>
<p>Finally, close the database file</p>
<pre><font color=Cyan>&gt;</font>         parseRecord line <font color=Red>=</font> <font color=Green><u>let</u></font> <font color=Cyan>(</font>start<font color=Cyan>,</font> end<font color=Cyan>)</font> <font color=Red>=</font> Char8<font color=Cyan>.</font>break <font color=Cyan>(</font><font color=Cyan>==</font><font color=Magenta>'='</font><font color=Cyan>)</font> line <font color=Green><u>in</u></font> <font color=Cyan>(</font>start<font color=Cyan>,</font> ByteString<font color=Cyan>.</font>drop <font color=Magenta>1</font> end<font color=Cyan>)</font>
</pre>
<p>Split the line around the first = in order to get the key and value. We should probably do better error handling here. Oh well. </p>
<pre><font color=Cyan>&gt;</font>         processLine db line <font color=Red>=</font> <font color=Green><u>if</u></font> <font color=Cyan>(</font>not <font color=Cyan>(</font>ByteString<font color=Cyan>.</font>null line<font color=Cyan>)</font> <font color=Cyan>&amp;&amp;</font> Char8<font color=Cyan>.</font>head line <font color=Cyan>/=</font> <font color=Magenta>'#'</font><font color=Cyan>)</font>
<font color=Cyan>&gt;</font>                                <font color=Green><u>then</u></font> <font color=Green><u>do</u></font> currentValue <font color=Red>&lt;-</font> get db key
<font color=Cyan>&gt;</font>                                        <font color=Green><u>case</u></font> currentValue <font color=Green><u>of</u></font>
<font color=Cyan>&gt;</font>                                           Nothing <font color=Red>-&gt;</font> put db key value
<font color=Cyan>&gt;</font>                                           Just currentValue <font color=Red>|</font> currentValue <font color=Cyan>==</font> value <font color=Red>-&gt;</font> return ()
<font color=Cyan>&gt;</font>                                           Just currentValue <font color=Red>-&gt;</font> printf <font color=Magenta>"Replacing value for key %s. Value %s -&gt; %s\n"</font> <font color=Cyan>(</font>show key<font color=Cyan>)</font> <font color=Cyan>(</font>show currentValue<font color=Cyan>)</font> <font color=Cyan>(</font>show value<font color=Cyan>)</font>
<font color=Cyan>&gt;</font>                                <font color=Green><u>else</u></font> return ()
<font color=Cyan>&gt;</font>           <font color=Green><u>where</u></font> <font color=Cyan>(</font>key<font color=Cyan>,</font> value<font color=Cyan>)</font> <font color=Red>=</font> parseRecord line
</pre>
<p>For each line, we first check if it&#8217;s empty or starts with #. If it is, we ignore it. Else we look up the relevant key in the database. If it&#8217;s there already and with a different value with print a warning message. Else we put the new value into the database.</p>
<pre><font color=Cyan>&gt;</font> eachLine <font color=Red>::</font> FilePath <font color=Red>-&gt;</font> <font color=Cyan>(</font>ByteString <font color=Red>-&gt;</font> IO ()<font color=Cyan>)</font> <font color=Red>-&gt;</font> IO ()
<font color=Cyan>&gt;</font> eachLine file f <font color=Red>=</font> <font color=Green><u>do</u></font> handle <font color=Red>&lt;-</font> openFile file ReadMode
<font color=Cyan>&gt;</font>                      catch <font color=Cyan>(</font>eachLineInHandle handle<font color=Cyan>)</font> <font color=Cyan>(</font>const <font color=Cyan>$</font> hClose handle<font color=Cyan>)</font>
<font color=Cyan>&gt;</font>   <font color=Green><u>where</u></font> eachLineInHandle handle <font color=Red>=</font> ByteString<font color=Cyan>.</font>hGetLine handle <font color=Cyan>&gt;&gt;=</font> f <font color=Cyan>&gt;&gt;</font> eachLineInHandle handle
<font color=Cyan>&gt;</font>
</pre>
<p>Simple utility function for operating over the lines of a file.</p>
<p>And that&#8217;s about it. It&#8217;s fairly grotty code, but hopefully conveys the idea of how to use the basics (not that that would really have been hard to figure out). There are a few other functions in the module, but they should be fairly self explanatory.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.drmaciver.com/2008/04/qdbm-bindings/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Monadic card shuffling</title>
		<link>http://www.drmaciver.com/2008/04/monadic-card-shuffling/</link>
		<comments>http://www.drmaciver.com/2008/04/monadic-card-shuffling/#comments</comments>
		<pubDate>Wed, 16 Apr 2008 22:22:50 +0000</pubDate>
		<dc:creator>david</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://www.drmaciver.com/?p=105</guid>
		<description><![CDATA[Because it&#8217;s what all the cool kids do, this is a post in literate Haskell. Assuming wordpress doesn&#8217;t screw things up too horribly, you should just be able to cut and paste it into your text editor and compile it. How do you shuffle a pack of cards? Easy. Throw it up in the air [...]]]></description>
			<content:encoded><![CDATA[<p>Because it&#8217;s what all the cool kids do, this is a post in literate Haskell. Assuming wordpress doesn&#8217;t screw things up too horribly, you should just be able to cut and paste it into your text editor and compile it.</p>
<p>
How do you shuffle a pack of cards?</p>
<p>
Easy. Throw it up in the air and then pick them up again. Done.</p>
<p>
Ok, you don&#8217;t do that in practice, because it makes a mess. But in principle it would give you a fair shuffling of the cards. Conceptually it&#8217;s equivalent to doing &#8220;pick a card, any card&#8221; until you run out of cards, and using the resulting order you picked them in. But while tidy, that&#8217;s far too boring.</p>
<p>
Nevertheless, it&#8217;s a pretty good way of shuffling. It&#8217;s more or less equivalent to one of the standard ways of shuffling a list/array/favourite sequential data structure, the <a href="http://en.wikipedia.org/wiki/Fisher-Yates_shuffle">Fisher-Yates shuffle</a>. This has a very easy to follow imperative implementation, but the purely functional ones&#8230; not so much. Oleg <a href="http://okmij.org/ftp/Haskell/perfect-shuffle.txt">has an implementation</a>, although he doesn&#8217;t call it by this name. However, I found this implementation a little scary and (more importantly) not that easy to use.</p>
<p>
Here&#8217;s one which is structured according to a custom monad (sorry) which emulates the &#8220;pick a card, any card&#8221; structure of shuffling the list. It seems likely that the monad has other uses, but I can&#8217;t think of any at the moment. Mostly I&#8217;m just posting this as a cute way to solve the problem.</p>
<pre><font color=Cyan>&gt;</font><font color=Blue>{-# LANGUAGE GeneralizedNewtypeDeriving#-}</font>
</pre>
<p>We&#8217;ll need this to derive the monad instance for our sample.</p>
<pre><font color=Cyan>&gt;</font> <font color=Green><u>module</u></font> Sample <font color=Cyan>(</font>
<font color=Cyan>&gt;</font>   Sample<font color=Cyan>,</font>
</pre>
<p>
We&#8217;ll define a type Sample a b. This should be interpreted as an action which can add items to and random draw items from a bag of elements of type a and results in a b. </p>
<pre><font color=Cyan>&gt;</font>   takeSample<font color=Cyan>,</font>
</pre>
<p>
Given a Sample we run it by providing it with a source of randomness.</p>
<p>
We define a sample with the following primitives:</p>
<pre><font color=Cyan>&gt;</font>   draw<font color=Cyan>,</font>
</pre>
<p>
We can draw an item from it at random. This returns Nothing if the bag is empty, else Just someItem</p>
<pre><font color=Cyan>&gt;</font>   place<font color=Cyan>,</font>
</pre>
<p>
We can put an item into the bag.</p>
<pre><font color=Cyan>&gt;</font>   placeAll<font color=Cyan>,</font>
<font color=Cyan>&gt;</font>   drawAll<font color=Cyan>,</font>
</pre>
<p>
And we provide some useful functions for bulk add and remove. placeAll puts a list of items into the bag. drawAll draws all the remaining items from the bag in a random order.</p>
<pre><font color=Cyan>&gt;</font> shuffle
</pre>
<p>
And using the combination of placeAll and drawAll we&#8217;ll define a shuffle function.</p>
<pre><font color=Cyan>&gt;</font> <font color=Cyan>)</font> <font color=Green><u>where</u></font>
<font color=Cyan>&gt;</font>
<font color=Cyan>&gt;</font> <font color=Green><u>import</u></font> Control<font color=Cyan>.</font>Monad<font color=Cyan>.</font>State
<font color=Cyan>&gt;</font> <font color=Green><u>import</u></font> System<font color=Cyan>.</font>Random
<font color=Cyan>&gt;</font> <font color=Green><u>import</u></font> <font color=Green><u>qualified</u></font> Data<font color=Cyan>.</font>Sequence <font color=Green><u>as</u></font> Seq
<font color=Cyan>&gt;</font> <font color=Green><u>import</u></font> Data<font color=Cyan>.</font>Sequence <font color=Cyan>(</font>Seq<font color=Cyan>,</font> <font color=Cyan>(</font><font color=Cyan>&lt;|</font><font color=Cyan>)</font><font color=Cyan>,</font> <font color=Cyan>(</font><font color=Cyan>|&gt;</font><font color=Cyan>)</font><font color=Cyan>,</font> <font color=Cyan>(</font><font color=Cyan>&gt;&lt;</font><font color=Cyan>)</font><font color=Cyan>)</font>
<font color=Cyan>&gt;</font> <font color=Green><u>newtype</u></font> Sample a b <font color=Red>=</font> Sample <font color=Cyan>(</font>State <font color=Cyan>(</font>StdGen<font color=Cyan>,</font> Seq a<font color=Cyan>)</font> b<font color=Cyan>)</font> <font color=Green><u>deriving</u></font> Monad
</pre>
<p>
A Sample consists of two things. A random generator with which to make choices and a collection of elements (we assume it&#8217;s a StdGen rather than an arbitrary generator, mainly because I&#8217;m being lazy) and a bag of elements to draw from. We allow repetitions, and in order to allow us to draw from any point we model it as a Data.Sequence rather than a list (which has O(log(k)) indexing).  </p>
<p>
We want to chain actions with respect to this sampling together, so we model it as a state monad.</p>
<pre><font color=Cyan>&gt;</font> takeSample <font color=Red>::</font> StdGen <font color=Red>-&gt;</font> Sample a b <font color=Red>-&gt;</font> b
<font color=Cyan>&gt;</font> takeSample g <font color=Cyan>(</font>Sample st<font color=Cyan>)</font> <font color=Red>=</font> evalState st <font color=Cyan>(</font>g<font color=Cyan>,</font> Seq<font color=Cyan>.</font>empty<font color=Cyan>)</font>
</pre>
<p>
Given a Sample, we set it running with a source of randomness and an empty bag.</p>
<pre><font color=Cyan>&gt;</font> draw <font color=Red>::</font> Sample a <font color=Cyan>(</font>Maybe a<font color=Cyan>)</font>
<font color=Cyan>&gt;</font> draw <font color=Red>=</font> Sample <font color=Cyan>$</font> <font color=Green><u>do</u></font> <font color=Cyan>(</font>gen<font color=Cyan>,</font> sample<font color=Cyan>)</font> <font color=Red>&lt;-</font> get
<font color=Cyan>&gt;</font>                    <font color=Green><u>if</u></font> <font color=Cyan>(</font>Seq<font color=Cyan>.</font>null sample<font color=Cyan>)</font>
<font color=Cyan>&gt;</font>                      <font color=Green><u>then</u></font> return Nothing
<font color=Cyan>&gt;</font>                      <font color=Green><u>else</u></font> <font color=Green><u>do</u></font> <font color=Green><u>let</u></font> <font color=Cyan>(</font>i<font color=Cyan>,</font> gen'<font color=Cyan>)</font> <font color=Red>=</font> randomR <font color=Cyan>(</font><font color=Magenta>0</font><font color=Cyan>,</font> Seq<font color=Cyan>.</font>length sample <font color=Blue>-</font> <font color=Magenta>1</font><font color=Cyan>)</font> gen
<font color=Cyan>&gt;</font>                              <font color=Green><u>let</u></font> <font color=Cyan>(</font>x<font color=Cyan>,</font> sample'<font color=Cyan>)</font> <font color=Red>=</font> remove i sample
<font color=Cyan>&gt;</font>                              put <font color=Cyan>(</font>gen'<font color=Cyan>,</font> sample'<font color=Cyan>)</font>
<font color=Cyan>&gt;</font>                              return <font color=Cyan>$</font> Just x
</pre>
<p>
Draw takes an element from the sequence, returns the result of that and chains through the new generator and the remaining elements.</p>
<pre><font color=Cyan>&gt;</font>  <font color=Green><u>where</u></font>
<font color=Cyan>&gt;</font>    remove <font color=Red>::</font> Int <font color=Red>-&gt;</font> Seq a <font color=Red>-&gt;</font> <font color=Cyan>(</font>a<font color=Cyan>,</font> Seq a<font color=Cyan>)</font>
<font color=Cyan>&gt;</font>    remove <font color=Magenta>0</font> xs <font color=Red>=</font> <font color=Cyan>(</font>x<font color=Cyan>,</font> u<font color=Cyan>)</font> <font color=Green><u>where</u></font> <font color=Cyan>(</font>x Seq<font color=Cyan>.:&lt;</font> u<font color=Cyan>)</font> <font color=Red>=</font> Seq<font color=Cyan>.</font>viewl xs
<font color=Cyan>&gt;</font>    remove i xs <font color=Red>|</font> i <font color=Cyan>==</font> Seq<font color=Cyan>.</font>length xs <font color=Red>=</font> <font color=Cyan>(</font>x<font color=Cyan>,</font> u<font color=Cyan>)</font> <font color=Green><u>where</u></font> <font color=Cyan>(</font>u Seq<font color=Cyan>.:&gt;</font> x<font color=Cyan>)</font> <font color=Red>=</font> Seq<font color=Cyan>.</font>viewr xs
<font color=Cyan>&gt;</font>    remove i xs <font color=Red>=</font> <font color=Cyan>(</font>x<font color=Cyan>,</font> u <font color=Cyan>&gt;&lt;</font> v<font color=Cyan>)</font>
<font color=Cyan>&gt;</font>      <font color=Green><u>where</u></font> <font color=Cyan>(</font>u'<font color=Cyan>,</font> v<font color=Cyan>)</font> <font color=Red>=</font> Seq<font color=Cyan>.</font>splitAt i xs
<font color=Cyan>&gt;</font>            <font color=Cyan>(</font>u Seq<font color=Cyan>.:&gt;</font> x<font color=Cyan>)</font>  <font color=Red>=</font> Seq<font color=Cyan>.</font>viewr u'
</pre>
<p>
This is just a helpful method for removing an element from inside a sequence.</p>
<pre><font color=Cyan>&gt;</font> place <font color=Red>::</font> a <font color=Red>-&gt;</font> Sample a ()
<font color=Cyan>&gt;</font> place x <font color=Red>=</font> Sample <font color=Cyan>$</font> <font color=Green><u>do</u></font> <font color=Cyan>(</font>gen<font color=Cyan>,</font> sample<font color=Cyan>)</font> <font color=Red>&lt;-</font> get
<font color=Cyan>&gt;</font>                       put <font color=Cyan>(</font>gen<font color=Cyan>,</font> x <font color=Cyan>&lt;|</font> sample<font color=Cyan>)</font>
</pre>
<p>
To place an element we just append it to the beginning of the sequence.</p>
<pre><font color=Cyan>&gt;</font> placeAll <font color=Red>::</font> <font color=Red>[</font>a<font color=Red>]</font> <font color=Red>-&gt;</font> Sample a ()
<font color=Cyan>&gt;</font> placeAll xs <font color=Red>=</font> Sample <font color=Cyan>$</font> <font color=Green><u>do</u></font> <font color=Cyan>(</font>gen<font color=Cyan>,</font> sample<font color=Cyan>)</font> <font color=Red>&lt;-</font> get
<font color=Cyan>&gt;</font>                           put <font color=Cyan>(</font>gen<font color=Cyan>,</font> Seq<font color=Cyan>.</font>fromList xs <font color=Cyan>&gt;&lt;</font> sample<font color=Cyan>)</font>
</pre>
<p>
Similarly for placing multiple elements, although we use sequence concatenation rather than appending them one by one.</p>
<pre><font color=Cyan>&gt;</font> drawAll <font color=Red>::</font> Sample a <font color=Red>[</font>a<font color=Red>]</font>
<font color=Cyan>&gt;</font> drawAll <font color=Red>=</font> <font color=Green><u>do</u></font> el <font color=Red>&lt;-</font> draw
<font color=Cyan>&gt;</font>              <font color=Green><u>case</u></font> el <font color=Green><u>of</u></font>
<font color=Cyan>&gt;</font>                   Nothing <font color=Red>-&gt;</font> return []
<font color=Cyan>&gt;</font>                   Just<font color=Cyan>(</font>x<font color=Cyan>)</font> <font color=Red>-&gt;</font> <font color=Green><u>do</u></font> xs <font color=Red>&lt;-</font> drawAll
<font color=Cyan>&gt;</font>                                 return <font color=Cyan>$</font> x <font color=Red><b>:</b></font> xs
</pre>
<p>drawAll simply draws from the bag until it finds nothing left. Pretty self explanatory.</p>
<pre><font color=Cyan>&gt;</font> shuffle <font color=Red>::</font> StdGen <font color=Red>-&gt;</font> <font color=Red>[</font>a<font color=Red>]</font> <font color=Red>-&gt;</font> <font color=Red>[</font>a<font color=Red>]</font>
<font color=Cyan>&gt;</font> shuffle gen xs <font color=Red>=</font> takeSample gen <font color=Cyan>$</font> placeAll xs <font color=Cyan>&gt;&gt;</font> drawAll
</pre>
<p>
And finally, we can implement shuffle. And it&#8217;s a one liner. In order to shuffle a bunch of elements we simply put them all in the bag, then take them all out again in a random order. Ta da!</p>
<p>
This wasn&#8217;t really very hard to do directly, but I found that creating the right abstraction to build it out of helped clarify the logic a lot. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.drmaciver.com/2008/04/monadic-card-shuffling/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

