<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>Zenzike's Blog</title>
        <link>http://zenzike.com</link>
        <description><![CDATA[A Haskell enthusiast's webpage]]></description>
        <atom:link href="http://zenzike.com/rss.xml" rel="self"
                   type="application/rss+xml" />
        <lastBuildDate>Mon, 01 Aug 2011 00:00:00 UT</lastBuildDate>
        <item>
    <title>The Conditional Choice Operator</title>
    <link>http://zenzike.com/posts/2011-08-01-the-conditional-choice-operator.html</link>
    <description><![CDATA[<p>A recent <a href="http://www.reddit.com/r/haskell/comments/j51yw/library_of_conditional_oneliners_and_combinators/">reddit post</a> asking for a library of conditional one-liners and combinators reminded me of one of my favourite operators: the conditional choice. Most programmers are used to the so-called <a href="http://en.wikipedia.org/wiki/McCarthy_Formalism">McCarthy conditional</a>:</p>
<pre class="sourceCode haskell"><code>if p then x else y
</code></pre>
<p>An alternative way of viewing this is as a ternary operator:</p>
<pre class="sourceCode haskell"><code>x &lt;| p |&gt; y
</code></pre>
<p>This operator is known as the <em>conditional choice</em>, but I’m told that it was introduced by Tony Hoare, so maybe naming it the Hoare conditional would make more sense (it makes an appearance in Hoare’s work on <a href="http://en.wikipedia.org/wiki/Communicating_sequential_processes">Communicating Sequential Processes</a> and <a href="http://en.wikipedia.org/wiki/Unifying_Theories_of_Programming">Unifying Theories of Programming</a>, but I haven’t found any references to its original introduction).</p>
<h2 id="laws">Laws</h2>
<p>Rendering conditonals as ternary operators makes it clear that there are a number of nice properties that hold true:</p>
<ul>
<li><p>Idempotency</p>
<pre class="sourceCode haskell"><code>x &lt;| p |&gt; x == x
</code></pre></li>
<li><p>Left-Identity</p>
<pre class="sourceCode haskell"><code>x &lt;| True |&gt; y == x
</code></pre></li>
<li><p>Right-Identity</p>
<pre class="sourceCode haskell"><code>x &lt;| False |&gt; y == y
</code></pre></li>
<li><p>Left-Distributivity</p>
<pre class="sourceCode haskell"><code>x &lt;| p |&gt; (y &lt;| q |&gt; z) == (x &lt;| p |&gt; y) &lt;| q |&gt; (x &lt;| p |&gt; z)
</code></pre></li>
<li><p>Right-Distributivity</p>
<pre class="sourceCode haskell"><code>(x &lt;| p |&gt; y) &lt;| q |&gt; z == (x &lt;| q |&gt; z) &lt;| p |&gt; (y &lt;| q |&gt; z)
</code></pre></li>
<li><p>Symmetry</p>
<pre class="sourceCode haskell"><code>x &lt;| p |&gt; y == y &lt;| not p |&gt; x
</code></pre></li>
<li><p>Conjunction-Associativity</p>
<pre class="sourceCode haskell"><code>(x &lt;| p |&gt; y) &lt;| q |&gt; z == x &lt;| p &amp;&amp; q |&gt; (y &lt;| q |&gt; z)
</code></pre></li>
<li><p>Disjunction-Associativity</p>
<pre class="sourceCode haskell"><code>x &lt;| p |&gt; (y &lt;| q |&gt; z) == (x &lt;| p |&gt; y) &lt;| p || q |&gt; z
</code></pre></li>
<li><p>Conjunction-Collapse</p>
<pre class="sourceCode haskell"><code>x &lt;| p |&gt; (y &lt;| p &amp;&amp; q |&gt; z) == x &lt;| p |&gt; z
</code></pre></li>
<li><p>Disjunction-Collapse</p>
<pre class="sourceCode haskell"><code>(x &lt;| p || q |&gt; y) &lt;| q |&gt; z == x &lt;| q |&gt; z
</code></pre></li>
<li><p>Abiding (Interchange)</p>
<pre class="sourceCode haskell"><code>x # y &lt;| p |&gt; v # w == (x &lt;| p |&gt; v) # (y &lt;| p |&gt; w)
</code></pre></li>
</ul>
<p>These laws are easily proved by considering the cases where <code>p</code> and <code>q</code> are <code>True</code> and <code>False</code>.</p>
<h2 id="implementation">Implementation</h2>
<p>In Haskell, implementing this operator is quite simple. First we’ll define the right bracket, which takes a predicate and a value <code>x</code>, and returns <code>Nothing</code> if the predicate is <code>True</code>, and returns <code>Just x</code> when it is <code>False</code>:</p>
<pre class="sourceCode literate haskell"><code>&gt; (|&gt;) :: Bool -&gt; a -&gt; Maybe a
&gt; True  |&gt; _ = Nothing
&gt; False |&gt; y = Just y
</code></pre>
<p>The left bracket is equivalent to <code>fromMaybe</code>, where the resulting value from the application of the right bracket (which evaluates the predicate) is consumed. If the result was <code>Nothing</code>, then we use the value <code>x</code>, otherwise we have <code>Just y</code>, and return <code>y</code> as the result.</p>
<pre class="sourceCode literate haskell"><code>&gt; (&lt;|) :: a -&gt; Maybe a -&gt; a
&gt; x &lt;| Nothing = x
&gt; _ &lt;| Just y  = y
</code></pre>
<p>Finally we give the operators low infixity precedence, and make them right associative:</p>
<pre class="sourceCode literate haskell"><code>&gt; infixr 0 &lt;|
&gt; infixr 0 |&gt;
</code></pre>
<p>Defining the operator this way makes the ternary operator right associative, so that:</p>
<pre class="sourceCode haskell"><code>x &lt;| p |&gt; y &lt;| q |&gt; z == x &lt;| p |&gt; (y &lt;| q |&gt; z)
</code></pre>
<p>Right associativity here is useful so that reading from left to right, the result is the expression to the left of the first predicate that is true.</p>]]></description>
    <pubDate>Mon, 01 Aug 2011 00:00:00 UT</pubDate>
    <guid>http://zenzike.com/posts/2011-08-01-the-conditional-choice-operator.html</guid>
</item>
<item>
    <title>Do The Hokey Cokey</title>
    <link>http://zenzike.com/posts/2011-04-18-do-the-hokey-cokey.html</link>
    <description><![CDATA[<p>   </p>
<p>A recent blog post by Jeremy Gibbons, <a href="http://patternsinfp.wordpress.com/2011/04/11/morality-and-temptation/">Morality and Temptation</a>, left the exercise of finding two definitions of the arrow with the signature \(μF → νF\), and showing that they are equivalent. This post shows my solution to this problem, and while I’m here, I too have a confession to make: when dealing with the ins and outs of initial algebras and final coalgebras I sometimes get the <a href="http://en.wikipedia.org/wiki/Hokey_Cokey">Hokey Cokey</a> playing in my mind. For those of you who don’t know this children’s song, it goes something like this:</p>
<blockquote>
<p>You put your left foot in,<br/> Your left foot out,<br/> In, out, in, out,<br/> You shake it all about.<br/> You do the Hokey Cokey,<br/> And you turn around,<br/> That’s what it’s all about!</p>
</blockquote>
<p>Now that’s out of the way, let’s focus on the problem at hand. I’ll start by summarising some of the basics of what we’re tackling.</p>
<h2 id="your-f-algebra-in">Your F-Algebra In</h2>
<p>Given a functor \(F : \C → \C\), an F-Algebra is a pair \((X, f)\), where \(X ∈ \C\), and \(f ∈ \C(F X, X)\). F-Algebras are objects in the category written \(Alg_F\), where an arrow in this category is given by an \(h ∈ \C\) such that the following property holds between two objects \((X, f)\), and \((Y, g)\): \[
h . f = g . F h
\] The construction of a \(fold\) is given by looking at the initial object in this category, written as \((μF, in)\). Initial objects have a unique arrow to every object in the category; in this category the unique arrow to an object \((Y, g)\) is given by \(\fold{g}\), and it makes the following commute (you’ll have to excuse the ASCII diagrams, I have yet to find a good way of rendering commutative diagrams for the web):</p>
<pre><code>        F(|g|)
   F μF ─——————&gt; F Y
    │             │
 in │             │ g
    │             │
    V             V
    μF ---------&gt; Y
         (|g|)
</code></pre>
<p>Following the arrows of this diagram gives us most of the ingredients needed to state the Universal Property of a \(fold\), which is as follows: \[
h . in = g . F h ⇔ \fold{g} = h
\] In other words, \(\fold{g}\) is the unique solution that satisfies this commuting diagram.</p>
<h2 id="your-f-coalgebra-out">Your F-Coalgebra Out</h2>
<p>Given a functor \(F : \C → \C\), an F-coalgebra is the categorical dual of an F-algebra and inhabits the \(Coalg_F\) category. Here, objects are pairs \((X, f)\), where \(X ∈ \C\), and \(f ∈ \C(X, F X)\).</p>
<p>Unsurprisingly, we are interested in the final object, written \((νF, out)\), of this category, where the unique arrow from every object \((X, f)\) to the final object is written \(\unfold{f}\), and the following commutes:</p>
<pre><code>       F[(f)]
  F X ────────&gt; F νF
   ^             ^
   │             │
 f │             │ out
   │             │
   │             │
   X ----------&gt; νF
        [(f)]
</code></pre>
<p>The universal property also dualises, and in this case we have: \[
h = \unfold{f} ⇔ F h . f = out . h
\] This property simply states that \(\unfold{f}\) is the unique equation satisfying the commuting diagram.</p>
<h2 id="in-out-in-out">In, Out, In, Out</h2>
<p>Our goal is to find two definitions of an arrow of type \(μF → νF\), and to show that these definitions are equivalent. Looking at the definition of an initial F-algebra, it’s pretty obvious that we can produce such an arrow by taking the fold of an arrow with type \(F(νF) → νF\). Using the inverse of \(out\), which we’ll write as \(out°\), is a fairly obvious choice and produces the following diagram:</p>
<pre><code>         F(|out°|)
    F μF ─———————&gt; F νF
     │              │
     │              │
  in │              │ out°
     │              │
     V              V
     μF ----------&gt; νF
         (|out°|)
</code></pre>
<p>By dualizing, the alternative definition of this arrow becomes quite apparent, where the unfold of \(in°\) is used instead:</p>
<pre><code>         F[(in°)]
    F μF ─———————&gt; F νF
     ^              ^
     │              │
 in° │              │ out
     │              │
     │              │
     μF ----------&gt; νF
         [(in°)]
</code></pre>
<p>So, we now have two definitions for the arrow in question, \(\fold{out°}\), and \(\unfold{in°}\). All that is left is to show that these two definitions are equivalent.</p>
<h2 id="shake-it-all-about">Shake It All About</h2>
<p>The universal properties of folds and unfolds are a useful way of encoding lots of information about their structure in one place. Consequently, these properties are very useful tools for proving properties of folds and unfolds.</p>
<p>By plugging our two arrows into the equations that describe the universal properties of folds and unfolds, we get the following: \[
\unfold{in°} . in = out° . F \unfold{in°}
⇔
\fold{out°} = \unfold{in°}
⇔
F \fold{out°} . in° = out . \fold{out°}
\] I think this equation is marvellous, I don’t know if it has a name, but for the purpose of this post I’ll call it the <em>Hokey Cokey Law</em>. The left hand side comes from instantiating the universal property for folds with an unfold, and the right hand side comes from instantiating the universal property for unfolds with a fold.</p>
<h2 id="do-the-hokey-cokey">Do the Hokey Cokey</h2>
<p>We still haven’t proved that \(\fold{out°} = \unfold{in°}\), but proving either the left hand side or the right hand side of the equation is all that is required. Let’s start with what is known: the universal property of \(fold\) applied to \(\fold{out°}\):</p>
<p>\(\fold{out°} . in = out° . F \fold{out°}\)</p>
<p>\(\hint{⇒}{Leibniz, twice}\)</p>
<p>\(out . \fold{out°} . in . in° = out . out° . F \fold{out°} . in°\)</p>
<p>\(\hint{⇒}{Identity, twice}\)</p>
<p>\(out . \fold{out°} = F \fold{out°} . in°\)</p>
<p>\(\hint{⇔}{Hokey Cokey}\)</p>
<p>\(\fold{out°} = \unfold{in°}\)</p>
<p>So there you have it, the Hokey Cokey in all its glory. Of course, we could take this proof <em>and turn around</em>, since everything dualises: we could have equally picked the universal of \(unfold\) applied to \(\unfold{in°}\), and would have arrived at the left hand side of our equivalence. That’s what it’s all about!</p>
<blockquote>
<p>Woah! The Hokey Cokey!<br/> Woah! The Hokey Cokey!<br/> Woah! The Hokey Cokey!<br/> Knees bent, arms stretched, ra ra ra!</p>
</blockquote>]]></description>
    <pubDate>Mon, 18 Apr 2011 00:00:00 UT</pubDate>
    <guid>http://zenzike.com/posts/2011-04-18-do-the-hokey-cokey.html</guid>
</item>
<item>
    <title>Injective Representables</title>
    <link>http://zenzike.com/posts/2011-04-07-injective-representables.html</link>
    <description><![CDATA[<p>In this article I’ll show how the injective and surjective properties of a function have a nice relationship with the injectivity of the corresponding representable functors, and how the right cancellative definition of surjection can be derived from the standard one. This is a fairly trivial discussion about a simple observation, so don’t expect anything spectacular.</p>
<p>The definition of injectivity is usually given in the following terms, where a function is injective when it is <em>left cancellative</em>:</p>
<blockquote>
<p>\(h\) is injective iff \(\forall f, g \cdot h . f = h . g \Rightarrow f = g\)</p>
</blockquote>
<p>Surjectivity can be described in similar terms, where a function is surjective when it is <em>right cancellative</em>:</p>
<blockquote>
<p>\(h\) is surjective iff \(\forall f, g \cdot f . h = g . h \Rightarrow f = g\)</p>
</blockquote>
<p>While these two definitions show the similarity between the injective and surjective properties, this definition of surjectivity isn’t the standard one. The standard definition goes as follows:</p>
<blockquote>
<p>\(h\) is surjective iff \(\forall y \cdot \exists x \cdot h~ x = y\)</p>
</blockquote>
<p>I don’t like this definition, since I don’t find it easy to work with in proofs, and it doesn’t show the relationship between surjections and injections well.</p>
<h2 id="representables">Representables</h2>
<p>The representables, or Hom-functors, are functions from arrows to arrows in a category. These functions come in two flavours, the covariant representable, and the contravariant representable. Given objects \(S\) and \(T\) in a category \(ℂ\), we write \(ℂ(S, T)\) denote the set of all arrows from \(S\) to \(T\).</p>

<h3>
Covariant Representable
</h3>

<p>Given a function \(h : X \rightarrow Y\), the covariant representable, \(ℂ(S,-)\) is defined as:</p>
<pre class="sourceCode haskell"><code>ℂ(S,—) :: (X -&gt; Y) -&gt; ℂ(S, X) -&gt; ℂ(S, Y)
ℂ(S,—) h f = h . f
</code></pre>
<p>As shorthand for the above, we usually slot the argument \(h\) into the dash:</p>
<pre class="sourceCode haskell"><code>ℂ(S, h) = ℂ(S,—) h
</code></pre>

<h3>
Contravariant Representable
</h3>

<p>Given a function \(h : X \rightarrow Y\), the contravariant representable, \(ℂ(-,T)\) is defined as:</p>
<pre class="sourceCode haskell"><code>ℂ(—,T) :: (X -&gt; Y) -&gt; ℂ(X, T) -&gt; ℂ(Y, T)
ℂ(—,T) h f = f . h
</code></pre>
<p>Again, we use the following shorthand, where we slot \(h\) into the dash:</p>
<pre class="sourceCode haskell"><code>ℂ(h, T) = ℂ(—,T) h
</code></pre>
<p>One feature of these representables that I like particularly is that they give rise to a clean correspondence between injectivity and surjectivity.</p>
<h2 id="injectivity">Injectivity</h2>
<p>The injective Representables give rise to a nice model for injective functions.</p>

<h3>
Injective Covariant Reperesentable
</h3>

<p>The following property holds of covariant representables:</p>
<blockquote>
<p>\(ℂ(S, h)\) is injective iff \(h\) is injective.</p>
</blockquote>

<h4>
Proof
</h4>

<p>First we show that if \(h\) is injective then \(ℂ(S, h)\) is injective:</p>
<pre class="sourceCode haskell"><code>ℂ(S, h) f == ℂ(S, h) g
  == {- definition ℂ(S, h) -}
h . f == h . g
  =&gt; {- injective h -}
f == g
</code></pre>
<p>Then we show that if \(ℂ(S, h)\) is injective then \(h\) is injective:</p>
<pre class="sourceCode haskell"><code>h . f == h . g
  == {- definition ℂ(S, h) -}
ℂ(S, h) f == ℂ(S, h) g
  =&gt; {- injective ℂ(S, h) -}
f == g
</code></pre>

<h3>
Injective Contravariant Reperesentable
</h3>

<p>Here’s a property of the contravariant representable functor:</p>
<blockquote>
<p>\(ℂ(h, S)\) is injective iff \(h\) is surjective.</p>
</blockquote>

<h4>
Proof
</h4>

<p>We work with the contrapositive to show that if \(h\) is surjective, then \(ℂ(h, S)\) is injective:</p>
<pre class="sourceCode haskell"><code>f ≠ g
  == {- definition inequality -}
∃ y . f y ≠ g y
  == {- surjective h -}
∃ x . f (h x) ≠ g (h x)
  == {- definition inequality -}
f . h ≠ g . h
  == {- definition ℂ(h, S) -}
ℂ(h, S) f ≠ ℂ(h, S) g
</code></pre>
<p>Finally we show that if \(h\) is not surjective, then \(ℂ(h, S)\) is not injective:</p>
<pre class="sourceCode haskell"><code>let h 0 = 0 {- h : {0} -&gt; {0,1} -}
let f 0 = 0, f 1 = 0
let g 0 = 0, g 1 = 1
</code></pre>
<p>then</p>
<pre class="sourceCode haskell"><code>f . h = g . h
  == {- definition ℂ(h, S) -}
ℂ(h, S) f = ℂ(h, S) g
</code></pre>
<p>but</p>
<pre class="sourceCode haskell"><code> f ≠ g
</code></pre>
<p>Sadly, I don’t like this part of the proof, since it involves finding a counterexample to the injectivity of \(ℂ(h, S)\) when \(h\) is not surjective, and I prefer constructive proofs. Nevertheless, we’ve shown that \(ℂ(h, S)\) is injective iff \(h\) is surjective, which gives us the right cancellative definition of surjection.</p>]]></description>
    <pubDate>Thu, 07 Apr 2011 00:00:00 UT</pubDate>
    <guid>http://zenzike.com/posts/2011-04-07-injective-representables.html</guid>
</item>
<item>
    <title>Rho-llercoaster Rides</title>
    <link>http://zenzike.com/posts/2011-01-16-rho-llercoaster-rides.html</link>
    <description><![CDATA[<p>Last week I attended the <a href="http://www.meetup.com/hoodlums/">London Haskell Hoodlums</a> meetup, where we worked on solving one of the <a href="http://code.google.com/codejam/contest/dashboard?c=433101#s=p2">Google Code Jam</a> problems. If you’re relatively new to Haskell, I can definitely recommend these kinds of meetings: they’re a great way of learning how to tackle problems in a functional style. This post is about the solution I came up with on the journey home, and uses an unusual characterisation of an unfold.</p>
<p>The problem is to calculate how much money a roller coaster ride makes in a day, where each time a person completes a ride £1 is made. People queue up for the ride in groups, and groups cannot be split up or reordered. The ride has a capacity of \(k\) people, and is filled with as many groups as possible before it is started. As soon as the ride is completed, the groups in the ride rejoin the queue in the same order they went in. Over the course of the day, the ride will run a total of \(r\) times.</p>
<p>Since this post is a literate Haskell file which can be compiled, we first need to declare the imports that will be used:</p>
<pre class="sourceCode literate haskell"><code>&gt; import Text.Printf (printf)
</code></pre>
<p>This imports the handy \(printf\) function which will help to output the solution in the format expected.</p>
<h2 id="creating-rides">Creating Rides</h2>
<p>To solve this problem, we first create the infinite list of rides which would be taken if the ride went on indefinitely. The creation of infinite lists is an example of an \(unfold\), which we can define as follows:</p>
<pre class="sourceCode literate haskell"><code>&gt; unfold :: (a -&gt; (b, a)) -&gt; a -&gt; [b]
&gt; unfold f x = y : unfold f x'
&gt;  where
&gt;   (y, x') = f x
</code></pre>
<p>Roughly speaking, you can think of an \(unfold\) as taking a grow function and a seed, and applying the grow function to the seed. The result is a value which is added to our list, along with a new seed used to produce the next value in the list. This process is repeated forever, thus generating a stream of values.</p>
<p>The stream of rides is a function of the capacity of the ride, and the current order of the groups, and we can define this stream as follows:</p>
<pre class="sourceCode literate haskell"><code>&gt; rides :: Int -&gt; [Int] -&gt; [[Int]]
&gt; rides k ps = unfold (requeue . usher k) ps
</code></pre>
<p>The <code>usher</code> function takes a capacity and a list of groups to produce two lists: the first represents the groups which will take the ride next, and the second represents the remaining groups.</p>
<pre class="sourceCode literate haskell"><code>&gt; usher :: Int -&gt; [Int] -&gt; ([Int], [Int])
&gt; usher _ []    = ([], [])
&gt; usher 0 ps    = ([], ps)
&gt; usher k ps@(p:ps')
&gt;   | k &gt;= p    = (p:qs, rs)
&gt;   | otherwise = ([], ps)
&gt;  where
&gt;   (qs, rs) = usher (k - p) ps'
</code></pre>
<p>To model the fact that groups who have just taken the ride want to come back for another go, we use the \(requeue\) function as follows:</p>
<pre class="sourceCode literate haskell"><code>&gt; requeue :: ([a], [a]) -&gt; ([a], [a])
&gt; requeue (ps, qs) = (ps, qs ++ ps)
</code></pre>
<p>The profit that is made in a day becomes a simple calculation:</p>
<pre class="sourceCode literate haskell"><code>&gt; profit :: (Int, Int, [Int]) -&gt; Int
&gt; profit (r, k, ps) = sum . concat . take r $ rides k ps
</code></pre>
<p>This takes some input parameters and a list of groups, and first organises the groups into a stream of potential rides. The first \(r\) rides in this stream are then taken and concatenated together. The sum of this list gives us our final result.</p>
<h2 id="unfold-and-rho">Unfold and Rho</h2>
<p>While the algorithm given above works fine for relatively small inputs, it is too inefficient for larger problems, where the number of runs, \(r\), is very large. One obvious inefficiency is in our \(unfold\), where at some point the seed group will already have been seen, but must be ushered all over again.</p>
<p>While the process can be made more efficient by using memoization, another approach is to consider how the result of the \(unfold\) can be decomposed. To do this, we’ll define a function \(rho\) which satisfies:</p>
<pre class="sourceCode haskell"><code>unfold f x = ys ++ cycle zs
 where
  (ys, zs) = rho f x
</code></pre>
<p>This decomposition uses a function \(rho\), named as such since the greek symbol, \(ρ\), is written as an initial segment followed by a cycle (I first saw this use of \(ρ\) in <a href="http://en.wikipedia.org/wiki/Pollard's_rho_algorithm">Pollard’s rho algorithm</a> which is also a cycle finding algorithm).</p>
<pre class="sourceCode literate haskell"><code>&gt; rho :: Eq a =&gt; (a -&gt; (b, a)) -&gt; a -&gt; ([b], [b])
&gt; rho f x = rho' [] f x
</code></pre>
<p>The type signature of \(rho\) is very similar to that of an \(unfold\), but differs in that two lists are returned rather than one. The first list is the initial segment, and the second is the cyclic part.</p>
<p>The \(rho\) function makes use of \(rho'\), which accumulates pairs of seeds and their corresponding values. For efficiency, these are stored in reverse order (so the list \(zs\) gets named \(sz\)).</p>
<pre class="sourceCode literate haskell"><code>&gt; rho' :: Eq a =&gt; [(b, a)] -&gt; (a -&gt; (b, a)) -&gt; a -&gt; ([b], [b])
&gt; rho' sz f x
&gt;   | any ((== x) . snd) sz =
&gt;       diag (map fst) . break ((== x) . snd) . reverse $ sz
&gt;   | otherwise = rho' ((y, x):sz) f x'
&gt;  where
&gt;   (y, x') = f x
</code></pre>
<p>The key here is that we check the list of previously computed values, \(sz\), to see whether or not the current seed, \(x\), is present. If the seed is present in the list, then we have found a cycle and therefore, after recovering the order of the list, must break the list into two parts: elements which come before this seed, and those which come after. Once this is done, we extract the values we are interested in from the resulting pair of lists. This makes use of the \(diag\) function which simply applies a function to a pair of values:</p>
<pre class="sourceCode literate haskell"><code>&gt; diag :: (a -&gt; b) -&gt; (a, a) -&gt; (b, b)
&gt; diag f (x, y) = (f x, f y)
</code></pre>
<p>If the seed value \(x\) does not appear in the list, we add the pair which consists of \(x\) and its corresponding value \(y\), and continue calculation with the new seed \(x'\).</p>
<p>Finally, we can use this to define an optimised version of \(profit\). Given a list of groups \(ps\) and a number of rides \(r\) we wish to find the largest \(s\) and smallest \(t\) such that:</p>
<pre class="sourceCode haskell"><code>r == length qss + s * length rss + t
 where
  (qss, rss) = rho (requeue . usher k) ps
</code></pre>
<p>The idea here is that we can decompose the number of rides into the rides which are performed before the cycle, those which are part of the cycle, and a final number of rides which don’t make a complete cycle.</p>
<p>Once those values are calculated, we can work out the profit as the following function:</p>
<pre class="sourceCode literate haskell"><code>&gt; profit' :: (Int, Int, [Int]) -&gt; Int
&gt; profit' (r, k, ps) = u + (s * v) + (sum . concat) (take t rss)
&gt;  where
&gt;   (qss, rss) = rho (requeue . usher k) ps
&gt;   u          = sum . concat $ qss
&gt;   v          = sum . concat $ rss
&gt;   (s, t)     = head [(s', t') |
&gt;     t' &lt;- [0 .. r - length qss],
&gt;     let s' = (r - t' - length qss) `div` (length rss),
&gt;     r == length qss + s' * length rss + t']
</code></pre>
<p>This works by decomposing the queues into \(qss\) and \(rss\), and then finding the constants \(s\) and \(t\) which satisfy the equation above. Once those values are known, the profit can be worked out by simple arithmetic: the profit is the number of people, \(u\), in the groups which form the initial rides before a cycle, \(qss\), added to the number of cycles, \(s\), multiplied by the size of the cycle, \(v\), added to the number of people in the final \(t\) groups which do not form a complete cycle in \(rss\).</p>
<h2 id="plumbing">Plumbing</h2>
<p>With the algorithm in place, all that is needed to solve this problem is provide some functions that will decode the given input string into the datatypes we require.</p>
<p>The input format is a file where the first line has a number which dictates the number of rides that proceed. Each ride is described in two lines. The first line contains three space separated values: the number of times the ride is started, the capacity of the ride, and the number of groups in the queue. The second line contains a list of space separated values which represents the number of people in each group. While we could certainly use <a href="http://www.haskell.org/haskellwiki/Parsec">Parsec</a> to do this, using a parser seems a little overkill since decoding this can be expressed in terms of the following function:</p>
<pre class="sourceCode literate haskell"><code>&gt; decode :: String -&gt; [(Int, Int, [Int])]
&gt; decode cs = [(r, k, ps) | ([r, k, _],ps) &lt;- pairs . tail . convert $ cs]
</code></pre>
<p>The convert function turns the input string into a list of lists of numbers. The first line of this list is ignored, and all consecutive lists are paired up. These pairs are then used to form the input type appropriate for the <code>profit</code> function.</p>
<p>The conversion from a string makes use of <code>lines</code> and <code>words</code> to find line separated, and space separated values:</p>
<pre class="sourceCode literate haskell"><code>&gt; convert :: String -&gt; [[Int]]
&gt; convert = (map (map read . words) . lines)
</code></pre>
<p>The pairs function is not standard, so here’s a simple definition:</p>
<pre class="sourceCode literate haskell"><code>&gt; pairs :: [a] -&gt; [(a,a)]
&gt; pairs []       = []
&gt; pairs [x]      = [(x, undefined)]
&gt; pairs (x:y:xs) = (x, y):pairs xs
</code></pre>
<p>Finally, we can put this all together to create a program that takes the appropriate input on the <code>stdin</code> pipe, and produces the output on the <code>stdout</code> pipe. The <code>interact</code> function provides much of the plumbing required, and is part of the prelude:</p>
<pre class="sourceCode haskell"><code>interact :: (String -&gt; String) -&gt; IO ()
</code></pre>
<p>This takes a function that is used to consume the input in <code>stdin</code> and its result is placed as output in <code>stdout</code>. By using <code>interact</code>, we can define a main function that puts our solution together:</p>
<pre class="sourceCode literate haskell"><code>&gt; main = interact $
&gt;   concat . zipWith (printf &quot;Case #%d: %d\n&quot;) [1 :: Int ..] .
&gt;     map profit' . decode
</code></pre>
<p>The key part is the function that <code>interact</code> takes as its argument, which takes a <code>String</code> and produces a <code>String</code>. The input string is first decoded into a list of datatypes that we map over using <code>profit</code> to produce a list of results. These results are then zipped together with the list of solution numbers, using a printing function which produces a list of strings in the right format. Finally, these strings are appended together using <code>concat</code> to produce our desired output.</p>
<p>Running this algorithm against the large practice dataset is remarkably fast: it is solved in about 0.6 seconds on my machine, whereas using the slower version didn’t finish after a minute.</p>
<h2 id="conclusion">Conclusion</h2>
<p>As a concluding remark, I started by tackling this using a cycle detecting algorithm, since we can decompose the list of group orderings as follows:</p>
<pre class="sourceCode haskell"><code>ps == qs ++ cycle rs
</code></pre>
<p>In particular, we are interested in the shortest \(qs\) and \(rs\) that satisfy this equation, and can construct a function \(uncycle\) which calculates these for us.</p>
<pre class="sourceCode literate haskell"><code>&gt; uncycle :: Eq a =&gt; [a] -&gt; ([a], [a])
&gt; uncycle ps = uncycle' [] ps
</code></pre>
<pre class="sourceCode literate haskell"><code>&gt; uncycle' :: Eq a =&gt; [a] -&gt; [a] -&gt; ([a], [a])
&gt; uncycle' sp [] = (reverse sp, [])
&gt; uncycle' sp (q:qs)
&gt;   | elem q sp = (takeWhile (/= q) . reverse $ sp, q : takeWhile (/= q) qs)
&gt;   | otherwise = uncycle' (q:sp) qs
</code></pre>
<p>This function makes the assumption that a cycle is formed whenever an element of the list appears more than once. While this would certainly be appropriate if the function applied in the unfold were a bijection, the \(usher\) function is not bijective, since two separate groups might have the same number of people and be the result of an ushering. This might be solved by either labelling the groups to make them unique, or by returning the seeding values along with the result: this is essentially how \(rho\) works.</p>]]></description>
    <pubDate>Sun, 16 Jan 2011 00:00:00 UT</pubDate>
    <guid>http://zenzike.com/posts/2011-01-16-rho-llercoaster-rides.html</guid>
</item>
<item>
    <title>Telling Fibs</title>
    <link>http://zenzike.com/posts/2010-12-16-telling-fibs.html</link>
    <description><![CDATA[<p>Recently I’ve been asked to interview candidates for a programming position using C++. One of the questions I ask is to implement a function that returns the \(n\)th Fibonacci number for a given \(n\). This article compares the linear procedural version of the Fibonacci algorithm with a linear functional version.</p>
<p>For candidates who have never heard of, or can’t remember how the Fibonacci sequence goes, I write out the following sequence, and explain that each new number is the sum of the previous two:</p>
<pre class="sourceCode haskell"><code>n     : 0, 1, 2, 3, 4, 5, 6, ...
fib n : 1, 1, 2, 3, 5, 8, 13, ...
</code></pre>
<p>Good candidates are able to write out the following recursive definition (though I have yet to encounter a candidate that says “that’s my program: it’s in Haskell!”):</p>
<pre class="sourceCode haskell"><code>fib 0 = 1
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)
</code></pre>
<p>So far, every good candidate has gone for something along the lines of the following procedural code:</p>
<pre class="sourceCode haskell"><code>int fib (int n) {
  if (n == 0 || n == 1) {
    return 1;
  }
  else {
    return (fib (n - 1) + fib (n - 2));
  }
}
</code></pre>
<p>After asking for the complexity of this algorithm, which is almost invariably incorrectly guessed as \(O(n^2)\), when it is in fact closer to \(O(2^n)\), I usually ask whether or not they can derive a linear time version instead.</p>
<h2 id="linear-procedural">Linear Procedural</h2>
<p>With help, good candidates have been able to come up with something along the following lines:</p>
<pre class="sourceCode haskell"><code>int fib (int n) {
  if (n == 0 || n == 1) {
    return 1;
  }

  int m    = 2;
  int fib2 = 1;
  int fib1 = 1;
  int fibm = 2;

  while (m &lt; n) {
    m    = m + 1;
    fib2 = fib1;
    fib1 = fibm;
    fibm = fib1 + fib2;
  }
  return fibm;
}
</code></pre>
<p>We can prove that this algorithm works by looking at the \(invariant\), and the \(variant\) of the loop body. The invariant proves correctness, while the variant proves termination of this code.</p>
<p>The invariant is a condition that must be true before entering and after exiting the loop body. In our case, we establish the following conditions:</p>
<pre class="sourceCode haskell"><code>fib1 = fib (m - 1)
fib2 = fib (m - 2)
fibm = fib (m - 1) + fib (m - 2) = fib m
</code></pre>
<p>It’s easy to check that this is true when we first enter the body of the loop, and while it’s a little tedious, since we’re not making use of multiple assignment (where we can simultaneously change values), we can also show that the invariance holds in the loop body.</p>
<p>The loop variant is used to show that the algorithm is progressing towards its goal. In our case, it is enough to show that the distance from <code>m</code> to <code>n</code> is decreasing. By expressing the old value of <code>m</code> as <code>m₀</code>, we have:</p>
<pre class="sourceCode haskell"><code>| n - m | &lt; | n - m₀ |
</code></pre>
<p>In terms of execution speed, it’s easy to see that this is a linear time algorithm: the main body of the loop is executed \(n\) times, and the operations in the body are all constant time.</p>
<h2 id="linear-functional">Linear Functional</h2>
<p>In Haskell, a linear time version is remarkably simple to express:</p>
<pre class="sourceCode literate haskell"><code>&gt; fibs :: [Int]
&gt; fibs   = 1 : fibs'
&gt; fibs'  = 1 : fibs''
&gt; fibs'' = zipWith (+) fibs fibs'
</code></pre>
<p>The \(n\)th Fibonacci can be extracted using a simple list lookup:</p>
<pre class="sourceCode literate haskell"><code>&gt; fib :: Int -&gt; Int
&gt; fib n = fibs !! n
</code></pre>
<p>This is a linear time algorithm because the <code>fibs</code> stream is constructed in linear time: each new element of the list is calculated by adding the previous two values, which is a constant time operation. Looking up values in a list is also done linear time.</p>
<h2 id="conclusion">Conclusion</h2>
<p>It’s interesting to see the procedural and the functional versions of these algorithms side by side, and I think it’s no exaggeration to say that the correctness of the functional ones is much easier to see than the correctness of the procedural ones.</p>
<p>As a means of discerning how good a candidate is, I’ve found that implementing fibs has been a particularly telling measure: bad candidates take a very long time to get to the end of the question, while only very good candidates have been able to derive a linear version of the algorithm.</p>]]></description>
    <pubDate>Thu, 16 Dec 2010 00:00:00 UT</pubDate>
    <guid>http://zenzike.com/posts/2010-12-16-telling-fibs.html</guid>
</item>

    </channel> 
</rss>
