<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Many things about OCaml]]></title><description><![CDATA[Well-typed programs cannot go wrong. - Robin Milner]]></description><link>http://typeocaml.com/</link><generator>Ghost 0.5</generator><lastBuildDate>Tue, 21 Apr 2026 05:39:09 GMT</lastBuildDate><atom:link href="http://typeocaml.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Pearl No.4 - Kth Smallest in the Union of 2 Sorted Collections]]></title><description><![CDATA[<p><img src="http://typeocaml.com/content/images/2017/10/cube-2-1.jpg#hero" alt="hero"></p>

<p>Here is the Pearl No.4:</p>

<blockquote>
  <p>Let A and B be two disjoint ordered collections with distinct elements inside. Their combined size is greater than k. </p>
  
  <ol>
  <li>A and B are sorted, but the underlying data structures are not specified as they are collections.</li>
  <li>A and B do not have common elements, since they are <em>disjoint</em></li>
  <li>All elements in A and B are distinct</li>
  <li>The total number of all elements is larger than k</li>
  </ol>
  
  <p><strong>Find the kth smallest element of A ∪ B.</strong></p>
  
  <p>By definition, the kth smallest element of a collection is one for which there are exactly k elements smaller than it, so the 0th smallest is the smallest, i.e., <strong>k starts from 0</strong>.</p>
</blockquote>

<p>Let's have a look at an example.</p>

<p><img src="http://typeocaml.com/content/images/2015/12/example-4.jpg" alt="example"></p>

<h1 id="easysolutionmerge">Easy Solution - Merge</h1>

<p>I believe it is easy enough to come out with the <strong>merge</strong> solution. Since both A and B are sorted, we can just start from the beginning of A and B and do the regular <a href="http://typeocaml.com/2014/12/04/recursion-reloaded/">merge operation</a> until we reach <code>kth</code>. (In fact, when I tried to produce the example figure above with <code>k = 7</code>, I did use <em>merge</em> in my head to find the target element <code>36</code>.)</p>

<p>Say A and B are <em>lists</em>, we can have the following solution in OCaml:</p>

<pre><code class="ocaml">let kth_merge a b k =  
  let rec merge i = function
    | x::_, y::_ when i = k -&gt; min x y
    | m::_, [] | [], m::_ when i = k -&gt; m
    | _::ms, [] | [], _::ms when i &lt; k -&gt; merge (i+1) ([], ms)
    | x::xs, y::ys when i &lt; k -&gt; 
      merge (i+1) (if x &lt; y then xs, y::ys else x::xs, ys)
    | _ -&gt; assert false
  in
  merge 0 (a,b)
</code></pre>

<p>The time complexity of this is obviously <code>O(n)</code> or more precisely <code>O(k)</code>. </p>

<p>This approach assumes A and B being lists and <em>merge</em> should be a quite optimal solution. However, the problem doesn't force us to use <em>list</em> only. If we assume A and B to be <em>array</em>, can we do better?</p>

<h1 id="recallbinarysearch">Recall Binary Search</h1>

<p>As described in <a href="http://typeocaml.com/2015/01/20/mutable/">Mutable</a>, when looking for an element in a <em>sorted array</em>, we can use <em>binary search</em> to obtain <code>O(log(n))</code> performance, instead of linear searching.</p>

<blockquote>
  <p>For binary search, we just go to the middle and then turn left or right depending on the comparison of the middle value and our target.</p>
</blockquote>

<p><img src="http://typeocaml.com/content/images/2015/12/binary_search.jpg" alt="binary search"></p>

<p>Coming back to our current problem, </p>

<ol>
<li>We are searching for something (a value with a rank instead of a particular value itself though)  </li>
<li>The data structures of A and B are not limited to <em>lists</em>, but also can be <em>arrays</em>.  </li>
<li>Both A and B are sorted.</li>
</ol>

<p>These characteristics present <em>nothing directly</em> towards a classic binary search problem, however, they seem hinting us that <em>binary search</em> is worth trying. </p>

<p>Let's have a go.</p>

<h1 id="doublebinaryranksearch">Double Binary Rank Search</h1>

<p>So here is the A and B, we want to find the <code>kth</code> smallest value</p>

<p><img src="http://typeocaml.com/content/images/2017/10/ds_1-2.jpg" alt="ds_1"></p>

<p>Since we are trying <em>binary search</em>, we can just split A and B by their middle values respectively.</p>

<p><img src="http://typeocaml.com/content/images/2017/10/ds_2.jpg" alt="ds_2"></p>

<p>So what now? </p>

<p>In single binary search, we can compare the middle value with the target varlue. And if target is larger, then we go right; otherwise, we go left. </p>

<p>But in this double binary rank search problem, it is a little trickier:</p>

<ol>
<li>We have 2 sorted arrays instead of 1  </li>
<li>We are not searching for an element with a particular value, instead, with a particular rank (kth smallest)</li>
</ol>

<p>From point 1 above, the middle values split the two arrays into four parts; From point 2 above, we have to find out which part (out of the four) the kth would fall into. In addition, since its about rank instead of a value, it must be related to the lengths of the parts.</p>

<p>Let's assume <em>a &lt; b</em> (if not, then we can simply swap A and B).</p>

<p>So if a &lt; b, what we can induct?</p>

<p><img src="http://typeocaml.com/content/images/2017/10/ds_3-9.jpg" alt="ds_3"></p>

<p>The relationships between all the parts (including <code>a</code> and <code>b</code>) are demonstrated as above. The position of <code>ha</code> is dynamic as we only know the middle points a &lt; b. However, the relationship between <code>la, a, lb</code> and <code>b</code> is determined and we know for sure that there are definitely at least <code>la + lb + 1 (lenth of a is 1)</code> numbers smaller than <code>b</code>. Thus considering the rank <code>k</code>, if <code>k &lt;= la + lb + 1</code>:</p>

<ol>
<li>From Case 1 and 2, the kth element must be in <code>la</code>, or <code>a</code>, or <code>ha</code>, or <code>lb</code>  </li>
<li>From Case 3, it must be in <code>la</code>, or <code>a</code>, or <code>lb</code></li>
</ol>

<p>We therefore can know simply that <strong>if k &lt;= la + lb + 1, the kth smallest number definitely won't be in <code>hb</code></strong>.</p>

<p><img src="http://typeocaml.com/content/images/2017/10/ds_4-3.jpg" alt="ds_4"></p>

<p>What if k > la + lb + 1? Going back to the 3 cases:</p>

<ol>
<li>The kth element might be in <code>hb</code> because k can be big enough.  </li>
<li>From Case 1, it might be in <code>ha</code> if <code>ha</code> are all larger than <code>lb</code> otherwise, it might be in <code>lb</code>  </li>
<li>From Case 2, it might be in <code>ha</code> or <code>b</code>  </li>
<li>From Case 3, it is obviously that <code>la</code> doesn't have a chance to have the kth element.</li>
</ol>

<p>Thus <strong>if k > la + lb + 1, the kth smallest number definitely won't be in <code>la</code></strong>.</p>

<p><img src="http://typeocaml.com/content/images/2017/10/ds_5.jpg" alt="ds_5"></p>

<p>So every time we compare <code>k</code> with <code>la + lb + 1</code> and at least one part can be eliminated out. If a &lt; b, then either <code>la</code> or <code>hb</code> is removed; otherwise, either <code>lb</code> or <code>ha</code> is removed (as said, we can simply swap A and B).</p>

<pre><code class="ocaml">let kth_union k a b =  
  let sa = Array.length a and sb = Array.length b in
  let rec kth k (a, la, ha) (b, lb, hb) =
    if la &gt;= ha+1 then b.(k+lb)
    else if lb &gt;= hb+1 then a.(k+la)
    else  
      let ma = (ha+la)/2 and mb = (hb+lb)/2 in
      match a.(ma) &lt; b.(mb), k &gt;= ma-la+1+mb-lb with 
      | true, true -&gt; kth (k-(ma-la+1)) (a, ma+1, ha) (b, lb, hb)
      | true, false -&gt; kth k (a, la, ha) (b, lb, mb-1)
      | _ -&gt; kth k (b, lb, hb) (a, la, ha) (* swap *)
  in 
  kth k (a, 0, sa-1) (b, 0, sb-1)
</code></pre>

<p>Since every time we remove <code>1 / 4</code> elements, the complexity is <code>O(2*log(N))</code>, i.e., <code>O(log(N))</code>.</p>

<h1 id="remark">Remark</h1>

<p>This pearl is comparatively not difficult, however, the idea of process of elimination is worth noting. Instead of choosing which part is positive towards our answer, we can remove parts that is impossible and eventually we can achieve similar algorithmic complexity. </p>

<h1 id="afurtherslightimprovement">A further slight improvement</h1>

<p>From a reply in <a href="https://news.ycombinator.com/reply?id=15514451">hackernews</a>, it was suggested that</p>

<blockquote>
  <p>If the data structures can be split (as it seems), then the first step should be to get the head k element of both collections, so we only have to work with a maximum of 2k elements. Then the solution is not O(2 * log(N)) but O(2 * log(min(N,2k))).</p>
</blockquote>

<p>This would not significantly improve the performance however it makes sense especially when <code>k</code> is smaller than the lengths of both <code>A</code> and <code>B</code>. </p>]]></description><link>http://typeocaml.com/2017/10/19/pearl-no-4-double-binary-search/</link><guid isPermaLink="false">cc92adb6-a7b8-42e3-b7cc-dcbe5f462f6d</guid><category><![CDATA[binary search]]></category><category><![CDATA[pearls]]></category><category><![CDATA[selection]]></category><category><![CDATA[double binary search]]></category><dc:creator><![CDATA[Jackson Tale]]></dc:creator><pubDate>Thu, 19 Oct 2017 13:37:30 GMT</pubDate></item><item><title><![CDATA[Visualise Randomness]]></title><description><![CDATA[<p><img src="http://typeocaml.com/content/images/2015/11/visual_random-1.jpg#hero" alt="heor"></p>

<p>It has been almost half year since my last blog post on OCaml. Well, actually I haven't even touched OCaml for that long time. My current job (in Python) got much busier. But finally, things <s>camls</s> calms down a bit now. I can at least have time sitting in front of my 2008 macbook pro, opening terminal, doing </p>

<pre><code>opam update

opam upgrade

opam switch 4.02.3

eval `opam config env`
</code></pre>

<p>Hmmmm, I like this feeling. </p>

<p><strong>typeocaml</strong> is back now. I digged my typeocaml notebook from one of our 78 packing boxes, and went through the list of <em>many things about OCaml</em> that I planned to write about. Those items still look familiar but obviously not very clear in my mind now. One should never put a vacuum space in things beloved. They would fade.</p>

<p>Anyway, enough chit-chat, back to the topic.</p>

<hr>

<p>This post is about visualising the randomness of random number generators. It will be lightweight and is just something I did for fun with OCaml. We will know a good way to test randomness and also learn how to create a <em>jpg</em> picture using an OCaml image library: <strong>camlimages</strong>. I hope it would be tiny cool.</p>

<h1 id="whatisrandomness">What is randomness?</h1>

<p>Say, we got a function <code>var ran_gen : int -&gt; int</code> from nowhere. It claims to be a good random integer generator with uniform distribution, which takes a bound and "perfectly" generates a random integer within [0, bound). The usage is simple but the question is <em>can you trust it</em> or <em>will the numbers it generates be really random</em>?</p>

<p>For example, here is a rather simple <code>ran_gen_via_time</code>:</p>

<pre><code class="ocaml">let decimal_only f = f -. (floor f)  
let ran_via_time bound =  
  ((Unix.gettimeofday() |&gt; decimal_only) *. 100,000,000. |&gt; int_of_float) mod bound
(*
  Unix.gettimeofday() returns float like 1447920488.92716193 in second. 
  We get the decimal part and then amplify it to be integer like, i.e., 1447920488.92716193 ==&gt; 0.92716193 ==&gt; 92716193.
  Then we mod it by bound to get the final "random" number.
*)
</code></pre>

<p>This generator is based on the <em>timestamp</em> when it is called and then mod by the <em>bound</em>. Will it be a good generator? My gut tells me <em>not really</em>. If the calls to the function has some patterns, then eaily the numbers become constant. </p>

<p>For example, if the <em>bound</em> is 10, then at <em>t</em> I make first call, I will get <code>t mod 10</code>. If I call at <em>t + 10</em> again, I will get <code>(t+10) mod 10</code> which is actually <code>t mod 10</code>. If I call it every 10 seconds, then I get a constant. Thus this generator's randomness would not be as good as it claims to be.</p>

<p>For any given random number generator, we have to really make sure its randomness is good enough to suite our goal, especially when we have to rely on them for trading strategies, gaming applications, online gambling hosting, etc. </p>

<p>However, we also need to be aware of that most of random generators are not perfect (<em><a href="https://en.wikipedia.org/wiki/Random_number_generation">Random number generator</a></em> and <em><a href="https://en.wikipedia.org/wiki/Pseudorandom_number_generator">Pseudorandom number generator</a></em>). What we often do is just to see whether the randomness of a given generator can reach a certain level or not.</p>

<h1 id="testrandomnessusingstatistics">Test randomness using statistics</h1>

<p><a href="https://en.wikipedia.org/wiki/Chi-squared_test">Chi-squared test</a> is a fairly simple and common methodology to test randomness mathematically.</p>

<p>Say, we have a generator producing random integers between [0, 10) with uniform distribution. So ideally, if the generator is perfect, and if we ran 1000 times, then there would be 100 of <em>0</em>, 100 of <em>1</em>, ..., 100 of <em>9</em> , right? For the test, we can just try the generator <em>N</em> times, and see whether the frequency of each number generated somehow matches or is close to <em>N / bound</em>.</p>

<p>Of course, the frquencies of numbers would not exactly match expectation. So we need some mathematics to measure the level of matching.</p>

<ol>
<li><em>k</em> is the number of possible candidates - e.g., <em>k = 10</em> for [0, 10)  </li>
<li><em>Ei</em> is the expected frequency for each candidate - <em>i = 1, 2, k</em>  </li>
<li><em>Oi</em> is the frequency for each candidate produced by the generator - <em>i = 1, 2, k</em></li>
</ol>

<p>Thus we can get <code>X^2 = (O1-E1)^2/E1 + ... + (Ok-Ek)^2/Ek</code></p>

<p>Essentially, the bigger <code>X^2</code> is, the matching is more unlikely. If we really want to see how unlikely or likely they match each other, then we need to check <code>X^2</code> against the <em>chi square distribution table</em> like below:</p>

<p><img src="https://faculty.elgin.edu/dkernler/statistics/ch09/images/chi-square-table.gif" alt="chi square distribution table"></p>

<ol>
<li>The <em>Degrees of Freedom</em> is our <code>k-1</code> (if <em>k = 1</em>, then our freedom is <em>0</em>, which means we just have one to choose all the time and don't have any freedom).  </li>
<li>The bold headings of columns are the probabilities that the observations match the expectations.  </li>
<li>The many numbers in those cells are values of <code>X^2</code>.</li>
</ol>

<p>For example, say in our case above, <code>k = 10</code>, so <em>Degree of freedom is 9</em>. </p>

<p>If we get <code>X^2</code> as <em>2</em>, which is less than <em>2.088</em>, then we can say we have more than <em>0.99</em> probability that the observations match the expectations, i.e., our random generator follows uniform distribution very well. </p>

<p>If we get <code>X^2</code> as <em>23</em>, which is bigger than <em>21.666</em>, the probability of matching is less than <em>0.01</em>, so our generator at least is not following uniform distribution.</p>

<p>This is roughly how we could use Chi-squared test for randomness checking. Of course, the description above is amateur and I am just trying to put it in a way for easier understanding. </p>

<h1 id="testrandomnessviavisualisation">Test randomness via visualisation</h1>

<p>Let's admit one thing first: Math can be boring. Although math can describe things most precisely, it does not make people like me feel intuitive, or say, straightforward. If I can directly see problems and the solutions via my eyes, I would be much happier and this was the reason why I tried to visualise the randomness of generators.</p>

<p>The way of the visualisation is fairly simple.</p>

<ol>
<li>We create a canvas.  </li>
<li>Each pixel on the canvas is a candidate random number that the generator can produce.  </li>
<li>We run the generator for lots of times.  </li>
<li>The more times a pixel gets hit, we draw a deeper color on it.  </li>
<li>In the end, we can directly feel the randomness depending on the color distribution on the canvas.</li>
</ol>

<h2 id="atrivialexample">A trivial example</h2>

<p>Initially we have such a canvas.</p>

<p><img src="http://typeocaml.com/content/images/2015/11/randomness_canvas.jpg" alt="canvas"></p>

<p>We use the random generator generating numbers. If a slot get a hit, we put a color on it.</p>

<p><img src="http://typeocaml.com/content/images/2015/11/randomness_1.jpg" alt="random_1"></p>

<p>If any slot keeps been hit, we put deeper and deeper color on it.</p>

<p><img src="http://typeocaml.com/content/images/2015/11/randomness_2.jpg" alt="random_2"></p>

<p>When the generator finishes, we can get a final image.</p>

<p><img src="http://typeocaml.com/content/images/2015/11/randomness_3.jpg" alt="random_3"></p>

<p>From the resulting image, we can see that several numbers are really much deeper than others, and we can directly get a feeling about the generator. </p>

<p>Of course, this is just trivial. Normally, we can get much bigger picture and see the landscape of the randomness, instead of just some spots. Let's get our hands dirty then.</p>

<h2 id="preparation">Preparation</h2>

<p>Assuming the essentials of OCaml, such as <em>ocaml</em> itself, <em>opam</em> and <em>ocamlbuild</em>, have been installed, the only 3rd party library we need to get now is <a href="https://bitbucket.org/camlspotter/camlimages">camlimagges</a>. </p>

<p>Before invoke <code>opam install camlimages</code>, we need to make sure <a href="http://stackoverflow.com/questions/24805385/camlimages-fatal-error-exception-failureunsupported"><em>libjpeg</em> being installed first in your system</a>. Basically, <em>camlimages</em> relies on system libs of <em>libjpeg</em>, <em>libpng</em>, etc to save image files in respective formats. In this post, we will save our images to <code>.jpg</code>, so depending on the operating system, we can just directly try installing it by the keyword of <em>libjpeg</em>.</p>

<p>For example, </p>

<ul>
<li><em>mac</em> -> <code>brew install libjpeg</code>; </li>
<li><em>ubuntu</em> -> <code>apt-get install libjpeg</code>; </li>
<li><em>redhat</em> -> <code>yum install libjpeg</code></li>
</ul>

<p>After <em>libjpeg</em> is installed, we can then invoke <code>opam install camlimages</code>.</p>

<p>In addition, for easier compiling or testing purposes, maybe <a href="https://ocaml.org/learn/tutorials/ocamlbuild/">ocamlbuild</a> <code>opam install ocamlbuild</code> and <a href="https://opam.ocaml.org/blog/about-utop/">utop</a> <code>opam install utop</code> could be installed, but it is up to you.</p>

<pre><code>brew install libjpeg  
opam install camlimages  
opam install ocamlbuild  
opam install utop  
</code></pre>

<h2 id="thegeneralprocess">The general process</h2>

<p>The presentation of an <em>RGB</em> image in memory is a bitmap, which is fairly simple: just an 2-d array (<em>width</em> x <em>height</em>) with each slot holding a color value, in a form like <em>(red, green, blue)</em>. Once we have such a bitmap, we can just save it to the disk in various formats (different commpression techniques).</p>

<p>So the process could be like this:</p>

<ol>
<li>Create a matrix array, with certain size (<em>width</em> and <em>height</em>)  </li>
<li>Manipulate the values (colors) of all slots via random generated numbers  </li>
<li>Convert the matrix bitmap to a real image  </li>
<li>Save the image to a <em>jpg</em> file</li>
</ol>

<h2 id="fillthematrix">Fill the matrix</h2>

<p>First, let's create a matrix.</p>

<pre><code class="ocaml">open Camlimages

(* w is the width and h is the height *)
let bitmap = Array.make_matrix w h {Color.r = 255; g = 255; b = 255}  
(* 
  Color is a type in camlimages for presenting RGB colors,
  and initially white here.
*)
</code></pre>

<p>When we generate a random number, we need to map it to a slot. Our image is a rectangle, i.e., having rows and columns. Our random numbers are within a bound <em>[0, b)</em>, i.e., 1-d dimension. A usual way to convert from 1-d to 2-d is just divide the number by the width to get the row and modulo the number by the width to get the col.</p>

<pre><code class="ocaml">let to_row_col ~w ~v = v / w, v mod w  
</code></pre>

<p>After we get a random number, we now need to fill its belonging slot darker. Initially, each slot can be pure white, i.e., <code>{Color.r = 255; g = 255; b = 255}</code>. In order to make it darker, we simply just to make the <em>rgb</em> equally smaller.</p>

<pre><code class="ocaml">let darker {Color.r = r;g = g;b = b} =  
  let d c = if c-30 &gt;= 0 then c-30 else 0 
  in 
  {Color.r = d r;g = d g;b = d b}
(*
  The decrement `30` really depends on how many times you would like to run the generator 
  and also how obvious you want the color difference to be.
*)
</code></pre>

<p>And now we can integrate the major random number genrations in.</p>

<pre><code class="ocaml">(*
  ran_f: the random number generator function, produce number within [0, bound)
         fun: int -&gt; int
  w, h:  the width and height
         int
  n:     the expected times of same number generated
         int

  Note in total, the generator will be called w * h * n times.
*)
let random_to_bitmap ~ran_f ~w ~h ~n =  
  let bitmap = Array.make_matrix w h {Color.r = 255; g = 255; b = 255} in
  let to_row_col ~w ~v = v / w, v mod w in
  let darker {Color.r = r;g = g;b = b} = let d c = if c-30 &gt;= 0 then c-30 else 0 in {Color.r = d r;g = d g;b = d b} 
  in
  for i = 1 to w * h * n do
    let row, col = to_row_col ~w ~v:(ran_f (w * h)) in
    bitmap.(row).(col) &lt;- darker bitmap.(row).(col);
  done;
  bitmap
</code></pre>

<h2 id="convertthematrixtoanimage">Convert the matrix to an image</h2>

<p>We will use the module <em>Rgb24</em> in <em>camlimages</em> to map the matrix to an image.</p>

<pre><code class="ocaml">let bitmap_to_img ~bitmap =  
  let w = Array.length bitmap in
  let h = if w = 0 then 0 else Array.length bitmap.(0) in
  let img = Rgb24.create w h in
  for i = 0 to w-1 do
    for j = 0 to h-1 do
      Rgb24.set img i j bitmap.(i).(j)
    done
  done;
  img
</code></pre>

<h2 id="savetheimage">Save the image</h2>

<p>Module <em>Jpeg</em> will do the trick perfectly, as long as you remembered to install <em>libjpeg</em> before <em>camlimages</em> arrives.</p>

<pre><code class="ocaml">let save_img ~filename ~img = Jpeg.save filename [] (Images.Rgb24 img)  
</code></pre>

<h2 id="ourmasterfunction">Our master function</h2>

<p>By grouping them all together, we get our master function.</p>

<pre><code class="ocaml">let random_plot ~filename ~ran_f ~w ~h ~n =  
  let bitmap = random_to_bitmap ~ran_f ~w ~h ~n in
  let img = bitmap_to_img ~bitmap in
  save_img ~filename ~img
</code></pre>

<p>All source code is in here <a href="https://github.com/MassD/typeocaml_code/tree/master/visualise_randomness">https://github.com/MassD/typeocaml_code/tree/master/visualise_randomness</a></p>

<h2 id="resultstandardrandomint">Result - standard Random.int</h2>

<p>OCaml standard lib provides a <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Random.html">random integer genertor</a>:</p>

<pre><code class="ocaml">val int : int -&gt; int

Random.int bound returns a random integer between 0 (inclusive) and bound (exclusive). bound must be greater than 0 and less than 2^30.  
</code></pre>

<p>Let's have a look what it looks like:</p>

<pre><code class="ocaml">let _ = random_plot ~filename:"random_plot_int.jpg" ~ran_f:Random.int ~w:1024 ~h:1024 ~n:5  
</code></pre>

<p><img src="https://raw.githubusercontent.com/MassD/typeocaml_code/master/visualise_randomness/random_plot_int.jpg" alt="ran_int"></p>

<p>Is it satisfying? Well, I guess so.</p>

<h2 id="resultran_gen_via_time">Result - ran_gen_via_time</h2>

<p>Let's try it on the <code>ran_gen_via_time</code> generator we invented before:</p>

<pre><code class="ocaml">let decimal_only f = f -. (floor f)  
let ran_via_time bound =  
  ((Unix.gettimeofday() |&gt; decimal_only) *. 100,000,000. |&gt; int_of_float) mod bound

let _ = random_plot ~filename:"random_plot_time.jpg" ~ran_f:ran_via_time ~w:1024 ~h:1024 ~n:5  
</code></pre>

<p><img src="https://raw.githubusercontent.com/MassD/typeocaml_code/master/visualise_randomness/random_plot_time.jpg" alt="ran_time"></p>

<p>Is it satisfying? Sure not.</p>

<p>Apparently, there are quite some patterns on images. Can you identify them?</p>

<p>For example,</p>

<p><img src="http://typeocaml.com/content/images/2015/11/random_plot_time.jpg" alt="ran_time_patr"></p>

<p>One pattern is the diagonal lines there (parrallel to the red lines I've added).</p>

<h1 id="onlyquickandfun">Only quick and fun</h1>

<p>Of course, visualisation of randomness is nowhere near accurately assess the quality of random geneators. It is just a fun way to feel its randomness.</p>

<p>I hope you enjoy it.</p>

<hr>

<h1 id="jpgvspng">JPG vs PNG</h1>

<p>Pointed by <a href="https://news.ycombinator.com/item?id=10609990">Ono-Sendai on hacker news</a>, it might be better to use <code>png</code> rather than <code>jpg</code>.</p>

<p>I've tried and the results for the bad <code>ran_gen_via_time</code> are like:</p>

<h2 id="jpg">JPG</h2>

<p><img src="https://raw.githubusercontent.com/MassD/typeocaml_code/master/visualise_randomness/random_plot_time.jpg" alt="jpg"></p>

<h2 id="png">PNG</h2>

<p><img src="https://raw.githubusercontent.com/MassD/typeocaml_code/master/visualise_randomness/random_plot_time.png" alt="png"></p>

<p>Seems not that different from my eyes. But anyway it was a good point.</p>

<p><a href="https://github.com/MassD/typeocaml_code/blob/master/visualise_randomness/plot_random.ml">https://github.com/MassD/typeocaml_code/blob/master/visualise_randomness/plot_random.ml</a> has been updated for <code>png</code> support. <strong>Please remember to install libpng-devel for your OS for png saving support</strong>.</p>

<h1 id="fortunarandomgeneratorfromnocrypto">Fortuna random generator from nocrypto</h1>

<p><a href="https://twitter.com/h4nnes">@h4nnes</a> has suggested me to try the <em>fortuna generator</em> from <a href="https://github.com/mirleft/ocaml-nocrypto">nocrypto</a>.</p>

<pre><code>opam install nocrypto  
</code></pre>

<p>and</p>

<pre><code>let _ = Nocrypto_entropy_unix.initialize()  
let _ = random_plot ~filename:"random_plot_fortuna" ~ran_f:Nocrypto.Rng.Int.gen ~w:1024 ~h:1024 ~n:5  
</code></pre>

<p>and we get</p>

<p><img src="https://raw.githubusercontent.com/MassD/typeocaml_code/master/visualise_randomness/random_plot_fortuna.jpg" alt="fortuna"></p>

<p>It is a very nice generator, isn't it?</p>]]></description><link>http://typeocaml.com/2015/11/22/visualise_random/</link><guid isPermaLink="false">205d88b6-0edd-412c-9ca7-5c7ea4557c5b</guid><category><![CDATA[visualisation]]></category><category><![CDATA[random]]></category><dc:creator><![CDATA[Jackson Tale]]></dc:creator><pubDate>Sun, 22 Nov 2015 13:14:20 GMT</pubDate></item><item><title><![CDATA[Permutations]]></title><description><![CDATA[<p><img src="http://typeocaml.com/content/images/2015/05/permutation3.jpg#hero" alt="hero"></p>

<p>In this post, we will talk about producing permuations using OCaml. Generating permutations was actually one of my first self-homeworks when I started to learn OCaml years ago. It can be a good exercise to train our skills on <em>list</em>, <em>recursion</em>, foundamental <em>fold</em>, <em>map</em>, etc, in OCaml. Also it shows the conciseness of the OCaml as a language.</p>

<p>We will first present <strong>2 common approaches</strong> for generating all permutations of a list of elements. </p>

<p>Then we introduce the <a href="http://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm">Johnson Trotter algorithm</a> which enable us to generate one permutation at a time. </p>

<p>Although Johnson Trotter algorithm uses imperative array, it provides us the opportunity to implement a stream (using <a href="http://typeocaml.com/2014/11/09/magic-of-thunk-stream-list/">stream list</a> or built-in <code>Stream</code> module) of permutations, i.e., we generate a permutation only when we need. We will describe that as last.</p>

<h1 id="theinsertintoallpositionssolution">The insert-into-all-positions solution</h1>

<p>We can generate permutations using <em>recursion</em> technique. As we descriped in <a href="http://typeocaml.com/2014/12/04/recursion-reloaded/">Recursion Reloaded</a>, let's first assume we already get a function that can produce all permuations. </p>

<p><img src="http://typeocaml.com/content/images/2015/05/permutations_function0.jpg" alt="permutation_function0"></p>

<p>What exactly <code>f</code> will generate is not our concern for now, but we are sure that given a list (say 3 distinct elements), <code>f</code> will produce a list of permutations (totally 6 in this example). </p>

<p>So now what if our original list has one more new element?</p>

<p><img src="http://typeocaml.com/content/images/2015/05/permutations_function1.jpg" alt="permutation_function1"></p>

<p>What should we do to combine the new element together with the old list of permutations, in order to generate a new list of permuatations?</p>

<p>Let's first take a look at how to combine the new element with one permutation.</p>

<p><img src="http://typeocaml.com/content/images/2015/05/permutations_function2-1.jpg" alt="permutation_function2"></p>

<p>A good way, like shown above, is to insert the new element into all possible positions. Easy, right?</p>

<p>So for the new list of permutations, we just insert the new element into all possible positions of all old permutations.</p>

<p><img src="http://typeocaml.com/content/images/2015/05/permutations_function3.jpg" alt="permutation_function3"></p>

<h2 id="code">code</h2>

<p>First let's implement the function that combines an element with a permutation (which is actually a normal list).</p>

<pre><code class="ocaml">(* note that in order to preserve certain order and also show the conciseness of the implementation, no tail-recursive is used *)
let ins_all_positions x l =  
  let rec aux prev acc = function
    | [] -&gt; (prev @ [x]) :: acc |&gt; List.rev
    | hd::tl as l -&gt; aux (prev @ [hd]) ((prev @ [x] @ l) :: acc) tl
  in
  aux [] [] l
</code></pre>

<p>Now the main permutations generator.</p>

<pre><code class="ocaml">let rec permutations = function  
  | [] -&gt; []
  | x::[] -&gt; [[x]] (* we must specify this edge case *)
  | x::xs -&gt; List.fold_left (fun acc p -&gt; acc @ ins_all_positions x p ) [] (permutations xs)
</code></pre>

<p>Here is the <a href="https://gist.github.com/MassD/fa79de3a5ee88c9c5a8e">Gist</a>.</p>

<h1 id="thefixedheadsolution">The fixed-head solution</h1>

<p>There is another way to look at the permutations.</p>

<p><img src="http://typeocaml.com/content/images/2015/05/permutations_function4.jpg" alt="permutation_function4"></p>

<p>For a list of 3 elements, each element can be the head of all permutations of the rest elements. For example, <em>blue</em> is the head of the permutations of <em>green</em> and <em>yellow</em>.</p>

<p>So what we can do is</p>

<ol>
<li>Get an element out  </li>
<li>Generate all permutations on all other elements  </li>
<li>Stick the element as the head of every permutation  </li>
<li>We repeat all above until we all elements have got their chances to be heads</li>
</ol>

<p><img src="http://typeocaml.com/content/images/2015/05/permutations_function5-1.jpg" alt="permutation_function5"></p>

<h2 id="code">Code</h2>

<p>First we need a function to remove an element from a list.</p>

<pre><code class="ocaml">let rm x l = List.filter ((&lt;&gt;) x) l  
</code></pre>

<p>The <code>rm</code> above is not a must, but it will make the meaning of our following <code>permutations</code> clearer. </p>

<pre><code class="ocaml">let rec permutations = function  
  | [] -&gt; []
  | x::[] -&gt; [[x]]
  | l -&gt; 
    List.fold_left (fun acc x -&gt; acc @ List.map (fun p -&gt; x::p) (permutations (rm x l))) [] l

(* The List.fold_left makes every element have their oppotunities to be a head *)
</code></pre>

<p>Here is the <a href="https://gist.github.com/MassD/22950955c5efa8f8af88">Gist</a></p>

<h1 id="notailrecusive">No tail-recusive?</h1>

<p>So far in all our previous posts, the tail-recusive has always been considered in the codes. However, when we talk about permutations, tail-recusive has been ignored. There are two reasons:</p>

<p>At first, it is not possible to make recusion tail-recusive everywhere for the two solutions. The best we can do is just make certain parts tail-recusive.</p>

<p>Secondly, permutation generation is a <em>P</em> problem and it is slow. If one tries to generate all permutations at once for a huge list, it would not be that feasible. Thus, when talking about permutations here, it is assumed that no long list would be given as an argument; hence, we assume no stackoverflow would ever occur.</p>

<p>In addition, ignoring tail-recusive makes the code cleaner.</p>

<h1 id="whatifthelistishuge">What if the list is huge?</h1>

<p>If a list is huge indeed and we have to somehow use possibly all its permutations, then we can think of making the permutations as a <em>stream</em>. </p>

<p>Each time we just generate one permutation, and then we apply our somewhat <code>use_permuatation</code> function. If we need to continue, then we ask the stream to give us one more permutation. If we get what we want in the middle, then we don't need to generate more permutations and time is saved.</p>

<p>If we still have to go through all the permutations, time-wise the process will still cost us much. However, we are able to avoid putting all permutations in the memory or potentiall stackoverflow.</p>

<p>In order to achieve <em>a stream of permutations</em>, we need <a href="http://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm">Johnson Trotter algorithm</a> and a stream.</p>

<h1 id="johnsontrotteralgorithm">Johnson Trotter algorithm</h1>

<p>The advantage of this algorithm is its ability to generate a new permutation based on the previous one, via simple <code>O(n)</code> operations (the very first permutation is the list itself). This is ideal for our adoption of stream.</p>

<p>The disadvantage, epecially for OCaml, is that it needs an mutable array. Fortunately, we can encapsulate the array in a module or inside a function, without exposing it to the outside world. Thus, certain level of safety will be maintained. </p>

<p>Personally I think this algorithm is very clever. Johnson must have spent quit much time on observing the changes through all permutations and set a group of well defined laws to make the changes happen naturally. </p>

<h2 id="anassumptionsorted">An assumption - sorted</h2>

<p>The first assumption of this algorithm is that the array of elements are initially sorted in ascending order (<em>[1]</em>). </p>

<p>If in some context we cannot sort the original array, then we can attach additional keys, such as simple integers starting from <code>1</code>, to every element. And carry on the algorithm based on that key.</p>

<p>For example, if we have <code>[|e1; e2; e3; e4|]</code> and we do not want to sort it, then we just put an integer in front of each element like <code>[|(1, e1); (2, e2); (3, e3); (4, e4)|]</code>. All the following process can target on the key, and only when return a permutation, we output the <code>e</code> in the tuple.</p>

<p>For simplicity, we will have an example array <code>[|1; 2; 3; 4|]</code>, which is already sorted.</p>

<p><img src="http://typeocaml.com/content/images/2015/05/johnson1.jpg" alt="1"></p>

<h2 id="directionlorr">Direction: L or R</h2>

<p>The key idea behind the algorithm is to move an element (or say, switch two elements) at a time and after the switching, we get our new permutation.</p>

<p>For any element, it might be able to move either <em>Left</em> or <em>Right</em>, i.e., switch position with either <em>Left</em> neighbour or <em>Right</em> one. </p>

<blockquote>
  <p>So we will attach a <em>direction</em> - <em>L</em> (initially) or <em>R</em> - to every element.</p>
</blockquote>

<p><img src="http://typeocaml.com/content/images/2015/05/johnson2.jpg" alt="johnson2"></p>

<h2 id="movable">Movable</h2>

<p>Even if an element has a direction, it might be able to move towards that direction. Only if the element has a <strong>smaller</strong> neighbour on that direction, it can move.</p>

<p>For example,</p>

<p><img src="http://typeocaml.com/content/images/2015/05/johnson3_0-1.jpg" alt="jonhson3_0"></p>

<p><code>4</code> and <code>2</code> are movable, because the neighbours on their <em>left</em> are smaller.</p>

<p><code>3</code> is not movable, because <code>4</code> is not smaller.</p>

<p><code>1</code> is not movable, because it doesn't have any neighbour on its <em>left</em>.</p>

<h2 id="scanforlargestmovableelement">Scan for largest movable element</h2>

<p>As we described before, the algorithm makes a new permutation by moving an element, i.e., switch an element with the neighbour on its <em>direction</em>.</p>

<p>What if there are more than one elmeent is movable? We will choose the largest one.</p>

<blockquote>
  <p>Each time, when we are about to generate a new permutation, we simply scan the array, find the largest movable element, and move it.</p>
  
  <p>If we cannot find such an element, it means we have generated all possible permutations and we can end now.</p>
</blockquote>

<p>For example, </p>

<p><img src="http://typeocaml.com/content/images/2015/05/johnson4-2.jpg" alt="johnson4"></p>

<p>Although in the above case, <code>2</code>, <code>3</code> and <code>4</code> are all movable, we will move only <code>4</code> since it is largest.</p>

<p>The whole process will end if no element is movable.</p>

<p><img src="http://typeocaml.com/content/images/2015/05/johnson4_0.jpg" alt="johnson4_0"></p>

<p>Note that <strong>this scan is before the movement</strong>.</p>

<h2 id="scantoflipdirectionsoflargerelement">Scan to flip directions of larger element</h2>

<p><strong>After we make a movement</strong>, immediately we need to scan the whole array and flip the directions of elements that are larger than the element which is just moved.</p>

<p><img src="http://typeocaml.com/content/images/2015/05/johnson5.jpg" alt="johnson5"></p>

<h2 id="acompleteexample">A complete example</h2>

<p><img src="http://typeocaml.com/content/images/2015/05/johnson6.jpg" alt="johnson6"></p>

<h2 id="code">Code</h2>

<p><strong>Direction</strong></p>

<pre><code class="ocaml">type direction = L | R

let attach_direction a = Array.map (fun x -&gt; (x, L)) a
</code></pre>

<p><strong>Move</strong></p>

<pre><code class="ocaml">let swap a i j = let tmp = a.(j) in a.(j) &lt;- a.(i); a.(i) &lt;- tmp

let is_movable a i =  
  let x,d = a.(i) in
  match d with
    | L -&gt; if i &gt; 0 &amp;&amp; x &gt; (fst a.(i-1)) then true else false
    | R -&gt; if i &lt; Array.length a - 1 &amp;&amp; x &gt; (fst a.(i+1)) then true else false

let move a i =  
  let x,d = a.(i) in
  if is_movable a i then 
    match d with
      | L -&gt; swap a i (i-1)
      | R -&gt; swap a i (i+1)
  else
    failwith "not movable"
</code></pre>

<p><strong>Scan for the larget movable element</strong></p>

<pre><code class="ocaml">let scan_movable_largest a =  
  let rec aux acc i =
    if i &gt;= Array.length a then acc
    else if not (is_movable a i) then aux acc (i+1)
    else
      let x,_ = a.(i) in
      match acc with
        | None -&gt; aux (Some i) (i+1)
        | Some j -&gt; aux (if x &lt; fst(a.(j)) then acc else Some i) (i+1)
  in
  aux None 0
</code></pre>

<p><strong>Scan to flip larger</strong></p>

<pre><code class="ocaml">let flip = function | L -&gt; R | R -&gt; L

let scan_flip_larger x a =  
  Array.iteri (fun i (y, d) -&gt; if y &gt; x then a.(i) &lt;- y,flip d) a
</code></pre>

<p><strong>Permutations generator</strong></p>

<pre><code class="ocaml">let permutations_generator l =  
  let a = Array.of_list l |&gt; attach_direction in
  let r = ref (Some l) in
  let next () = 
    let p = !r in
    (match scan_movable_largest a with (* find largest movable *)
      | None -&gt; r := None (* no more permutations *)
      | Some i -&gt; 
        let x, _ = a.(i) in (
        move a i; (* move *)
        scan_flip_larger x a; (* after move, scan to flip *)
        r := Some (Array.map fst a |&gt; Array.to_list)));
    p
  in
  next

(* an example of permutation generator of [1;2;3].
   Every time called, generator() will give either next permutation or None*)
let generator = permutations_generator [1;2;3]

&gt; generator();;
&gt; Some [1; 2; 3]

&gt; generator();;
&gt; Some [1; 3; 2]

&gt; generator();;
&gt; Some [3; 1; 2]

&gt; generator();;
&gt; Some [3; 2; 1]

&gt; generator();;
&gt; Some [2; 3; 1]

&gt; generator();;
&gt; Some [2; 1; 3]

&gt; generator();;
&gt; None
</code></pre>

<p>Here is the <a href="https://gist.github.com/MassD/be3f6571967662b9d3c6">Gist</a>.</p>

<h2 id="theimperativepartinside">The imperative part inside</h2>

<p>Like said before, although we use array and <code>ref</code> for the impelmentation, we can hide them from the interface <code>permutations_generator</code>. This makes our code less fragile, which is good. However, for OCaml code having imperative parts, we should not forget to put <code>Mutex</code> locks for thread safety. </p>

<h1 id="astreamofpermutations">A stream of permutations</h1>

<p>Now it is fairly easy to produce a stream of permutations via built-in <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Stream.html">Stream</a>.</p>

<pre><code class="ocaml">let stream_of_permutations l =  
  let generator = permutations_generator l in
  Stream.from (fun _ -&gt; generator())
</code></pre>

<hr>

<p><strong>[1]</strong>. The array can be descending order, which means later on we need to put all initial directions as <em>R</em>.</p>]]></description><link>http://typeocaml.com/2015/05/05/permutation/</link><guid isPermaLink="false">ae0353b3-3eeb-451a-a560-2d6e4e9ac276</guid><dc:creator><![CDATA[Jackson Tale]]></dc:creator><pubDate>Tue, 05 May 2015 19:15:23 GMT</pubDate></item><item><title><![CDATA[Pearl No.3 - Saddleback Search]]></title><description><![CDATA[<p><img src="http://typeocaml.com/content/images/2015/03/pearl_3_easter_1-2.jpg#hero" alt=""></p>

<h1 id="happyeaster">Happy Easter</h1>

<p>Our easter egg happens to be Pearl 3.</p>

<blockquote>
  <p>A function $ f $ can have the following properties:</p>
  
  <ol>
  <li>$ f $ takes two arguments: $ x $ and $ y $</li>
  <li>Both $ x $ and $ y $ are natural numbers, i.e., non-negative integers  </li>
  <li>$ f $ also returns natural numbers  </li>
  <li>$ f $ is strictly increasing in each argument. This means if $ x $ increases or descreases, the according result of $ f $  will also increase or descrease. The same applies on $ y $.</li>
  </ol>
  
  <p>Now we are given such a function $ f $ and a natural number <code>z</code>, and we want to find out all pairs of $ x $ and $ y $ that makes $ f (x, y) = z $.</p>
  
  <p>In OCaml world, this problem requires us to write a function <code>let find_all f z = ...</code> which returns a list of <code>(x, y)</code> that satisfy <code>f x y = z</code>, assuming the supplied <code>f</code> meets the requirements above.</p>
</blockquote>

<h1 id="basicmathanalysis">Basic Math Analysis</h1>

<p>This problem seems not that difficult. A trivial brute-force solution comes out immediately. We can simply try every possible value for $ x $ and $ y $ on $ f $, and accumulate all $ (x, y) $ satisfying $ f (x, y) = z $ to the list. There is just one silly question:</p>

<blockquote>
  <p>Can we try all infinite $ x $ and $ y $?</p>
</blockquote>

<p>Of course we cannot. We should try to set a range for both $ x $ and $ y $, otherwise, our solution would run forever. Then how? From some simple math analysis, we can conclude something about $ f $, even if we won't know what $ f $ will be exactly.</p>

<p>Here are what we know so far:</p>

<ol>
<li>$ x >= 0 $  </li>
<li>$ y >= 0 $  </li>
<li>$ z >= 0 $  </li>
<li>$ x, y, z $ are all integers, which means the unit of increment or decrement is $ 1 $  </li>
<li>$ f $ goes up or down whenever $ x $ or $ y $ goes up or down.  </li>
<li>$ f (x, y) = z $</li>
</ol>

<p>From first 4 points, if we pick a value $ X $ for $ x $, we know we can descrease $ x $ from $ X $ at most $ X $ times. It is also true for $ y $ and $ z $.</p>

<p><img src="http://typeocaml.com/content/images/2015/03/x_descrease.jpg" alt="decrease_x"></p>

<p>Then let's assume $ X $ and $ Y $ makes $ f $ equal to $ Z $ ($ X, Y, Z $ are assumed to be values), i.e., </p>

<p>$$ f (X, Y) = Z $$</p>

<p>Let's now fix $ Y $ and try descreasing $ x $ to $ X-1 $. From point 5, we know </p>

<p>$$ f (X-1, Y) = Z_{X-1} &lt; f (X, Y) = Z $$</p>

<p>We can continue to decrease $ x $ until $ 0 $:</p>

<p>$$ f (0, Y) = Z_0 &lt; f (1, Y) = Z_1 &lt; ... &lt; f (X-2, Y) = Z_{X-2} &lt; f (X-1, Y) = Z_{X-1} &lt; f (X, Y) = Z $$</p>

<p>Together with point 3 ($ z >= 0 $), we can simplify the above inequalities like:</p>

<p>$$ 0 &lt;= Z_0 &lt; Z_1 &lt; ... &lt; Z_{X-2} &lt; Z_{X-1} &lt; Z $$</p>

<p>We can see that through this descreasing of $ x $, the number of results ($ Z_0, Z_1, ..., Z_{X-1} $) is $ X $. How many possible values between $ 0 $ (inclusive) and $ Z $ (exclusive)?  Of course the answer is $ Z $, right? So we can get $$ 0 &lt;= X &lt;= Z $$ and similarly, $$ 0 &lt;= Y &lt;= Z $$.</p>

<p>Thus, for any given $ x, y, z $, their relationship is</p>

<p>$$ 0 &lt;= x, y &lt;= Z $$</p>

<p>We obtained the range and now our brute-force solution will work.</p>

<h1 id="bruteforcesolution">Brute-force solution</h1>

<p>It is simple enough.</p>

<pre><code class="ocaml">let find_all_bruteforce f z =  
  let rec aux acc x y =
    if y &gt; z then aux acc (x+1) 0
    else if x &gt; z then acc
    else 
      let r = f x y in
      if r = z then aux ((x, y)::acc) x (y+1)
      else aux acc x (y+1)
  in
  aux [] 0 0
</code></pre>

<p>The time complexity is $ O(log(z^2)) $. To be exact, we need $ (z + 1)^2 $ calculation of $ f $. It will be a bit slow and we should seek for a better solution</p>

<h1 id="amatrix">A Matrix</h1>

<p>The fact that $ f $ is an increasing function on $ x $ and $ y $ has been used to retrieve the range of $ x $ and $ y $. We actually can extract more from it.</p>

<p>If we fix the somewhat value of $ y $, then increase $ x $ from $ 0 $, then the result of $ f $ will increase and naturally be sorted. If we fix $ x $, and increase $ y $ from $ 0 $, the same will happen that $ f $ will increase and be sorted. </p>

<p>We also know $ 0 &lt;= x, y &lt;= Z $; thus, we can create a matrix that has $ z + 1 $ rows and $ z + 1 $ columns. And each cell will be the result of $ f (x, y) $, where $ x $ is the row number and $ y $ is the column number.</p>

<p><img src="http://typeocaml.com/content/images/2015/03/matrix-1.jpg" alt="matrix"></p>

<p>The best thing from this matrix is that <strong>all rows are sorted and so are all columns</strong>. The reason is that $ f $ is a strictly increasing function on $ x $ and $ y $.</p>

<p><img src="http://typeocaml.com/content/images/2015/03/sorted_matrix.jpg" alt="sorted_matrix"></p>

<p>This matrix converts the original problem to the one that <strong>now we have a board of unrevealed cards and we need to seek for an efficient strategy to find all cards that we want</strong>. </p>

<p>The trivial solution in the previous section has a simplest strategy: simply reveal all cards one by one and collect all that are satisfying.</p>

<p><img src="http://typeocaml.com/content/images/2015/03/trivial.jpg" alt="trivial"></p>

<h1 id="zigzag">Zig-zag</h1>

<p>Let's take an example simple function $ f (x, y) = x * y $ and assume $ z = 6 $. </p>

<p>If we employ the trivial solution, then of course we will find all cards we want.</p>

<p><img src="http://typeocaml.com/content/images/2015/03/zig_zag_1.jpg" alt="zig_zag_1"></p>

<p>However, we can see that we need to reveal $ 36 $ cards for $ 4 $ targets. <br>
<img src="http://typeocaml.com/content/images/2015/03/zig_zag_2.jpg" alt="zig_zag_2"></p>

<p>What a waste! But how can we improve it?</p>

<blockquote>
  <p>Maybe just start from somewhere, reveal one card, depend on its value and then decide which next card to reveal?</p>
</blockquote>

<p>Let's just try starting from the most natural place - the top-left corn, where $ x = 0, y = 0 $.</p>

<p><img src="http://typeocaml.com/content/images/2015/03/zig_zag_3-2.jpg" alt="zig_zag_3"></p>

<ol>
<li>We get $ R $.  </li>
<li>If $ R > z $, our problem is solved. This is because the 3 possible next cards must be bigger than $ R $ as the bigger $ x $ or $ y $ are the larger the results are. So we do not need to move any more.  </li>
<li>What if $ R &lt; z $? then we have to try to reveal all 3 cards, which makes not much sense since we may still anyway reveal all cards.</li>
</ol>

<p>We need a better way.</p>

<h2 id="targetsumoftwosortedlists">Target sum of two sorted lists</h2>

<p>Before we continue to think, let's try another simpler problem first.</p>

<blockquote>
  <p>Given a value <code>k</code> and two sorted lists of integers (all being distinct), find all pairs of integers <code>(i, j)</code> where <code>i + j == k</code>.</p>
  
  <p>For example, <code>[1; 2; 8; 12; 20]</code> and <code>[3; 6; 9; 14; 19]</code> and <code>k = 21</code> is given, we should return <code>[(2, 19); (12, 9)]</code>.</p>
</blockquote>

<p>Of course, we can just scan all possible pairs to see. But it is not efficient and we waste the execellent hint: <em>sorted</em>. </p>

<p>Since sorted list is the fundamental condition for <em>merge</em>, how about we try to do something similar? Let's put two sorted lists in parallel and for the first two elements $ 1 $ and $ 3 $, we know $ 1 + 3 = 4 &lt; 21 $. </p>

<p><img src="http://typeocaml.com/content/images/2015/03/sorted_list_1-3.jpg" alt="1"></p>

<p>It is too small at this moment, what should we do? We know we should move rightwards to increase, but do we move along <code>list 1</code> or <code>list 2</code> or both? </p>

<p><img src="http://typeocaml.com/content/images/2015/03/sorted_list_2-2.jpg" alt="2"></p>

<p>We don't know actually, because each possible movement may give us chances to find good pairs. If we just take all possible movements, then it makes no sense as in the end as it will just try every possible pair. Hence, we just need to find a way to restrict our choices of movements.</p>

<p>How about we put one list in its natural order and put the other in its reversed order?</p>

<p><img src="http://typeocaml.com/content/images/2015/03/sorted_list_3-3.jpg" alt="3"></p>

<p>Now, $ 1 + 19 = 20 &lt; 21 $. It is again too small. What shall we do? Can we move along <code>list 2</code>? We cannot, because the next element there is definitely smaller and if we move along, we will get even smaller sum. So moving along <code>list 1</code> is our only option.</p>

<p>If <code>i + j = k</code>, then good, we collect <code>(i, j)</code>. How about the next move? We cannot just move along any single list because the future sum will forever be either bigger than <code>k</code>  or smaller. Thus, we move along both because only through increasing <code>i</code> and decreasing <code>j</code> may give us changes to find the target sum again.</p>

<p>What if <code>i + j &gt; k</code>? It is easy to see that the only option for us is the next element in <code>list 2</code>.</p>

<p><img src="http://typeocaml.com/content/images/2015/03/sorted_list_4-1.jpg" alt="4"></p>

<h2 id="oneascendingandtheotherdescendingalways">One ascending and the other descending, always</h2>

<p>Let's come back to our <em>sorted</em> matrix problem. We do not have simple two sorted lists any more, but it is not difficult to see that we should <strong>start from bottom-left corner</strong> (rows are descending and columns are ascending). And depending on what we get from $ R = f (x, y) $, we just change direction (either up, right-up or right), and towards the top-right corner:</p>

<ol>
<li>We move <em>right</em> along $ y $ until we reach the <em>ceiling</em> (the smallest number that is bigger than $ z $), and then change to <em>up</em>  </li>
<li>We move <em>up</em> along $ x $ until we reach the <em>floor</em> (the bigger number that is smaller than $ z $), and then change to <em>right</em>  </li>
<li>Whenever we reach $ R = f (x, y) = z $, we change to <em>right-up</em>.</li>
</ol>

<p>We can use an example to explain why we want the <em>ceiling</em> (similarly explaining why the <em>floor</em>).</p>

<p><img src="http://typeocaml.com/content/images/2015/03/zigzag_binarysearch_y.jpg" alt="binary_search_1"></p>

<p>When we reach the <em>ceiling</em>, we know all cells on its left can be dicarded because those are definitely smaller than $ z $.</p>

<p><img src="http://typeocaml.com/content/images/2015/03/zig_zag_4.jpg" alt="start_point"></p>

<p>In this way, the card revealing process for $ f (x, y) = x * y $ looks like this:</p>

<p><img src="http://typeocaml.com/content/images/2015/03/matrix_example.jpg" alt="example"></p>

<h2 id="code">Code</h2>

<pre><code class="ocaml">let find_all_zigzag f z =  
  let rec aux acc x y =
    if x &lt; 0 || y &gt; z then acc
    else
      let r = f x y in
      if r &lt; z then aux acc x (y+1) 
      else if r&gt; z then aux acc (x-1) y
      else aux (r::acc) (x-1) (y+1)
  in
  aux [] z 0
</code></pre>

<p>The time complexity is $ O(Z) $ and in the worst case, we need to calculate $ 2 * Z + 1 $ times of $ f $.</p>

<p>This solution is a linear one and there is still room for improvement.</p>

<h2 id="asameproblemwithslightlydifferentappearance">A same problem with slightly different appearance</h2>

<p>There is a quite popular interview question which is very similar to the pearl 3.</p>

<blockquote>
  <p>We have a matrix of numbers. All rows are sorted and so are all columns. Find the coordinates of a given number.</p>
</blockquote>

<p>Although it seems all numbers are already computed and put in the matrix, both this problem and pearl 3 are actually identical.</p>

<h1 id="zigzagbinarysearch">Zig-zag + Binary Search</h1>

<p>Zig-zag solution is actually scan along $ x $ axis and $ y $ axis by turns. The scan on each turn is linear. But wait, each row and column are sorted, right? Does it ring a bell?</p>

<p>When a sequence of elements are sorted, and if we have a target to find, then we of course can try <em>binary search</em>.</p>

<p>Simply say, in order to improve the <em>zig-zag</em> solution, we just replace the <em>linear scan</em> part with <em>binary search</em>. </p>

<h2 id="targetsofbinarysearch">Targets of binary search</h2>

<p>For each round of binary search, we cannot just search for the given value of $ z $ only. Instead, </p>

<ol>
<li>Our target is the <strong>ceiling</strong> when we binary search <strong>horizontally</strong>, i.e., along $ y $, from left to right.  </li>
<li>Our target is the <strong>floor</strong> when we binary search <strong>vertically</strong>, i.e., along $ x $, from down to up.  </li>
<li>During our search, if we find a target card, we can simply stop.</li>
</ol>

<h2 id="eventuallystopsatceilingorfloororequal">Eventually stops at ceiling or floor or equal</h2>

<p>The next question is <em>when a round of binary search stops?</em></p>

<p>When we reach an card equal to $ z $, of course we can stop immediately.</p>

<p>If we never reach an ideal card, then anyway the search will stop because there will eventually be no room on either left side or right side to continue. And that stop point will definitely be the <em>ceiling</em> or the <em>floor</em> of $ z $. </p>

<p>Again, because we need the <em>ceiling</em> for <em>horizon</em> and <em>floor</em> for <em>vertical</em>, we need to adjust it after we finish the binary search.</p>

<h2 id="code">Code</h2>

<pre><code class="ocaml">type direction = H | V

let rec binary_search z g p q =  
  if p + 1 &gt;= q then p
  else
    let m = (p + q) / 2 in
    let r = g m in
    if r = z then m
    else if r &gt; z then binary_search z g p (m-1)
    else binary_search z g (m+1) q

(* adjust ceiling or floor *)
let next_xy z f x y direction =  
  let r = f x y in
  match direction with
    | _ when r = z -&gt; x, y
    | H when r &gt; z -&gt; x-1, y
    | H -&gt; x-1, y+1
    | V when r &lt; z -&gt; x, y+1
    | V -&gt; x-1, y+1

let find_all_zigzag_bs f z =  
  let rec aux acc (x, y) =
    if x &lt; 0 || y &gt; z then acc
    else 
      let r = f x y in
      if r = z then aux (f x y::acc) (x-1, y+1)
      else if r &lt; z then 
        let k = binary_search z (fun m -&gt; f x m) y z in
        aux acc (next_xy z f x k H)
      else
        let k = binary_search z (fun m -&gt; f m y) 0 x in
        aux acc (next_xy z f k y V)
  in
  aux [] (z, 0)
</code></pre>

<h1 id="whycalledsaddleback">Why called Saddleback</h1>

<p>The reason why this pearl is called <em>Saddleback Search</em> is (quoted from the <a href="http://www.amazon.co.uk/Pearls-Functional-Algorithm-Design-Richard/dp/0521513383/ref=sr_1_1?ie=UTF8&amp;qid=1427413337&amp;sr=8-1&amp;keywords=pearls+functional">book</a>), </p>

<blockquote>
  <p>(It is) an important search strategy, dubbed saddleback search by David Gries... </p>
  
  <p>I imagine Gries called it that because the shape of the three-dimensional plot of f , with the smallest element at the bottom left, the largest at the top right and two wings, is a bit like a saddle.</p>
</blockquote>

<p>For example, if we plot $ f (x, y) = x * y $ , we can see <a href="http://www.livephysics.com/tools/mathematical-tools/online-3-d-function-grapher/?xmin=-1&amp;xmax=1&amp;ymin=-1&amp;ymax=1&amp;zmin=Auto&amp;zmax=Auto&amp;f=x*y">this</a></p>

<p><img src="http://typeocaml.com/content/images/2015/03/plot.jpg" alt="plot"></p>

<p>Does it look like a saddle?</p>]]></description><link>http://typeocaml.com/2015/03/31/pearl-no-3-saddleback-search/</link><guid isPermaLink="false">6f0c2ee7-c112-4a61-8af5-1f8622e303d5</guid><dc:creator><![CDATA[Jackson Tale]]></dc:creator><pubDate>Tue, 31 Mar 2015 17:30:00 GMT</pubDate></item><item><title><![CDATA[Binomial Heap]]></title><description><![CDATA[<p><img src="http://typeocaml.com/content/images/2015/03/binomial_heap.jpg#hero" alt=""></p>

<p>As we described in the previous post, leftist tree is a binary tree based functional heap. It manipulates the tree structure so that the left branches are always the longest and operations follow the right branches only. It is a clever and simple data structure that fulfills the purpose of heap. </p>

<p>In this post, we present another functional heap called <a href="http://en.wikipedia.org/wiki/Binomial_heap">Binomial Heap</a> (<em>[1]</em>). Instead of being a single tree strucutre, it is a list of <em>binomial tree</em>s and it provides better performance than leftist tree on <em>insert</em>. </p>

<p>However, the reason I would like to talk about it here is not because of its efficiency. The fascination of binomial heap is that <strong>if there are N elements inside it, then it will have a determined shape, no matter how it ended up with the N elements</strong>. Personally I find this pretty cool. This is not common in tree related data structures. For example, we can not predict the shape of a leftist tree with N elements and the form of a binary search tree can be arbitrary even if it is somehow balanced. </p>

<p>Let's have a close look at it.</p>

<h1 id="binomialtree">Binomial Tree</h1>

<p>Binomial tree is the essential element of binomial heap. Its special structure is why binomial heap exists. Understanding binomial tree makes it easier to understand binomial heap.</p>

<p>Binomial tree's definition does not involve the values associated with the nodes, but just the structure:</p>

<ol>
<li>It has a rank <em>r</em> and <em>r</em> is a natural number.  </li>
<li>Its form is <em>a root node</em> with <em>a list of binomial trees</em>, whose ranks are strictly <em>r-1</em>, <em>r-2</em>, ..., <em>0</em>.  </li>
<li>A binomial tree with rank <em>0</em> has only one root, with an empty list.</li>
</ol>

<p>Let's try producing some examples.</p>

<p>From point 3, we know the base case:</p>

<p><img src="http://typeocaml.com/content/images/2015/03/rank_0.jpg" alt="rank_0"></p>

<p>Now, how about <em>rank 1</em>? It should be a root node with a sub binomial tree with rank <code>1 - 1 = 0</code>:</p>

<p><img src="http://typeocaml.com/content/images/2015/03/rank_1-1.jpg" alt="rank_1"></p>

<p>Let's continue for <em>rank 2</em>, which should have <em>rank 1</em> and <em>rank 0</em>:</p>

<p><img src="http://typeocaml.com/content/images/2015/03/rank_2.jpg" alt="rank_2"></p>

<p>Finally <em>rank 3</em>, can you draw it?</p>

<p><img src="http://typeocaml.com/content/images/2015/03/rank_3.jpg" alt="rank_3"></p>

<h2 id="d2rdnodes">$ 2^r $ nodes</h2>

<p>If we pull up the left most child of the root, we can see:</p>

<p><img src="http://typeocaml.com/content/images/2015/03/r_2_r-1-3.jpg" alt="r_2_r-1"></p>

<p>This means a binomial tree with rank <em>r</em> can be seen as <em>two</em> binomial trees with the same rank <em>r-1</em>. Furthermore, because that <em>two</em>, and rank <em>0</em> has one node, then in term of the number of nodes, for a binomial tree with <strong>rank <em>r</em>, it must have $ 2^r $ nodes, no more, no less</strong>.</p>

<p>For example, rank <em>0</em> has 1 node. Rank <em>1</em> is 2 <em>rank 0</em>, so rank <em>1</em> has $ 2 * 1 = 2 $ nodes, right? Rank <em>2</em> then has $ 2 * 2 = 4 $ nodes, and so on so forth.</p>

<p>Note that $ 2^r = 1 + 2^r-1 + 2^r-2 + ... + 2^0 $ and we can see that a rank <em>r</em> tree's structure fits exactly to this equation (the <em>1</em> is the root and the rest is the children list). </p>

<h2 id="twor1isthewaytober">Two <em>r-1</em> is the way to be <em>r</em></h2>

<p>The definition tells us that a rank <em>r</em> tree is a root plus a list of trees of rank <em>r-1</em>, <em>r-2</em>, ..., and <em>0</em>. So if we have a binomial tree with an arbitrary rank, can we just insert it to another target tree to form a rank <em>r</em> tree?</p>

<p>For example, suppose we have a rank <em>1</em> tree, can we insert it to the target tree below for a rank <em>3</em> tree?</p>

<p><img src="http://typeocaml.com/content/images/2015/03/wrong_way.jpg" alt="wrong"></p>

<p>Unfortunately we cannot, because the target tree won't be able to exist in the first place and it is not a valid binomial tree, is it?</p>

<p>Thus in order to have a rank <em>r</em> tree, we must have two <em>r-1</em> trees and link them together. When linking, we need to decide which tree is the new root, depending on the context. For the purpose of building a <em>min heap</em> later, we assume we always let the root with the <em>smaller</em> key be the root of the new tree.</p>

<h2 id="code">code</h2>

<p>Defining a binomial tree type is easy:</p>

<pre><code class="ocaml">(* Node of key * child_list * rank *)
type 'a binomial_t = Node of 'a * 'a binomial_t list * int  
</code></pre>

<p>Also we can have a function for a singleton tree with rank <em>0</em>:</p>

<pre><code class="ocaml">let singleton_tree k = Node (k, [], 0)  
</code></pre>

<p>Then we must have <code>link</code> function which promote two trees with same ranks to a higher rank tree.</p>

<pre><code class="ocaml">let link ((Node (k1, c1, r1)) as t1) ((Node (k2, c2, r2)) as t2) =  
  if r1 &lt;&gt; r2 then failwith "Cannot link two binomial trees with different ranks"
  else if k1 &lt; k2 then Node (k1, t2::c1, r1+1)
  else Node (k2, t1::c2, r2+1)
</code></pre>

<p>One possibly interesting problem can be:</p>

<blockquote>
  <p>Given a list of $ 2^r $ elements, how to construct a binomial tree with rank <em>r</em>?</p>
</blockquote>

<p>We can borrow the idea of <em>merging from bottom to top</em> for this problem.</p>

<p><img src="http://typeocaml.com/content/images/2015/03/from_list_2-1.jpg" alt="from_list"></p>

<pre><code class="ocaml">let link_pair l =  
  let rec aux acc = function
    | [] -&gt; acc
    | _::[] -&gt; failwith "the number of elements must be 2^r"
    | t1::t2::tl -&gt; aux (link t1 t2 :: acc) tl
  in
  aux [] l

let to_binomial_tree l =  
  let singletons = List.map singleton_tree l in
  let rec aux = function
    | [] -&gt; failwith "Empty list"
    | t::[] -&gt; t
    | l -&gt; aux (link_pair l)
  in
  aux singletons
</code></pre>

<h2 id="binomialcoefficient">Binomial coefficient</h2>

<p>If we split a binomial tree into levels and pay attention to the number of nodes on each level, we can see:</p>

<p><img src="http://typeocaml.com/content/images/2015/03/binomial_coefficiency.jpg" alt="binomial coefficient"></p>

<p>So from top to bottom, the numbers of nodes on levels are <em>1</em>, <em>3</em>, <em>3</em> and <em>1</em>. It happens to be the coefficients of $ (x+y)^3 $ .</p>

<p>Let's try rank <em>4</em>:</p>

<p><img src="http://typeocaml.com/content/images/2015/03/binomial_coefficiency_2.jpg" alt="binomial_coefficient_2"></p>

<p>They are <em>1</em>, <em>4</em>, <em>6</em>, <em>4</em> and <em>1</em>, which are the coefficients of $ (x+y)^4 $ .</p>

<p>The number of nodes on level <em>k</em> ( 0 &lt;= <em>k</em> &lt;= <em>r</em>) matches $ {r}\choose{k} $, which in turn matches <strong>the kth binomial coefficient of $ (x+y)^r $. This is how the name <em>binomial</em> tree came from</strong>.</p>

<h1 id="binomialheap">Binomial Heap</h1>

<p>A binomial heap is essentially a list of binomial trees with distinct ranks. It has two characteristics:</p>

<ol>
<li>If a binomial heap has <em>n</em> nodes, then its shape is determined, no matter what operations have been gone through it.  </li>
<li>If a binomial heap has <em>n</em> nodes, then the number of trees inside is <code>O(logn)</code>.</li>
</ol>

<p>The reason for the above points is explained as follows.</p>

<p>As we already knew, a binomial tree with rank <em>r</em> has $ 2^r $ nodes. If we move to the context of binary presentation of numbers, then a rank <em>r</em> tree stands for the case where there is a list of bits with only the <em>rth</em> slot turned on.</p>

<p><img src="http://typeocaml.com/content/images/2015/03/binary.jpg" alt="binary"></p>

<p>Thus, for <em>n</em> number of nodes, it can be expressed as a list of binomial trees with distinct ranks, because the number <em>n</em> is actually a list of bits with various slots being <em>1</em>. For example, suppose we have 5 nodes (ignoring their values for now), mapping to a list of binomial trees, we will have:</p>

<p><img src="http://typeocaml.com/content/images/2015/03/binomial_heap_origin-2.jpg" alt="origin"></p>

<p>This is where binomial heap comes from. </p>

<ol>
<li>Since a number <em>n</em> has determined binary presentation, a binomial heap also has fixed shape as long as it has <em>n</em> nodes.  </li>
<li>In addition, because <em>n</em> has <code>O(logn)</code> effective bits, a binomial heap has <code>O(logn)</code> binomial trees.  </li>
<li>If we keep each binomial tree having the min as the root, then for a binomial heap, the overall minimum elements is on of those roots.</li>
</ol>

<p>Let's now implement it.</p>

<h2 id="typeandsingleton">Type and singleton</h2>

<p>It is easy.</p>

<pre><code class="ocaml">type 'a binomial_heap_t = 'a binomial_t list
</code></pre>

<h2 id="insert">insert</h2>

<p>When we <em>insert</em> a key <code>k</code>, we just create a singleton binomial tree and try to insert the tree to the heap list. The rule is like this:</p>

<ol>
<li>If the heap doesn't have a rank <em>0</em> tree, then directly insert the new singleton tree (with rank <em>0</em>) to the head of the list.  </li>
<li>If the heap has a rank <em>0</em> tree, then the two rank <em>0</em> tree need to be linked and promoted to a new rank <em>1</em> tree. And we have to continue to try to insert the rank <em>1</em> tree with the rest of the list that potentiall starts with a existing rank <em>1</em> tree.  </li>
<li>If there is already a rank <em>1</em> tree, then link and promot to rank <em>2</em>... so on so forth, until the newly promoted tree has a slot to fit in.</li>
</ol>

<p>Here are two examples:</p>

<p><img src="http://typeocaml.com/content/images/2015/03/insert.jpg" alt="insert_1"></p>

<p><img src="http://typeocaml.com/content/images/2015/03/insert_2.jpg" alt="insert_2"></p>

<p>The <em>insert</em> operation is actually the addition between <em>1</em> and <em>n</em> in binary presentation, in a revered order. </p>

<pre><code class="ocaml">let insert k h =  
  let rec aux acc (Node (_, _, r1) as bt1) = function
    | [] -&gt; List.rev (bt1::acc)
    | (Node (_, _, r2) as bt2)::tl -&gt;
      if r1 = r2 then aux acc (link bt1 bt2) tl
      else if r1 &lt; r2 then List.rev_append acc (bt1::bt2::tl)
      else aux (bt2::acc) bt1 tl
  in
  aux [] (singleton_tree k) h
</code></pre>

<p>If the heap is full as having a consecutive series of ranks of trees starting from rank <em>0</em>, we need <code>O(logn)</code> operations to finish the <em>insert</em>. However, once it is done, most of the lower rank slots are empty (like shown in the above figure). And for later new <em>insert</em>, it won't need <code>O(logn)</code> any more. Thus, The time complexity of <em>insert</em> seems to be <code>O(logn)</code>, but <strong>actually amortised <code>O(1)</code></strong>.</p>

<p>Note the above <em>insert</em> description is just for demonstration purpose. Like in <a href="http://typeocaml.com/2015/03/12/heap-leftist-tree/">Leftist tree</a>, <em>merge</em> is the most important operation for binomial heap and <em>insert</em> is just a simpler <em>merge</em>. </p>

<h2 id="merge">merge</h2>

<p>The <em>merge</em> is like this:</p>

<ol>
<li>Get the two heads (<code>bt1</code> and <code>bt2</code>) out of two heaps (<code>h1</code> and <code>h2</code>).  </li>
<li>If <code>rank bt1 &lt; rank bt2</code>, then <code>bt1</code> leaves first and continue to merge <code>the rest of h1</code> and <code>h2</code>.  </li>
<li>If <code>rank bt1 &gt; rank bt2</code>, then <code>bt2</code> leaves first and continue to merge <code>h1</code> and <code>the rest of h2</code>.  </li>
<li>If <code>rank bt1 = rank bt2</code>, then <code>link bt1 bt2</code>, add the new tree to <code>the rest of h1</code> and merge the new <code>h1</code> and <code>the rest of h2</code>.</li>
</ol>

<p>I will skip the digram and directly present the code here:</p>

<pre><code class="ocaml">let rec merge h1 h2 =  
  match h1, h2 with
  | h, [] | [], h -&gt; h
  | (Node (_, _, r1) as bt1)::tl1, (Node (_, _, r2) as bt2)::tl2 -&gt;
    if r1 &lt; r2 then bt1::merge tl1 h2
    else if r1 &gt; r2 then bt2::merge h1 tl2
    else merge (link bt1 bt2::tl1) tl2

(* a better and simpler version of insert *)
let insert' k h = merge [singleton_tree k] h  
</code></pre>

<p>The time complexity is <code>O(logn)</code>.</p>

<h2 id="get_min">get_min</h2>

<p>We just need to scan all roots and get the min key.</p>

<pre><code class="ocaml">let get_min = function  
  | [] -&gt; failwith "Empty heap"
  | Node (k1, _, _)::tl -&gt;
    List.fold_left (fun acc (Node (k, _, _)) -&gt; min acc k) k1 tl
</code></pre>

<blockquote>
  <p>For achieve <code>O(1)</code>, we can attach a <code>minimum</code> property to the heap's type. It will always record the min and can be returned immediately if requested. However, we need to update this property when <em>insert</em>, <em>merge</em> and <em>delete_min</em>. Like every other book does, this modification is left to the readers as an exercise.</p>
</blockquote>

<h2 id="delete_min">delete_min</h2>

<p><em>delete_min</em> appears as a little bit troublesome but actually very neat. </p>

<ol>
<li>We need to locate the binomial tree with <em>min</em>.  </li>
<li>Then we need to merge <code>the trees on its left</code> and <code>the trees on its right</code> to get a new list.  </li>
<li>It is not done yet as we need to deal with the <em>min</em> binomial tree.  </li>
<li>We are lucky that <strong>a binomial tree's child list is a heap indeed</strong>. So we just need to merge <code>the child list</code> with the new list from point 2.</li>
</ol>

<pre><code class="ocaml">let key (Node (k, _, _)) = k  
let child_list (Node (_, c, _)) = c

let split_by_min h =  
  let rec aux pre (a, m, b) = function
    | [] -&gt; List.rev a, m, b
    | x::tl -&gt;
      if key x &lt; key m then aux (x::pre) (pre, x, tl) tl
      else aux (x::pre) (a, m, b) tl
  in
  match h with 
    | [] -&gt; failwith "Empty heap"
    | bt::tl -&gt; aux [bt] ([], bt, []) tl

let delete_min h =  
  let a, m, b = split_by_min h in
  merge (merge a b) (child_list m |&gt; List.rev)
</code></pre>

<h1 id="binomialheapvsleftisttree">Binomial Heap vs Leftist Tree</h1>

<pre>
|               | get_min                                 | insert         | merge   | delete_min |
|---------------|-----------------------------------------|----------------|---------|------------|
| Leftist tree  | O(1)                                    | O(logn)        | O(logn) | O(logn)    |
| Binomial heap | O(logn), but can be improved to be O(1) | Amortised O(1) | O(logn) | O(logn)    |

</pre>

<hr>

<p><strong>[1]</strong> Binomial Heap is also introduced in <a href="http://www.amazon.co.uk/Purely-Functional-Structures-Chris-Okasaki/dp/0521663504/ref=sr_1_1?ie=UTF8&amp;qid=1426283477&amp;sr=8-1&amp;keywords=functional+data+structure">Purely Functional Data Structures</a>.</p>]]></description><link>http://typeocaml.com/2015/03/17/binomial-heap/</link><guid isPermaLink="false">2c8b51b1-2b0a-4379-b99c-3512b2b189a9</guid><category><![CDATA[heap]]></category><category><![CDATA[binomial heap]]></category><dc:creator><![CDATA[Jackson Tale]]></dc:creator><pubDate>Wed, 18 Mar 2015 00:07:39 GMT</pubDate></item><item><title><![CDATA[Heap - Leftist Tree]]></title><description><![CDATA[<p><img src="http://typeocaml.com/content/images/2015/03/leftist.jpg#hero" alt="leftist"></p>

<p><a href="https://en.wikipedia.org/wiki/Heap_(data_structure)">Heap</a> is one of most important data structure, where the minimum of all elements can always be easily and efficiently retrieved. </p>

<h1 id="binaryheap">Binary Heap</h1>

<p>In imperative world, <a href="https://en.wikipedia.org/wiki/Binary_heap">binary heap</a> (implemented via <em>array</em>) is frequently used. Here is an example:</p>

<p><img src="http://typeocaml.com/content/images/2015/03/binary_heap-2.jpg" alt="binary_heap"></p>

<p>The (min) heap on the right hand side is a full binary tree indeed. The root is always the min and recursively, a root (of any sub tree) is always smaller than its two children. Note that <strong>we just need to keep partial order for heap</strong>, not total order like binary search tree. For example, <code>1</code> needs to be smaller than its two children, but the relationship between the two children does not matter. Thus, the left child and right child can be either <code>10</code> and <code>3</code> or <code>3</code> and <code>10</code>. Moreover, the big node <code>17</code> can be in the right branch of <code>1</code> while its parent <code>3</code> is smaller than <code>10</code>. </p>

<p>The array based implementation is actually beautiful. Essentially, it uses two tricks to simulate the binary heap tree:</p>

<ol>
<li>If the index of a root is <code>i</code>, then its left child index is <code>2*i+1</code> and right child index is <code>2*i+2</code>.  </li>
<li>The relationship of left child and right child is not important, so the two child slots in the array for a root can be fully used. (<em>Can we use array to implement a binary search tree?</em>)</li>
</ol>

<p>The time complexities on operations are:</p>

<ol>
<li><em>get_min</em>: <code>O(1)</code>  </li>
<li><em>insert</em>: <code>O(logn)</code>  </li>
<li><em>delete_min</em>: <code>O(logn)</code>  </li>
<li><em>merge</em>: <code>O(n)</code></li>
</ol>

<p>Although its <code>merge</code> is not satisfying, this data structure is adorable and gives us the most compact space usage on array. </p>

<p>However, unfortunately we cannot have it in pure functional world where mutable array is not recommended. </p>

<h1 id="listbasedheap">List based heap</h1>

<p>I would like to first explore two possible functional approaches for heap (the list based in this section and the direct binary tree based in next section) . They are trivial or even incomplete, but the ideas behind may lead to the invention of leftist tree. </p>

<p>List is basically the replacement of array in functional world and of course, we can use it for heap. The idea is simple:</p>

<ol>
<li>When <em>insert</em> <code>x</code>, linearly compare <code>x</code> with all existing elements one by one and insert it to the appropriate place where the element on its left hand side is smaller and the element on its right is equal or bigger.  </li>
<li>When <em>get_min</em>, it is as simple as returning the head.  </li>
<li>When <em>delete_min</em>, remove the head.  </li>
<li>When <em>merge</em>, do a standard <em>merge</em> like in <em>mergesort</em>.</li>
</ol>

<p>The time complexities are:</p>

<ol>
<li><em>get_min</em>: <code>O(1)</code>  </li>
<li><em>insert</em>: <code>O(n)</code>  </li>
<li><em>delete_min</em>: <code>O(1)</code>  </li>
<li><em>merge</em>: <code>O(n)</code></li>
</ol>

<p><img src="http://typeocaml.com/content/images/2015/03/list_based-2.jpg" alt="list_based"></p>

<p>We can see that in this design, the list is fully sorted all the time. And also it is a tree, with just one branch always. </p>

<p>Of course, the performance of <em>insert</em> and <em>merge</em> is <code>O(n)</code> which is unacceptable. This is due to the adoption of just one leg which is crowded with elements and all elements have to be in their natural order to fit in (remember a parent must be smaller than its kid(s)?). Eventually the fact of <em>total order is not necessary</em> is not leveraged at all. </p>

<p>Hence, we need <strong>at least two branches</strong> so that we may be able to spread some elements into different branches and the comparisons of the children of a root may be avoided. </p>

<h1 id="binaryheapnotusingarray">Binary Heap not using array</h1>

<p>Since the array based binary heap is a binary tree, how about implementing it directly in a binary tree form?</p>

<p>We can define a binary tree heap like this:</p>

<pre><code class="ocaml">type 'a bt_heap_t =  
  | Leaf
  | Node of 'a * 'a bt_heap_t * 'a bt_heap_t
</code></pre>

<p>The creation of the type is easy, but it is hard to implement those operations. Let's take <em>insert</em> as an example.</p>

<p><img src="http://typeocaml.com/content/images/2015/03/binary_tree_heap.jpg" alt="insert"></p>

<p>The <em>attempt 1</em> in the diagram above illustrates the idea behind the array based binary heap. When we insert an element, ideally we should put it in the last available place at the bottom level or the first place at a brand new level if already full, then we do a <em>pull up</em> by comparing and swapping with parents one by one. Obviously, we cannot do it in a pure tree structure since it is not efficient to find the initial place.</p>

<p>So let's try <em>attempt 2</em> by directly try to insert from top to bottom. So in the example, <code>2 &lt; 6</code> so <code>2</code> stays and <code>6</code> should continue going down. However, the question now is <strong>which branch it should take?</strong> <code>10</code> or <code>3</code>? This is not trivial to decide and we have to find a good rule.  </p>

<p>We will also have problem in <em>delete_min</em>.</p>

<p><img src="http://typeocaml.com/content/images/2015/03/binary_tree_heap_delete.jpg" alt="delete_min"></p>

<p>If we delete the root (min), then we will have two binary trees. Then the question is how to merge them? Do we just take all elements of one of the trees, and insert every element into the other tree? Will this way be efficient even if we are able to design a good <em>insert</em>? </p>

<p>If we consider <em>insert</em> as <em>merge</em> with a single node tree, then the problem of <em>insert</em> becomes the problem of <em>merge</em>, just like <em>delete_min</em>. <strong>Should we design a good <em>merge</em> so that both <em>insert</em> and <em>delete_min</em> are naturally solved</strong>?</p>

<p>Bear all those questions in mind, and now we can start look at leftist tree.</p>

<h1 id="leftisttree">Leftist Tree</h1>

<p>The concerns in answering those questions in the previous section are majorly about the performance. We are dealing with a tree. How the tree getting structure or transformed along the time is very important and it affects the performance a lot.</p>

<p>For example, for the question of <em>which branch to take when inserting</em>, if we just always go left, then the left branch will be longer and longer if we insert lots of elements, and the time complexity becomes <code>O(n)</code>.</p>

<p>Also when merging, the two trees are already heaps, i.e., the elements and structure of either tree obeys the principle that a parent must be smaller than its children. Why do we need to destory one tree completely? Why not try to keep the structures of two trees untouched as much as possible? If we can somehow attach a root from one tree directly under a root of another tree, then all children under the first root can stay still and no operations are necessary for them. </p>

<p>Let's see how leftist tree is designed to make sure the good performance.</p>

<h2 id="leftalwayslonger">Left always longer</h2>

<p>Leftist tree always keeps the left branches of all roots being the longer and in worst case, they are as long as the right branches. In other word, all right branches of all roots are shortest. This makes sense. When we decide which branch to go, if we know one branch is always shorter than the other, then we should take it. This is because shorter branch means potentially less nodes and the number of future possible operations intends to be smaller. </p>

<p>In order to maintain this property, each node has a <strong>rank</strong>, which indidates <strong>the length of the path between the node and the right most leaf</strong>. For example, </p>

<p><img src="http://typeocaml.com/content/images/2015/03/leftist_rank.jpg" alt="rank"></p>

<p>The way of keep ranks up-to-date is like this:</p>

<ol>
<li>We always assume <code>the rank of the right child &lt;= the rank of the left child</code>.  </li>
<li>So we always go right.  </li>
<li>If we reach a leaf, then we replace the leaf with our <em>element</em> and update the ranks of all the parents back to the root. Note that the <em>element</em> in this context is not necessarily the original new element which is being inserted and we will explain it soon.  </li>
<li>When updating the rank of a parent, we first compare the rank of left <code>rank_left</code> and the rank of right <code>rank_right</code>. If <code>rank_left &lt; rank_right</code>, then we swap the left child and the right child and update the rank of the parent to be <code>rank_left + 1</code>; other wise <code>rank_right + 1</code> </li>
</ol>

<p>A diagram is better than hundreds of words. Let's build a leftist by inserting two elements.</p>

<h2 id="insert">Insert</h2>

<p><img src="http://typeocaml.com/content/images/2015/03/leftist_insert-2.jpg" alt="insert"></p>

<p>We can see that by always putting the higher rank to the left can make the right branch being shortest all the time. Actually, this strategy is how this design of tree based heap got the name <em>leftist</em>, i.e., more nodes intend to be on the left side. </p>

<p>But this is not the full story of leftist. Actually, although the diagram above describes <em>insert</em>, it is just for the purpose of demonstration of how ranks are updated. </p>

<p>In leftist tree, the most important operation is <em>merge</em> and an <em>insert</em> is just a <em>merge</em> with a singleton tree that has only the new element and two leaves.</p>

<h2 id="merge">Merge</h2>

<p><em>Merge</em> is a recursive operation.</p>

<ol>
<li>We have two trees to merge: <code>merge t1 t2</code>.  </li>
<li>Compare two roots, if <code>k1 &gt; k2</code>, we simply switch two trees by <code>merge t2 t1</code>. This is to make sure the tree on the left always has smaller key, for conveniences.  </li>
<li>Since <code>t1</code> has smaller key, its root should stay as the new root.  </li>
<li>Because <code>t1</code>'s right branch <code>r</code> is always shortest, we then do <code>merge r t2</code>.  </li>
<li>If one of the two trees is leaf, we simply returns the other. And begin the rank updating process back to the root.  </li>
<li>The rank updating is the same as we described in the previous section.</li>
</ol>

<p>Again, let's see an example.</p>

<p><img src="http://typeocaml.com/content/images/2015/03/leftist_merge.jpg" alt="merge"></p>

<h2 id="code">Code</h2>

<p><strong>type</strong></p>

<pre><code class="ocaml">type 'a leftist =  
  | Leaf 
  | Node of 'a leftist * 'a * 'a leftist * int
</code></pre>

<p><strong>essentials</strong></p>

<pre><code class="ocaml">let singleton k = Node (Leaf, k, Leaf, 1)

let rank = function Leaf -&gt; 0 | Node (_,_,_,r) -&gt; r  
</code></pre>

<p><strong>merge</strong></p>

<pre><code class="ocaml">let rec merge t1 t2 =  
  match t1,t2 with
    | Leaf, t | t, Leaf -&gt; t
    | Node (l, k1, r, _), Node (_, k2, _, _) -&gt;
      if k1 &gt; k2 then merge t2 t1 (* switch merge if necessary *)
      else 
        let merged = merge r t2 in (* always merge with right *)
        let rank_left = rank l and rank_right = rank merged in
        if rank_left &gt;= rank_right then Node (l, k1, merged, rank_right+1)
        else Node (merged, k1, l, rank_left+1) (* left becomes right due to being shorter *)
</code></pre>

<p><strong>insert, get_min, delete_min</strong></p>

<pre><code class="ocaml">let insert x t = merge (singleton x) t

let get_min = function  
  | Leaf -&gt; failwith "empty"
  | Node (_, k, _, _) -&gt; k

let delete_min = function  
  | Leaf -&gt; failwith "empty"
  | Node (l, _, r, _) -&gt; merge l r
</code></pre>

<h2 id="timecomplexity">Time complexity</h2>

<ol>
<li><em>get_min</em>: <code>O(1)</code>  </li>
<li><em>insert</em>: <code>O(logn)</code>  </li>
<li><em>delete_min</em>: <code>O(logn)</code>  </li>
<li><em>merge</em>: <code>O(logn)</code></li>
</ol>

<p>Leftist tree's performance is quite good. Comparing to the array based binary heap, it has a much better <em>merge</em>. Moreover, its design and implementation are simple enough. Thus, leftist tree can an excellent choice for heap in the functional world.</p>]]></description><link>http://typeocaml.com/2015/03/12/heap-leftist-tree/</link><guid isPermaLink="false">3e0ab087-faab-4bb5-9b79-9114fca51472</guid><category><![CDATA[heap]]></category><category><![CDATA[leftist tree]]></category><dc:creator><![CDATA[Jackson Tale]]></dc:creator><pubDate>Fri, 13 Mar 2015 02:04:57 GMT</pubDate></item><item><title><![CDATA[Pearl No.2 - The Max Number of Surpassers]]></title><description><![CDATA[<p><img src="http://typeocaml.com/content/images/2015/02/pear-2.jpg#hero" alt="pear-2"></p>

<blockquote>
  <p>In a list of unsorted numbers (not necessarily distinct), such as</p>
</blockquote>

<p><img src="http://typeocaml.com/content/images/2015/02/problem_description_1-1.jpg" alt="problem1"></p>

<blockquote>
  <p>The surpassers of an element are all elements whose indices are bigger and values are larger. For example, the element <code>1</code>'s surpassers are <code>9</code>, <code>5</code>, <code>5</code>, and <code>6</code>, so its number of surpassers is 4. </p>
</blockquote>

<p><img src="http://typeocaml.com/content/images/2015/02/problem_description_2.jpg" alt="problem2"></p>

<blockquote>
  <p>And also we can see that <code>9</code> doesn't have any surpassers so its number of surpassers is 0. </p>
  
  <p>So the problem of this pearl is:</p>
  
  <p><strong>Given an unsorted list of numbers, find the max number of surpassers, O(nlogn) is required.</strong></p>
  
  <p>In the answer for the above example is 5, for the element <code>-10</code>. </p>
</blockquote>

<h1 id="aneasybutnotoptimalsolution">An easy but not optimal solution</h1>

<p>As usual, let's put a trivial solution on the table first (<em>[1]</em>). It is straightforward:</p>

<ol>
<li>For every element, we scan all elements behind it and maintain a <code>ns</code> as its number of surpassers.  </li>
<li>If one element is larger, then we increase the <code>ns</code>.  </li>
<li>After we finish on all elements, the <code>max</code> of all the <code>ns</code>es is what we are looking for.</li>
</ol>

<p>The diagram below demonstrates the process on <code>1</code>. <br>
<img src="http://typeocaml.com/content/images/2015/02/trivial_solution-2.jpg" alt="trivial solution"></p>

<pre><code class="ocaml">let num_surpasser p l = List.fold_left (fun c x -&gt; if x &gt; p then c+1 else c) 0 l

let max_num_surpasser l =  
  let rec aux ms l =
    match ms, l with
    | _, [] -&gt; ms
    | None, p::tl -&gt; aux (Some (p, num_surpasser p tl)) tl
    | Some (_, c), p::tl -&gt; 
      let ns = num_surpasser p tl in
      if ns &gt; c then aux (Some (p, ns)) tl
      else aux ms tl
  in
  aux None l

(* note think the answer as an `option` will make the code seem more complicated, but it is not a bad practice as for empty list we won't have max number of surpassers *)
</code></pre>

<p>The solution should be easy enough to obtain but its time complexity is <code>O(n^2)</code> which is worse than the required <code>O(nlogn)</code>. </p>

<h1 id="introducingdivideandconquer">Introducing Divide and Conquer</h1>

<p><img src="http://typeocaml.com/content/images/2015/02/conquer-1.jpg" alt="hero"></p>

<p>The algorithm design technique <em>divide and conquer</em> was mentioned in <a href="http://typeocaml.com/2014/12/04/recursion-reloaded/">Recursion Reloaded</a>. I believe it is a good time to properly introduce it now as it provides a elegant approach towards a better solution for pearl 2.</p>

<h2 id="whatisitliterally">What is it, literally</h2>

<p>Suppose we want to replace the dragon lady and become the king of the land below (<em>[2]</em>).</p>

<p><img src="http://typeocaml.com/content/images/2015/02/game_of_thrones_color-1.jpg" alt="game_of_thrones"></p>

<p>We are very lucky that we have got a strong army and now the only question is how to overcome the realm.</p>

<p>One "good" plan is <em>no plan</em>. We believe in our troops so much that we can just let all of them enter the land and pwn everywhere.</p>

<p><img src="http://typeocaml.com/content/images/2015/02/game_of_thrones_strategy_1.jpg" alt="pwn"></p>

<p>Maybe our army is very good in terms of both <em>quality</em> and <em>quantity</em> and eventually this plan will lead us to win. However, is it really a good plan? Some soldiers may march to places that have already been overcome; Some soldiers may leave too soon for more wins after one winning and have to come back due to local rebel... the whole process won't be efficient and it cost too much gold on food for men and horses.</p>

<p>Fortunately, we have a better plan.</p>

<p><img src="http://typeocaml.com/content/images/2015/02/game_of_thrones_dragon-2.jpg" alt="better"></p>

<p>We divide the land into smaller regions and further smaller ones inside until unnecessary. And for each small region, we put ideal amount of soldiers there for battles. After soldiers finish their assigned region, they don't need to move and just make sure the region stay with us. This is more oganised and more efficient in terms of both gold and time. After all, if we conquer all the tiny regions, who would say we were not the king?</p>

<h2 id="whatisitinalgorithmdesignwithaccumulation">What is it in algorithm design, with accumulation</h2>

<p><em>divide and conquer</em> in algorithm design is not a universal solution provider, but a problem attacking strategy or paradigm. Moreover, although this classic term has been lasting for quite a long time, personally I would like to add one more action - <strong>accumulate</strong> - to make it appear more complete. Let's check the 3 actions one by one to see how we can apply the techque.</p>

<h3 id="divide">Divide</h3>

<p>Conceptually this action is simple and we know we need to divide a big problem into smaller ones. But <em>how to</em> is non-trivial and really context-sensitive. Generally we need to ask ourselves 2 questions first:</p>

<blockquote>
  <p>What are the sizes of the smaller sub-problems?</p>
</blockquote>

<p>Normally we intend to halve the problem because it can lead us to have a <code>O(logn)</code> in our final time complexity. </p>

<p>But it is not a must. For example <a href="http://www.sorting-algorithms.com/quick-sort-3-way">3-way quicksort</a> divides the problem set into 3 smallers ones. 3-way partition can let quicksort have O( $ \log_3{n} $ ). However, do not forget the number of comparison also increases as we need to check equality during partition.</p>

<p>Moreover, sometimes we may have to just split the problem into a sub-problem with size 1 and another sub-problem with the rest, like what we did for the <code>sum</code> function. This kind of <em>divide</em> won't give us any performance boost and it turns out to be a normal recursion design. </p>

<blockquote>
  <p>Do we directly split the problem, or we somehow reshape the problem and then do the splitting?</p>
</blockquote>

<p>In <em>mergesort</em>, we simply split the problem into 2; while in <em>quicksort</em>, we use <em>partition</em> to rearrange the list and then obtain the 2 sub-problems. </p>

<p>The point of this question is to bear in mind that we do not have shortcuts. We can have a very simple splitting, but later on we need to face probably more complicated <em>accumulate</em>. Like <em>mergesort</em> relies on <em>merge</em>. Or, we can do our important work during <em>divide</em> phase and have a straight <em>accumulate</em> (<em>quicksort</em> just needs to concatenate the solutions of the two sub-problems with the <em>pivot</em> in the middle).</p>

<h3 id="conquer">Conquer</h3>

<p>This action implies two things:</p>

<ol>
<li>Recursion. We divided the problem, then we need to conquer. How to conquer? We need to apply <em>divide and conquer and accumulate</em> again until we are not able to divide any more.  </li>
<li>Edge cases. This means if we cannot divide further, then it is time to really give a solution. For example, let's say our target is a list. If we reach an empty list or an one-element list, then what shall we do? Normally, if this happens, we do not need to <em>accumulate</em> and just return the answer based on the edge cases.</li>
</ol>

<p>I believe the <em>conquer</em> part in the original <em>divide and conquer</em> term also implies the <em>accumulate</em>. I seperate <em>accumulate</em> as explained next.</p>

<h3 id="accumulate">Accumulate</h3>

<p>After we conquer every little area of the land, we should now somehow combine all our accomplishments and really build a kingdom out of them. This is the step of <em>accumulate</em>.</p>

<p>A key way to figure out <em>how to accumulate</em> is to <strong>start from small</strong>. In <em>mergesort</em>, if each of the 2 sub-problems just has one element, then the according answer is a list having that element and we have finished the <em>conquer</em> step. Now we have two lists each of which has one element, how can we accumulate them to have a single sorted list? Simple, smaller element goes first into our resulting list. What if we have two sorted list each of which has two elements? The same, smaller element goes first again.</p>

<p>If we decide to divide the problem in a fairly simple way, then <em>accumulate</em> is normally non-trivial and also dominates the time complexity. Figuring out a cost-efficient approach of <em>accumulate</em> is very important.</p>

<h3 id="summary">Summary</h3>

<p>Again, <em>divide and conquer and accumulate</em> is just a framework for solving an algorithm problem. All the concrete solutions are problem context based and can spread into all 3 steps. </p>

<p>In addition, a fundamental hint to using this techqniue is that if we are given a problem, and we know the future solution is not anyhow related to the problem size, then we should try <em>divide and conquer and accumulate</em></p>

<h1 id="solvepearl2">Solve pearl 2</h1>

<p>Although pearl 2 asks us to get the max number of surpassers, we can </p>

<ol>
<li>Get the number of surpassers for every element (we anyway need to)  </li>
<li>Then do a linear scan for the max one. </li>
</ol>

<p>The second step is <code>O(n)</code>. If we can achieve the first step in <code>O(nlogn)</code>, the overall time complexity stays as <code>O(nlogn)</code>. </p>

<p>So our current goal is to use <em>divide and conquer and accumulate</em> to get all numbers of surpassers.</p>

<h1 id="dividetheproblemofpearl2">Divide the problem of pearl 2</h1>

<p><img src="http://typeocaml.com/content/images/2015/02/problem_description_1-1.jpg" alt="problem1"></p>

<p>We have such as list and we want to get a new list that have the same elements and each element is associated with the number of its surpassers. Now we want to divide the original list (problem set).</p>

<p>Can we directly halve the list?</p>

<p><img src="http://typeocaml.com/content/images/2015/02/divide_1-3.jpg" alt="divide_1"></p>

<p>As pearl 2 stated, an element only cares about all elements that are behind it. So if we split the list in the middle, we know the numbers of surpassers for all elements in <code>sub-problem 2</code> do not need any special operations and the answers can directly be part of the future resulting list. </p>

<p>For the elements inside <code>sub-problem 1</code>, the answers are not fully accomplished yet as they will be affected by the elemnts in <code>sub-problem 2</code>. But hey, how we obtain full answers for <code>sub-problem 1</code> with the help of the solutions of <code>sub-problem 2</code> should be the job of <em>accumulate</em>, right? For now, I believe halving the problem is a good choice for <em>divide</em> as at least we already solve half of the problem directly.</p>

<h1 id="conquer">Conquer</h1>

<p>We of course will use recursion. For sub-problems, we further halve them into smaller sub-problems until we are not able to, which means we reach the edge cases.</p>

<p>There are possibly two edge cases we need to conquer:</p>

<ol>
<li>Empty list  </li>
<li>A list with only one element.</li>
</ol>

<p><img src="http://typeocaml.com/content/images/2015/02/conquer-2.jpg" alt="conquer"></p>

<p>For empty list, we just need to return an empty list as there is no element for us to count the number of surpassers. For an one-element list, we also return an one-element resulting list where the only element has <code>0</code> surpassers.</p>

<h1 id="accumulate">Accumulate</h1>

<p>Now we finished dividing and conquering like below and it is time to accumulate (take <code>sub-problem 1</code> only for illustration).</p>

<p><img src="http://typeocaml.com/content/images/2015/02/accumulate_1.jpg" alt="accumulate 1"></p>

<p>It is easy to combine solutions of <code>sp 111</code> and <code>sp 112</code>: just compare <code>8</code> from <code>sp 111</code> with <code>1</code> from <code>sp112</code>, update <code>8</code>'s number of surpassers if necessary and we can leave <code>sp 112</code> alone as we talked about during <em>divide</em>. The same way can be applied on <code>sp 121</code> and <code>sp 122</code>. Then we get:</p>

<p><img src="http://typeocaml.com/content/images/2015/02/accumulate_2.jpg" alt="accumulate 2"></p>

<p>Now both <code>sp 11</code> and <code>sp 12</code> have more than one element. In order to get the solution for <code>sp 1</code>, <code>sp 12</code> can stay put. How about <code>sp 11</code>? An obvious approach is just let every element in <code>sp 11</code> to compare every element in <code>sp 12</code>, and update their numbers of surpassers accordingly. This can be a candidate for <em>accumulate</em> action, however, it is <code>O(n^2)</code>. We need to accumulate better.</p>

<p>We said in the very beginning of this post during our trivial solution that the original order of the list matters. However, is it still sensitive after we get the solution (for a sub-problem)? </p>

<p><img src="http://typeocaml.com/content/images/2015/02/accumulate_3-1.jpg" alt="accumulate 3"></p>

<p>As we can see once the answer of <code>sp 11</code> is obtained, the order between <code>8</code> and <code>1</code> doesn't matter as they don't rely on each for their number of surpassers any more.</p>

<p>If we can obtain the solution in a sorted manner, it will help us a lot. For example, assume the resulting lists for <code>sp 11</code> and <code>sp 12</code> are sorted like this:</p>

<p><img src="http://typeocaml.com/content/images/2015/02/accumulate_4.jpg" alt="accumulate 4"></p>

<p>Then we can avoid comparing every pair of elements by using <em>merge</em> like this:</p>

<p><img src="http://typeocaml.com/content/images/2015/02/accumulate_5-1.jpg" alt="accumulate 5"></p>

<p>We can see that <code>8</code> in the left hand side list doesn't have to compare to <code>-10</code> any more. However, this example has not shown the full picture yet. <strong>If keep tracking the length of resulting list on the right hand side, we can save more comparisons</strong>. Let's assume both <code>sp 1</code> and <code>sp 2</code> have been solved as sorted list with lengths attached.</p>

<p><img src="http://typeocaml.com/content/images/2015/02/accumulate_6.jpg" alt="accumulate 6"></p>

<p>We begin our <em>merge</em>.</p>

<p><img src="http://typeocaml.com/content/images/2015/02/accumulate_7-2.jpg" alt="accumulate 7"></p>

<p>Have you noticed the fascinating part? Because <code>-10 &lt; -2</code>, without further going down along the resulting list on the right hand side, we can directly update the number of surpassers of <code>-10</code> and get it out. Why? Because <code>-2</code> is the smallest element on the right, and if it is bigger than <code>-10</code>, then the rest of the elements on the right must all be bigger than <code>-10</code>, right? Through only one comparison (instead of 4), we get the number of surpassers. </p>

<p>Thus, <strong>as long as the solutions of all sub-problems are sorted list with the length associated, we can accumulate like this</strong>:</p>

<ol>
<li>Compare the heads <code>hd1</code> and <code>hd2</code>, from two sorted resulting lists <code>l1</code> and <code>l2</code>, respectively  </li>
<li>If <code>hd1</code> >= <code>hd2</code>, then <code>hd2</code> gets out; go to 1 with updated length for <code>l2</code>  </li>
<li>if <code>hd1</code> &lt; <code>hd2</code>, then <code>hd1</code> gets out, and its <code>ns</code> gets updated by adding the length of <code>l2</code> to the existing value; go to 1 with updated length for <code>l1</code></li>
</ol>

<p>The full process of accumulating <code>sp 1</code> and <code>sp 2</code> is illustrated as follows:</p>

<p><img src="http://typeocaml.com/content/images/2015/02/accumulate_8-1.jpg" alt="accumulate 8"></p>

<p>Two things might need to be clarified:</p>

<ol>
<li>Although we assumed the resulting lists of sub-problems to be sorted, they will naturally become sorted anyway because we are doing the <em>smaller goes first</em> merging.  </li>
<li>We need to attach the lengths to each resulting list on the right and keep updating them because scanning the length of a list takes <code>O(n)</code>.</li>
</ol>

<p>Obviously this way of accumulation can give us <code>O(n)</code>. Because at most we can divide <code>O(logn)</code> times, our <em>divide and conquer and accumulate</em> solution will be <code>O(nlogn)</code>.</p>

<h1 id="code">Code</h1>

<p>At first, we <em>divide</em>. Note that this version of <em>divide</em> is actually a kind of <code>splitting from middle</code>, as the original order of the elements before we get any solution is important.</p>

<pre><code class="ocaml">(* we have a parameter n to indicate the length of l.
   it will be passed by the caller and 
   in this way, we do not need to scan l for its length every time.

   it will return left, right and the length of the right.
*)
let divide l n =  
  let m = n / 2 in
  let rec aux left i = function
    | [] -&gt; List.rev left, [], 0
    | right when i &gt;= m -&gt; List.rev left, right, n-i
    | hd::tl -&gt; aux (hd::left) (i+1) tl
  in
  aux [] 0 l
</code></pre>

<p>Now <em>accumulate</em>. We put it before writing <em>conquer</em> because <em>conquer</em> would call it thus it must be defined before <em>conquer</em>.</p>

<pre><code class="ocaml">let accumulate l1 l2 len2 =  
  let rec aux acc len2 = function
    | l, [] | [], l -&gt; List.rev_append acc l
    | (hd1,ns1)::tl1 as left, ((hd2,ns2)::tl2 as right) -&gt;
      if hd1 &gt;= hd2 then aux ((hd2,ns2)::acc) (len2-1) (left, tl2)
      else aux ((hd1,ns1+len2)::acc) len2 (tl1, right)
  in
  aux [] len2 (l1, l2)
</code></pre>

<p><em>conquer</em> is the controller.</p>

<pre><code class="ocaml">(* note the list parameter is a list of tuple, i.e., (x, ns) *)
let rec conquer n = function  
  | [] | _::[] as l -&gt; l
  | l -&gt;
    let left, right, right_len = divide l n in
    let solution_sp1 = conquer (n-right_len) left in
    let solution_sp2 = conquer right_len right in
    accumulate solution_sp1 solution_sp2 right_len
</code></pre>

<p>So if we are given a list of numbers, we can now get all numbers of surpassers:</p>

<pre><code class="ocaml">let numbers_of_surpassers l =  
  List.map (fun x -&gt; x, 0) l |&gt; conquer (List.length l)
</code></pre>

<p>Are we done? No! we should find the max number of surpassers out of them:</p>

<pre><code class="ocaml">(* we should always consider the situation where no possible answer could be given by using **option**, although it is a bit troublesome *)
let max_num_surpassers = function  
  | [] -&gt; None
  | l -&gt;
    let nss = numbers_of_surpassers l in
    Some (List.fold_left (fun max_ns (_, ns) -&gt; max max_ns ns) 0 nss)
</code></pre>

<hr>

<p><strong>[1]</strong> Unless I can see an optimal solution instantly, I always intend to think of the most straightforward one even though it sometimes sounds stupid. I believe this is not a bad habit. Afterall, many good solutions come out from brute-force ones. As long as we anyway have a solution, we can work further based on it and see whether we can make it better. </p>

<p><strong>[2]</strong> Yes, I believe the dragon lady will <a href="http://www.imdb.com/title/tt0944947/">end the game and win the throne</a>. It is the circle and fate. </p>]]></description><link>http://typeocaml.com/2015/02/20/pearl-no-2-the-max-number-of-surpassers/</link><guid isPermaLink="false">9b0bc69d-2e2a-46bf-896a-95a167151999</guid><category><![CDATA[merge]]></category><category><![CDATA[pearls]]></category><category><![CDATA[algorithm]]></category><category><![CDATA[max]]></category><category><![CDATA[divide and conquer]]></category><category><![CDATA[surpassers]]></category><dc:creator><![CDATA[Jackson Tale]]></dc:creator><pubDate>Sat, 21 Feb 2015 01:24:38 GMT</pubDate></item><item><title><![CDATA[Pearl No.1 - The Min Missing Natural Number]]></title><description><![CDATA[<p><img src="http://typeocaml.com/content/images/2015/01/pearls2-1.jpg#hero" alt="pears"></p>

<p><a href="http://www.cs.ox.ac.uk/richard.bird/">Prof. Richard Simpson Bird</a> is a Supernumerary Fellow of Computation at <a href="http://www.lincoln.ox.ac.uk/">Lincoln College, Oxford</a>, England, and former director of <a href="http://www.cs.ox.ac.uk/">the Oxford University Computing Laboratory</a>. His research interests include:</p>

<ul>
<li>The algebra of programming</li>
<li>The calculation of algorithms from their specification</li>
<li>Functional programming</li>
<li>Algorithm design</li>
</ul>

<p>In 2010, he wrote the book <a href="http://www.cambridge.org/gb/academic/subjects/computer-science/programming-languages-and-applied-logic/pearls-functional-algorithm-design">Pearls of Functional Algorithm Design</a>  </p>

<p><img src="http://typeocaml.com/content/images/2015/01/pearls_book.jpeg" alt="book"></p>

<p>This book presents <strong>30 algorithm problems and their functional solutions</strong>. The reason that they are called as <em>pearls</em> is what I quote below:</p>

<blockquote>
  <p>Just as natural pearls grow from grains of sand that have irritated oysters, these programming pearls have grown from real problems that have irritated programmers. The programs are fun, and they teach important programming techniques and fundamental design principles. </p>
</blockquote>

<p>These pearls are all classic and togehter with the well presented functional approaches, they become very helpful for ones who really wish to sharpen their functional programming on algorithms. I have so far solved / fully understood 17 pearls and hmm...the rest are indeed difficult, at least for me. Nevertheless, I would like to share my journey of studying this book with you via a series of posts, each of which is a pearl in the book. All the posts will differ from the book in the following ways:</p>

<ol>
<li><strong>Only OCaml is used</strong> for the implementations (for the obvious reason: I am a fan of OCaml)  </li>
<li><strong>More general (functional) analysis techniques</strong> are adopted. The book heavily focuses on algebraic approach, namely, <em>design by calculation</em>, which honestly is too much for me. I mean I can understand the methodology, but cannot master it. So during my study, I did not replicate the algebraic thinking; instead, I tried to sniff around the functional sprit behind the curtain and consider the algebraic part as the source of hints.  </li>
<li><strong>Tail-recursive implementation</strong> will be provided if possible. The haskell implementations in the book do not consider much about tail-recursive because a) haskell is lazy; b) haskell's compiler is doing clever things to help recursion not blow. OCaml is different. It is not lazy and does not rely on the compiler to do optimisations on the potential <em>stackoverflow</em>. So as OCaml developers, we need to care about tail-recursive explicitly.</li>
</ol>

<p>Ok. Let's get started.</p>

<h1 id="theminmissingnaturalnumber">The Min Missing Natural Number</h1>

<blockquote>
  <p>Given a unordered list of distinct natural numbers, find out the minimum natural number that is not in the list.</p>
  
  <p>For example, if the list is [8; 2; 3; 0; 12; 4; 1; 6], then 5 is the minimum natural number that is missing.</p>
  
  <p>O(n) solution is desired.</p>
</blockquote>

<p><img src="http://typeocaml.com/content/images/2015/02/problem_description-1.jpg" alt="eg"></p>

<h1 id="analysisoftheproblemdescription">Analysis of the problem description</h1>

<p>The description of an algorithm problem specifies the input, the output and the constraint. Yet, it is more than just telling us what to achieve. Most of the time, the literatures can provide us hints for possible solutions. Let's break down the description first:</p>

<ol>
<li>unordered list  </li>
<li>distinct  </li>
<li>natural numbers  </li>
<li>minimum and missing</li>
</ol>

<h3 id="unorderedlist">unordered list</h3>

<p>The input list is not sorted. If this is specified explicitly, it implies that ordering is important here. In other words, if the list was sorted, then the problem would not be a problem any more or at least much easier to solve.</p>

<h3 id="distinct">distinct</h3>

<p>There are no duplicates inside.</p>

<h3 id="naturalnumbers">natural numbers</h3>

<p>All numbers are non-negative integers, i.e., 0, 1, 2, ... This puts a lower boundary on the possible numbers in the input list.</p>

<h3 id="minimumandmissing">minimum and missing</h3>

<p>There might be unlimited numbers not in the input list, but we just need to find the smallest one. When our goal is to locate something with certain characteristic, it would normally be a <em>selection problem</em>. Moreover, for problems related <em>min</em> or <em>max</em>, they normally can be solved by somehow bringing sorting; however, sorting will heavily involve moving all numbers around. As our target is only one number, sorting can be an overkill.</p>

<h1 id="aneasybutnotoptimalsolution">An easy but not optimal solution</h1>

<p>From the analysis above, it is obvious that sorting can solve our problem quite easily. We can simply </p>

<ol>
<li>Sort the input list  </li>
<li>If the first number is not <code>0</code>, then the result is <code>0</code>  </li>
<li>Scan every consecutive pair (x, y)  </li>
<li>If <code>y - x &gt; 1</code> then the result is <code>x + 1</code>  </li>
<li>If point 4 never happens, then the result is <code>the last number plus 1</code>.</li>
</ol>

<p><img src="http://typeocaml.com/content/images/2015/02/easy_solution.jpg" alt="easy_solution"></p>

<pre><code class="ocaml">let min_missing_trivial l =  
  let sl = List.sort compare l in
  let rec find = function
    | [] -&gt; None
    | x::[] -&gt; Some (x+1)
    | x::y::_ when y - x &gt; 1 -&gt; Some (x+1)
    | _::tl -&gt; find tl
  in
  (* adding -1 can cover point 2 and make find work for all *)
  find ((-1)::sl) 
</code></pre>

<p>Have we solved the problem? Let's have a look. The solution above can achieve the goal indeed. However, the time complexity of this solution is <code>O(nlogn)</code> since the sorting bit is dominating, which is worse than the required <code>O(n)</code>. </p>

<p>We have to try harder.</p>

<h1 id="doweneedcompleteorder">Do we need complete order?</h1>

<p>So, if we do a sorting, we can obtain the answer but it is too slow. Let's have a look again at what we get after sorting.</p>

<p><img src="http://typeocaml.com/content/images/2015/02/completely_ordered.jpg" alt="completely sorted"></p>

<p>If the list is sorted, then it provides us a chance where we check the consecutiveness of the numbers and the first gap is what we want. There are two questions though:</p>

<blockquote>
  <p>Q1. Shall we care about the consecutiveness after <code>6</code>?</p>
</blockquote>

<p>The answer is <em>no</em>. Since we are chasing for the <em>minimum</em>, i.e., the first missing one, the order of the numbers after the gap doesn't matter any more. </p>

<p>For example, even if <code>12</code> is before <code>8</code>, the result won't be affected.</p>

<p><img src="http://typeocaml.com/content/images/2015/02/after_gap.jpg" alt="after gap"></p>

<blockquote>
  <p>Q2. Is the order of all the numbers before the gap important?</p>
</blockquote>

<p>Let's randomly mess up the order of <code>0</code>, <code>1</code>, <code>2</code>, and <code>3</code> a little:</p>

<p><img src="http://typeocaml.com/content/images/2015/02/before_gap-1.jpg" alt="before gap"></p>

<p>It seems fine as the messed order of those 4 numbers does not affect the position of <code>4</code> and <code>6</code>. But hang on a minute, something is not right there.</p>

<p>We replied on the consecutiveness of <code>0</code>, <code>1</code>, <code>2</code>, and <code>3</code> to locate the first gap, and the consecutiveness can be checked via the numbers being sorted. Hence, if the order before the gap was not maintained, how could we scan for consecutiveness and find the gap in the first place? It sounds like a chicken and egg thing.</p>

<p>So can we check for the consecutiveness of the numbers without sorting them?</p>

<h1 id="hintshiddenindistinctnaturalnumbers">Hints hidden in "distinct natural numbers"</h1>

<p>Yes, we can, and now it is the time to ask for help from <em>distinct natural numbers</em>. </p>

<p>As we described before, <em>natural numbers</em> are integers euqal to or larger than <code>0</code>. This lower bound <code>0</code> plus the constraint of <em>no duplicates</em> gives us the opportunity to check for consecutiveness without requiring all numbers being sorted. Let's first see a perfect consecutive sequnce (starting from 0) of natural numbers:</p>

<p><img src="http://typeocaml.com/content/images/2015/02/perfect_consecutive_1.jpg" alt="perfect1"></p>

<p>They are sorted of course. Is there any other characteristic? Or say, for a number inside the sequence, how many other numbers are less than it (on its left side)?</p>

<p><img src="http://typeocaml.com/content/images/2015/02/perfect_consecutive_count.jpg" alt="count"></p>

<p>For number <code>4</code>, there will exact <code>4</code> natural numbers less than itself. The same thing will apply on any numbers as long as all those belong to a perfect consecutive sequence starting from <code>0</code>. </p>

<p>This is also a two-way mapping, i.e., if we are told that there are <code>4</code> numbers less than <code>4</code> and all of them are before <code>4</code>, we can be sure that all five numbers can form a consecutive sequence. Most importantly, now whether all numbers are in order or not does not matter any more.</p>

<p><img src="http://typeocaml.com/content/images/2015/02/perfect_consecutive_not_ordered.jpg" alt="not ordered again"></p>

<blockquote>
  <p>What does a perfect consecutiveness imply? </p>
</blockquote>

<p>It implies that among the sequence, no one is missing and if anyone is missing, it must be on the right side of the max of the sequence.</p>

<p><img src="http://typeocaml.com/content/images/2015/02/missing_in_right.jpg" alt="in the right"></p>

<blockquote>
  <p>What if for a number, the number of smaller ones does not match its own value?</p>
</blockquote>

<p>It means the sequence up to the number won't be consecutive, which implies that there must be at least one a natural number missing, right?</p>

<p><img src="http://typeocaml.com/content/images/2015/02/in_the_left.jpg" alt="in the left"></p>

<p>Now we have the weapon we want. In order to check consecutiveness, or say, to know the region where the min missing natural number is, we don't need complete sorting any more. Instead, we just to</p>

<ol>
<li>pick a number <code>x</code> from the sequence  </li>
<li>put all other smaller numbers to its left and count how many are those in <code>num_less</code>  </li>
<li>put all larger ones to its right  </li>
<li>If <code>num_less = x</code>, then it means <code>x</code>'s left branch is perfect and the missing one must be in its right branch. We repeat the whole process in the sequence of right hand side.  </li>
<li>Otherwise, we repeat in the left branch. Note that due to <em>distinct</em>, it is impossible <code>num_less &gt; x</code>. </li>
</ol>

<p>In this way, we cannot identify the min missing one in one go, but we can narrow down the range where it might be through each iteration and eventually we will find it when no range can be narrowed any more. </p>

<p>Sounds like a good plan? let's try to implement it.</p>

<h1 id="partitionandimplementation">Partition and Implementation</h1>

<p>Do you feel familiar with the process we presented above? It is actually a classic <code>partition</code> step which is the key part of <em>quicksort</em> <a href="http://typeocaml.com/2015/01/02/immutable/">we talked about</a>.</p>

<p>Of course, in this problem, it won't be a standard <code>partition</code> as we need to record <code>num_less</code>. The code should be easy enough to write:</p>

<pre><code class="ocaml">let partition x l =  
  let f (num_less, left, right) y =
    if y &lt; x then num_less+1, y::left, right
    else num_less, left, y::right
  in
  List.fold_left f (0, [], []) l
</code></pre>

<p>Also our solver function should be straightword too:</p>

<pre><code class="ocaml">let min_missing l =  
  let rec find lo = function
    | [] -&gt; lo
    | x::tl -&gt;
      let num_less, left, right = partition x tl in
      if num_less + lo = x then find (x+1) right
      else find lo left
  in
  find 0 l

(* Why do we introduce `lo`?
   I will leave this question to the readers *)
</code></pre>

<h2 id="timecomplexityofournewsolution">Time complexity of our new solution</h2>

<p>For the very 1st iteration, we need to scan all numbers, so costs <code>O(n)</code> for this step. But we can skip out ideally half of the numbers.</p>

<p>So for the 2nd iteration, it costs <code>O(n*(1/2))</code>. Again, further half will be ruled out.</p>

<p>...</p>

<p>So the total cost would be <code>O(n * (1 + 1/2 + 1/4 + 1/8 + ...)) = O(n * 2) = O(n)</code>.</p>

<p>We made it!</p>

<h1 id="summary">Summary</h1>

<p>This is the first pearl and it is not that difficult, especially if you knew <em>quickselect</em> algorithm before. </p>

<p>Actually, many of the pearls involve certain fundamental algorithms and what one need to do is to peel the layers out one by one and eventually solve it via the essentials. If you are interested in pearls, please pay attentions to the tags attached with each pearl as they show what each pearl is really about.</p>]]></description><link>http://typeocaml.com/2015/02/02/functional-pearl-no-1-the-min-free-nature/</link><guid isPermaLink="false">8893ba30-fb46-4ad4-a4b8-c3fdd34d596f</guid><category><![CDATA[pearls]]></category><category><![CDATA[algorithm]]></category><category><![CDATA[min]]></category><category><![CDATA[selection]]></category><category><![CDATA[quickselect]]></category><category><![CDATA[min missing natural number]]></category><dc:creator><![CDATA[Jackson Tale]]></dc:creator><pubDate>Mon, 02 Feb 2015 17:34:31 GMT</pubDate></item><item><title><![CDATA[Recursive Memoize & Untying the Recursive Knot]]></title><description><![CDATA[<p><img src="http://typeocaml.com/content/images/2015/01/knot-1.jpg#hero" alt=""></p>

<p>When I wrote the section of <em>When we need later substitution</em> in  <a href="http://typeocaml.com/2015/01/20/mutable/">Mutable</a>, I struggled. I found out that I didn't fully understand the recursive memoize myself, so what I had to do was just copying the knowledge from <a href="https://realworldocaml.org/v1/en/html/imperative-programming-1.html#memoization-and-dynamic-programming">Real World OCaml</a>. Luckily, after the post was published, <em>glacialthinker</em> <a href="http://www.reddit.com/r/ocaml/comments/2t49p9/mutable_and_when_shall_we_use_imperative/cnvryku">commented</a> in <a href="http://www.reddit.com/r/ocaml/comments/2t49p9/mutable_and_when_shall_we_use_imperative/">reddit</a>:</p>

<blockquote>
  <blockquote>
    <p>(I never thought before that a recursive function can be split like this, honestly. I don't know how to induct such a way and can't explain more. I guess we just learn it as it is and continue. More descriptions of it is in the book.)</p>
  </blockquote>
  
  <p>This is "untying the recursive knot". And I thought I might find a nice wikipedia or similiar entry... but I mostly find Harrop. :) He actually had a nice article on this many years back in his OCaml Journal. Anyway, if the author swings by, searching for that phrase may turn up more material on the technique.</p>
</blockquote>

<p>It greatly enlightened me. Hence, in this post, I will share with you my futher understanding on <em>recursive memoize</em> together with the key cure <em>untying the recursive knot</em> that makes it possible. </p>

<h1 id="simplememoizerevamped">Simple Memoize revamped</h1>

<p>We talked about the simple <em>memoize</em> before. It takes a non-recursive function and returns a new function which has exactly the same logic as the original function but with new new ability of caching the <em>argument, result</em> pairs. </p>

<pre><code class="ocaml">let memoize f =  
  let table = Hashtbl.Poly.create () in
  let g x = 
    match Hashtbl.find table x with
    | Some y -&gt; y
    | None -&gt;
      let y = f x in
      Hashtbl.add_exn table ~key:x ~data:y;
      y
  in
  g
</code></pre>

<p><img src="http://typeocaml.com/content/images/2015/01/simple_memoize-1.jpg" alt=""></p>

<blockquote>
  <p>The greatness of <code>memoize</code> is its flexibility: as long as <code>f</code> takes a single argument, <code>memoize</code> can make a <em>memo version</em> out of it without touching anything inside <code>f</code>.  </p>
</blockquote>

<p>This means while we create <code>f</code>, we don't need to worry about the ability of caching but just focus on its own correct logic. After we finish <code>f</code>, we simply let <code>memoize</code> do its job. <em>Memoization</em> and <em>functionality</em> are perfectly separated. </p>

<p><strong>Unfortunately, the simple <code>memoize</code> cannot handle recursive functions.</strong> If we try to do <code>memoize f_rec</code>, we will get this:</p>

<p><img src="http://typeocaml.com/content/images/2015/01/simple_memoize_rec.jpg" alt=""></p>

<p><code>f_rec</code> is a recursive function so it will call itself inside its body. <code>memoize f_rec</code> will produce <code>f_rec_memo</code> which is a little similar as the previous <code>f_memo</code>, yet with the difference that it is not a simple single call of <code>f_rec arg</code> like we did <code>f arg</code>. Instead, <code>f_rec arg</code> may call <code>f_rec</code> again and again with new arguments. </p>

<p>Let's look at it more closely with an example. Say, <code>arg</code> in the recursive process will be always decreased by <code>1</code> until <code>0</code>.</p>

<ol>
<li>Let's first od <code>f_rec_memo 4</code>.  </li>
<li><code>f_rec_memo</code> will check the <code>4</code> against <code>Hashtbl</code> and it is not in.  </li>
<li>So <code>f_rec 4</code> will be called for the first time.  </li>
<li>Then <code>f_rec 3</code>, <code>f_rec 2</code>, <code>f_rec 1</code> and <code>f_rec 0</code>.  </li>
<li>After the 5 calls, result is obtained. Then <em>4, result</em> pair is stored in <code>Hashtbl</code> and returned.  </li>
<li>Now let's do <code>f_rec_memo 3</code>, what will happen? Obviously, <code>3</code> won't be found in <code>Hashtbl</code> as only <code>4</code> is stored in step 5.  </li>
<li>But should <em>3, result</em> pair be found? Yes, it should of course because we have dealt with <code>3</code> in step 4, right?  </li>
<li>Why <code>3</code> has been done but is not stored?  </li>
<li>ahh, it is because we did <code>f_rec 3</code> but not <code>f_rec_memo 3</code> while only the latter one has the caching ability. </li>
</ol>

<p>Thus, we can use <code>memoize f_rec</code> to produce a memoized version out of <code>f_rec</code> anyway, but it changes only the surface not the <code>f_rec</code> inside, hence not that useful. How can we make it better then?</p>

<h1 id="recursivememoizerevamped">Recursive Memoize revamped</h1>

<p>What we really want for memoizing a recursive function is to blend the <em>memo</em> ability deep inside, like this:</p>

<p><img src="http://typeocaml.com/content/images/2015/01/memoize_rec_wish-1.jpg" alt=""></p>

<p>Essentially we have to replace <code>f_rec</code> inside with <code>f_rec_memo</code>:</p>

<p><img src="http://typeocaml.com/content/images/2015/01/transform-1.jpg" alt=""></p>

<p>And only in this way, <code>f_rec</code> can be fully memoized. However, we have one problem: **it seems that we have to change the internal of <code>f_rec</code>.</p>

<p>If we can modify <code>f_rec</code> directly, we can solve it easily . For instance of <em>fibonacci</em>:</p>

<pre><code class="ocaml">let rec fib_rec n =  
  if n &lt;= 1 then 1
  else fib_rec (n-1) + fib_rec (n-2)
</code></pre>

<p>we can make the memoized version:</p>

<pre><code class="ocaml">let fib_rec_memo_trivial n =  
  let table = Hashtbl.Poly.create () in
  let rec fib_rec_memo x = 
    match Hashtbl.find table x with
    | Some y -&gt; y
    | None -&gt;
      let y = fib_rec_memo (x-1) + fib_rec_memo (x-2) in
      Hashtbl.add_exn table ~key:x ~data:y;
      y
  in
  fib_rec_memo
</code></pre>

<p>In the above solution, we replaced the original <code>fib_rec</code> inside with <code>fib_rec_memo</code>, however, we also changed the declaration to <code>fib_rec_memo</code> completely. In fact, now <code>fib_rec</code> is totally ditched and <code>fib_rec_memo</code> is a new function that blends the logic of <em>memoize</em> with the logic of <code>fib_rec</code>. </p>

<p>Well, yes, <code>fib_rec_memo_trivial</code> can achieve our goal, but only for <code>fib_rec</code> specificly. If we need to make a memoized version for another recursive function, then we need to change the body of that function again. This is not what we want. <strong>We wish for a <code>memoize_rec</code> that can turn <code>f_rec</code> directly into a memoized version, just like what the simple <code>memoize</code> can do for <code>f</code></strong>.</p>

<p>So we don't have a shortcut. Here is what we need to achieve:</p>

<ol>
<li>we have to replace the <code>f_rec</code> inside the body of <code>f_rec</code> with <code>f_rec_memo</code>  </li>
<li>We have keep the declaration of <code>f_rec</code>.  </li>
<li>We must assume we can't know the specific logic inside <code>f_rec</code>. </li>
</ol>

<p>It sounds a bit hard. It is like giving you a compiled function without source code and asking you to modify its content. And more imporantly, your solution must be generalised. </p>

<p>Fortunately, we have a great solution to create our <code>memoize_rec</code> without any <em>hacking</em> or <em>reverse-engineering</em> and <strong>untying the recursive knot is the key</strong>. </p>

<h1 id="untyingtherecursiveknot">Untying the Recursive Knot</h1>

<p>To me, this term sounds quite fancy. In fact, I never heard of it before <em>2015-01-21</em>. After I digged a little bit about it, I found it actually quite simple but very useful (this recursive memoize case is an ideal demonstration). Let's have a look at what it is.</p>

<p>Every recursive function somehow follows a similar pattern where it calls itself inside its body:</p>

<p><img src="http://typeocaml.com/content/images/2015/01/single_f_rec.jpg" alt=""></p>

<p>Once a recursive function application starts, it is out of our hands and we know it will continue and continue by calling itself until the <em>STOP</em> condition is satisfied. <strong>What if the users of our recursive function need some more control even after it gets started?</strong> </p>

<p>For example, say we provide our users <code>fib_rec</code> without source code, what if the users want to print out the detailed trace of each iteration? They are not able unless they ask us for the source code and make a new version with printing. It is not that convenient.</p>

<p>So if we don't want to give out our source code, somehow we need to reform our <code>fib_rec</code> a little bit and give the space to our users to insert whatever they want for each iteration. </p>

<pre><code class="ocaml">let rec fib_rec n =  
  if n &lt;= 1 then 1
  else fib_rec (n-1) + fib_rec (n-2)
</code></pre>

<p>Have a look at the above <code>fib_rec</code> carefully again, we can see that the logic of <code>fib_rec</code> is already determined during the binding, it is the <code>fib_rec</code>s inside that control the iteration. What if we rename the <code>fib_rec</code>s within the body to be <code>f</code> and add it as an argument?</p>

<pre><code class="ocaml">let fib_norec f n =  
  if n &lt;= 1 then 1
  else f (n-1) + f (n-2)

(* we actually should now change the name of fib_norec 
   to something like fib_alike_norec as it is not necessarily 
   doing fibonacci anymore, depending on f *)
</code></pre>

<p>So now <code>fib_norec</code> won't automatically repeat unless <code>f</code> tells it to. Moreover, <code>fib_norec</code> becomes a pattern which returns <code>1</code> when <code>n</code> is <code>&lt;= 1</code> otherwise <code>add</code> <code>f (n-1)</code> and <code>f (n-2)</code>. As long as you think this pattern is useful for you, you can inject your own logic into it by providing your own <code>f</code>.</p>

<p>Going back to the printing requirement, a user can now build its own version of <code>fib_rec_with_trace</code> like this:</p>

<pre><code class="ocaml">let rec fib_rec_with_trace n =  
  Printf.printf "now fibbing %d\n" n; 
  fib_norec fib_rec_with_trace n
</code></pre>

<blockquote>
  <p>Untying the recusive knot is a functional design pattern. It turns the recursive part inside the body into a new parameter <code>f</code>. In this  way, it breaks the iteration and turns a recursive function into a pattern where new or additional logic can be injected into via <code>f</code>. </p>
</blockquote>

<p><img src="http://typeocaml.com/content/images/2015/01/untie_f_rec.jpg" alt=""></p>

<p>It is very easy to untie the knots for recusive functions. You just give an addition parameter <code>f</code> and replace <code>f_rec</code> everywhere inside with it. For example, for <code>quicksort</code>:</p>

<pre><code class="ocaml">let quicksort_norec f = function  
  | [] | _::[] as l -&gt; l
  | pivot::rest -&gt;
    let left, right = partition_fold pivot rest in
    f left @ (pivot::f right)

let rec quicksort l = quicksort_norec quicksort l  
</code></pre>

<p>There are more examples in <a href="http://martinsprogrammingblog.blogspot.co.uk/2012/07/untying-recursive-knot.html">Martin's blog</a>, though they are not in OCaml. A formalized description of this topic is in the article <em>Tricks with recursion: knots, modules and polymorphism</em> from <a href="http://www.ffconsultancy.com/products/ocaml_journal/?ob26">The OCaml Journal</a>. </p>

<p>Now let's come back to <em>recursive memoize</em> problem with our new weapon. </p>

<h1 id="solverecursivememoize">Solve Recursive Memoize</h1>

<p>At first, we can require that every recursive function <code>f_rec</code> must be supplied to <code>memoize_rec</code> in the untied form <code>f_norec</code>. This is not a harsh requirement since it is easy to transform <code>f_rec</code> to <code>f_norec</code>.</p>

<p>Once we get <code>f_norec</code>, we of course cannot apply <code>memoize</code> (non-rec version) on it directly because <code>f_norec</code> now takes two parameters: <code>f</code> and <code>arg</code>. </p>

<p>Although we can create <code>f_rec</code> in the way of <code>let rec f_rec arg = f_norec f_rec arg</code>, we won't do it that straightforward here as it makes no sense to have an exactly the same recursive function. Instead, we can for now do something like <code>let f_rec_tmp arg = f_norec f arg</code>. </p>

<p>We still do not know what <code>f</code> will be, but <code>f_rec_tmp</code> is non-recursive and we can apply <code>memoize</code> on it: <code>let f_rec_tmp_memo = memoize f_tmp</code>.  </p>

<p><code>f_rec_tmp_memo</code> now have the logic of <code>f_norec</code> and the ability of memoization. If <code>f</code> can be <code>f_rec_tmp_memo</code>, then our problem is solved. This is because <code>f</code> is inside <code>f_norec</code> controlling the iteration and we wished it to be memoized.</p>

<p>The magic that can help us here is <strong>making <code>f</code> mutable</strong>. Because <code>f</code> needs to be known in prior and <code>f_rec_tmp_memo</code> is created after, we can temporarily define <code>f</code> as a trivial function and later on after we create <code>f_rec_tmp_memo</code>, we then change <code>f</code> to <code>f_rec_tmp_memo</code>. </p>

<p>Let's use a group of bindings to demonstrate:</p>

<pre><code class="ocaml">(* trivial initial function and it should not be ever applied in this state *)
let f = ref (fun _ -&gt; assert false)

let f_rec_tmp arg = f_norec !f arg

(* memoize is the simple non-rec version *)
let f_rec_tmp_memo = memoize f_rec_tmp

(* the later substitution made possible by being mutable *)
f := f_rec_tmp_memo
</code></pre>

<p>The final code for <code>memoize_rec</code> is:</p>

<pre><code class="ocaml">let memo_rec f_norec =  
  let f = ref (fun _ -&gt; assert false) in
  let f_rec_memo = memoize (fun x -&gt; f_norec !f x) in
  f := f_rec_memo;
  f_rec_memo
</code></pre>]]></description><link>http://typeocaml.com/2015/01/25/memoize-rec-untying-the-recursive-knot/</link><guid isPermaLink="false">37e5e68e-9c9c-4116-b952-abea9b981699</guid><category><![CDATA[recursion]]></category><category><![CDATA[memoize]]></category><category><![CDATA[untying the recursive knot]]></category><category><![CDATA[memoize recursive]]></category><dc:creator><![CDATA[Jackson Tale]]></dc:creator><pubDate>Sun, 25 Jan 2015 13:22:15 GMT</pubDate></item><item><title><![CDATA[Mutable]]></title><description><![CDATA[<p><img src="http://typeocaml.com/content/images/2015/01/mutable_2.jpg#hero" alt="mutable"></p>

<p>While OCaml is a functional programming language and emphasises pure functional style, it allows <em>mutable</em> (variables and values) and hence imperative programming style. The reason is said in <a href="https://realworldocaml.org/v1/en/html/imperative-programming-1.html">Real World OCaml</a>:</p>

<blockquote>
  <p>Imperative code is of fundamental importance to any practical programming language, because real-world tasks require that you interact with the outside world, which is by its nature imperative. Imperative programming can also be important for performance. While pure code is quite efficient in OCaml, there are many algorithms that can only be implemented efficiently using imperative techniques.</p>
</blockquote>

<p>How to write imperative code in OCaml has been well introduced in both <a href="http://caml.inria.fr/pub/docs/manual-ocaml-4.02/coreexamples.html#sec12">OCaml's documentation and user's manual</a> and <a href="https://realworldocaml.org/v1/en/html/imperative-programming-1.html">Real World OCaml</a>. The imperative logic flow is very similar as in other imperative languages. For example, we can write an OCaml <em>binary search</em> like this:</p>

<pre><code class="ocaml">let binary_search a x =  
  let len = Array.length a in
  let p = ref 0 and q = ref (len-1) in
  let loc = ref None in
  while !p &lt;= !q &amp;&amp; !loc = None &amp;&amp; !p &gt;= 0  &amp;&amp; !q &lt; len do
    let mi = (!p + !q) / 2 in
    if x = a.(mi) then loc := Some mi
    else if x &gt; a.(mi) then p := mi + 1
    else q := mi - 1
  done;
  !loc
</code></pre>

<p><em>Mutable</em> or <em>imperative</em> could be a snake. People, who are <em>forced</em> to use OCaml (for work or course assignments) <em>while they are not yet convinced by the potential functional power</em>, may be happy when they know stuff can be written like in Java. They may also intend to (secretly) write imperative code in OCaml as much as possible to just get things done. </p>

<p>It sounds bad and it indeed is. What is the point to code in a heavily imperative way with a functional programming language?</p>

<p>However, I won't be worried even if one does that, because I know it is just the initial avoidance and it won't last long. Why? Because writing imperative code is a bit troublesome anyway. Let's revisit the <code>binary_search</code> we wrote before.</p>

<p>You can see that nothing is straightforward there. </p>

<ol>
<li>When we define a mutable variable, we have to use <code>ref</code>;  </li>
<li>When we get the value out, we have to use <code>!</code> everywhere;  </li>
<li>When we assign a value, we can't forget <code>:</code> before <code>=</code>;  </li>
<li>We even need to add <code>.</code> before <code>()</code> when we access arrays. </li>
</ol>

<p>Even after we finish the function, it appears quite verbose and a little bit uncomfortable to read, right? This is why I am sure in longer term, one may give up imperative style, just truly learn the functional style and eventually understand OCaml's beautiful side. </p>

<p>So if we will not / should not write everything imperatively, when to leverage the benefits from <em>mutable</em>?</p>

<h1 id="whenperformancerequiresit">When performance requires it</h1>

<p>In order to manipulate a sequence of elements, we noramlly will use <code>array</code> in imperative languages; however, in pure functional language, we prefer <code>list</code> as it is immutable. </p>

<p>The best thing <code>array</code> offers us is the <em>O(1)</em> speed in accessing an element via its index. But we lose this advantage if using <code>list</code>, i.e.,  we have to do a linear scan, which is <code>O(n)</code>, to get the <code>ith</code> value. Sometimes it would be too slow. To demonstrate this, let's have a look at the problem of <em>shuffle</em>:</p>

<blockquote>
  <p>Given a sequence, randomize the order of all the elements inside. </p>
</blockquote>

<p>A typical algorithm for <em>shuffle</em> can be:</p>

<ol>
<li><code>i</code> initially is <code>0</code> and <code>len</code> is the length of the sequence.  </li>
<li>Randomly generate an integer <code>r</code> within <code>[i, len)</code>.  </li>
<li>Swap the element at <code>i</code> and the one at <code>r</code>.  </li>
<li>Increase <code>i</code> for next targeting element.  </li>
<li>Repeat from step 2. </li>
</ol>

<p>If we use <code>list</code> in OCaml, then we will have:</p>

<pre><code class="ocaml">let rm_nth n l =  
  let rec aux acc i = function
    | [] -&gt; List.rev acc
    | _::tl when i = n -&gt; List.rev_append acc tl
    | x::tl -&gt; aux (x::acc) (i+1) tl
  in 
  aux [] 0 l

(* a slight modification when using list.
   we do not swap, instead, we remove the element from the randomised index 
   and put it to the new list.
*)
let shuffle l =  
  Random.self_init();
  let len = List.length l in
  let rec aux i acc l =
    if i &lt; len then
      let r = Random.int (len - i) in
      aux (i+1) (List.nth l r ::acc) (rm_nth r l)
    else acc
  in
  aux 0 [] l
</code></pre>

<p>We have to scan the list twice in each iteration: once to get the element at the randomised index <code>r</code> and once to remove it. Totally we have <code>n</code> iterations, thus, the time complexity is <em>O(n^2)</em>. </p>

<p>If we use <code>array</code>, then it is much faster with time complexity of <em>O(n)</em> as locating an element and swapping two elements in array just cost <em>O(1)</em>.</p>

<pre><code class="ocaml">let swap a i j =  
  let tmp = a.(i) in
  a.(i) &lt;- a.(j);
  a.(j) &lt;- tmp

let shuffle_array a =  
  Random.self_init();
  let len = Array.length a in
  for i = 0 to len-1 do
    let r = i + Random.int (len - i) in
    swap a i r
  done
</code></pre>

<p>In addition to <code>array</code>, some other imperative data structures can also improve performance. For example, the <code>Hashtbl</code> is the traditional <code>hash table</code> with <code>O(1)</code> time complexity. However, the functional <code>Map</code> module uses <em>AVL</em> tree and thus provides <code>O(logN)</code>. If one really cares about such a difference, <code>Hashtbl</code> can be used with higher priority.</p>

<p>Note that we <em>should not use potential performance boost as an excuse</em> to use imperative code wildly in OCaml. In many cases, functional data structures and algorithms have similar performance, such as the <em>2-list</em> based <a href="http://www.cs.cornell.edu/Courses/cs3110/2014sp/recitations/7/functional-stacks-queues-dictionaries-fractions.html">functional queue</a> can offer us amortised <code>O(1)</code>.</p>

<h1 id="whenweneedtoremembersomething">When we need to remember something</h1>

<p>Constantly creating new values makes functional programming safer and logically clearer, as <a href="http://typeocaml.com/2015/01/02/immutable/">discussed previously</a>. However, occasionally we don't want everything to be newly created; instead, we need a mutable <em>object</em> that stays put in the memory but can be updated. In this way, we can remember values in a single place.</p>

<blockquote>
  <p>Write a function that does <code>x + y * z</code>. It outputs the correct result and in addition, prints how many times it has been called so far.</p>
</blockquote>

<p>The <code>x + y * z</code> part is trivial, but the later recording the times of calls is tricky. Let's try to implement such a function in pure functional style first.</p>

<pre><code class="ocaml">(* pure functional solution *)
let f x y z last_called_count =  
  print_int (last_called_count+1);
  x + y * z, last_called_count + 1
</code></pre>

<p>The code above can roughly achieve the goal. However, it is not great. </p>

<ol>
<li>It needs an additional argument which is meant to be the most recent count of calls. The way could work but is very vulnerable because it accepts whatever integer and there is no way to constrain it to be the real last count.  </li>
<li>It has to return the new call count along with the real result</li>
</ol>

<p>When a user uses this function, he / she will feel awkward. <code>last_called_count</code> needs to be taken care of very carefully in the code flow to avoid miscounting. The result returned is a tuple so pattern matching is necessary to obtain the real value of <code>x + y * z</code>. Also again, one need to somehow remember the new call count so he / she can supply to the next call.</p>

<p>This is where imperative programming comes to help:</p>

<pre><code class="ocaml">(* with help of imperative programming.
   note that the function g can be anonymous.*)
let f =  
  let countable_helper () =
    let called_count = ref 0 in
    let g x y z = 
      called_count := !called_count + 1;
      print_int !called_count;
      x + y * z
    in
    g
  in 
  countable_helper()
</code></pre>

<p><code>countable_helper</code> is a helper function. If it is called, it first creates a mutable <code>called_count</code> and then pass it to <code>g</code>. Because <code>called_count</code> is mutable, so <code>g</code> can freely increase its value by <code>1</code>. Eventually <code>x + y * z</code> is done after printing <code>called_count</code>. <code>g</code> is returned to f as it is the result of <code>countable_helper()</code>, i.e., <code>f</code> is <code>g</code>. </p>

<h1 id="whenweneedlatersubstitution">When we need later substitution</h1>

<p>I found this interesting case from <a href="https://realworldocaml.org/v1/en/html/imperative-programming-1.html#memoization-and-dynamic-programming">The chapter for imperative programming in Real World OCaml</a> and it is about <em>memoize</em>. In this section, we borrow contents directly from the book but will emphasise <em>the substitution</em> part.  </p>

<p>Python developers should be quite familiar with the <code>memoize</code> decorator . Essentially, it makes functions remember the <em>argument, result</em> pairs so that if the same arguments are supplied again then the stored result is returned immediately without repeated computation.</p>

<p>We can write <code>memoize</code> in OCaml too:</p>

<pre><code class="ocaml">(* directly copied from Real World OCaml, does not use anonymous function *)
let memoize f =  
  let table = Hashtbl.Poly.create () in
  let g x = 
    match Hashtbl.find table x with
    | Some y -&gt; y
    | None -&gt;
      let y = f x in
      Hashtbl.add_exn table ~key:x ~data:y;
      y
  in
  g
</code></pre>

<p>It uses <code>Hashtbl</code> as the imperative storage box and the mechanism is similar as our previous example of <em>call count</em>.</p>

<p>The fascinating bit comes from the fact that this <code>memoize</code> cannot handle recursive functions. If you don't believe it, let's try with the <em>fibonacci</em> function:</p>

<pre><code class="ocaml">let rec fib n =  
  if n &lt;= 1 then 1 else fib(n-1) + fib(n-2)

let fib_mem = memoize fib  
</code></pre>

<p>Hmmm...it will compile and seems working. Yes, <code>fib_mem</code> will return correct results, but we shall have a closer look to see whether it really remembers the <em>argument, result</em> pairs. So what is <code>fib_mem</code> exactly? By replacing <code>f</code> with <code>fib</code> inside <code>memoize</code>, we get:</p>

<pre><code class="ocaml">(* not proper ocaml code, just for demonstration purpose *)

fib_mem is actually  
  match Hashtbl.find table x with
  | Some y -&gt; y
  | None -&gt;
    let y = fib x in (* here is fib *)
    Hashtbl.add_exn table ~key:x ~data:y;
    y
</code></pre>

<p>So inside <code>fib_mem</code>, if a new argument comes, it will call <code>fib</code> and <code>fib</code> is actually not memoized at all. What does this mean? It means <code>fib_mem</code> may eventually remember the new argument and its result, but will never remember all the arguments and their results along the recusive way.</p>

<p>For example, let's do <code>fib_mem 5</code>.</p>

<ol>
<li><code>5</code> is not in the Hashtbl, so <code>fib 5</code> is called.  </li>
<li>According to the definition of <code>fib</code>, <code>fib 5 = fib 4 + fib 3</code>, so now <code>fib 4</code>.  </li>
<li><code>fib 4 = fib 3 + fib 2</code>, no problem, but look, <code>fib 3</code> will be done after <code>fib 4</code> finishes.  </li>
<li>Assuming <code>fib 4</code> is done, then we go back to the right hand side of the <code>+</code> in point 2, which means we need to do <code>fib 3</code>.  </li>
<li>Will we really do <code>fib 3</code> now? Yes, unfortunately. Even though it has been done during <code>fib 4</code>, because <code>fib</code> is not memoized.</li>
</ol>

<p>To solve this problem, we need <em>the substitution</em> technique with the help of imperative programming.</p>

<h2 id="anattractivebutwrongsolution">An attractive but WRONG solution</h2>

<p>When I read the book for the first time, before continuing for the solution of memoized fib, I tried something on my own.</p>

<p>So the problem is the <code>f</code> inside <code>memoize</code> is not memoized, right? How about we make that that <code>f</code> mutable, then after we define <code>g</code>, we give <code>g</code> to <code>f</code>? Since <code>g</code> is memoized and <code>g</code> is calling <code>g</code> inside, then the whole thing would be memoized, right?</p>

<pre><code class="ocaml">let mem_rec_bad f =  
  let table = Hashtbl.Poly.create () in
  let sub_f = ref f in
  let g x = 
    match Hashtbl.find table x with
    | Some y -&gt; y
    | None -&gt;
      let y = !sub_f x in
      Hashtbl.add_exn table ~key:x ~data:y;
      y
  in
  sub_f := g;
  g
</code></pre>

<p>It can pass compiler but will stackoverflow if you do <code>let fib_mem = mem_rec_bad fib;; fib_mem 5</code>. After we define <code>g</code> and replae the original value of <code>sub_f</code> with <code>g</code>, it seems fine, but What is <code>g</code> now?</p>

<pre><code class="ocaml">(* g is now actually like: *)
let g x =  
  match Hashtbl.find table x with
  | Some y -&gt; y
  | None -&gt;
    let y = g x in
    Hashtbl.add_exn table ~key:x ~data:y;
    y
</code></pre>

<p><code>g</code> will check the Hashtbl forever! And we totally lose the functionality of the original <code>f</code> and <code>g</code> becomes meaningless at all. </p>

<p>So we can't directly replace the <code>f</code> inside. Is there any way to reserve the functionality of <code>f</code> but somehow substitute some part with the memoization? </p>

<h2 id="theelegantsolution">The elegant solution</h2>

<p><strong>Updated on 2015-01-25:</strong> Please go to <a href="http://typeocaml.com/2015/01/25/memoize-rec-untying-the-recursive-knot/">Recursive Memoize &amp; Untying the Recursive Knot</a> for better explanation of recursive memoize. This following content here is not that good.</p>

<p>The answer is Yes, and we have to build a non-recusive function out of the recusive <code>fib</code>.</p>

<pre><code class="ocaml">(* directly copied from the book *)
let fib_norec f n =  
  if n &lt;= 1 then 1
  else f(n-2) + f(n-1)

let fib_rec n = fib_norec fib_rec n  
</code></pre>

<p>(I never thought before that a recursive function can be split like this, honestly. I don't know how to induct such a way and can't explain more. I guess we just learn it as it is and continue. More descriptions of it is in the book.) (<em>[1]</em>)</p>

<p>Basically, for a recursive function <code>f_rec</code>, we can </p>

<ol>
<li>change <code>f_rec</code> to <code>f_norec</code> with an additional parameter <code>f</code>  </li>
<li>replace the <code>f_rec</code> in the original body with <code>f</code>  </li>
<li>then <code>let rec f_rec parameters = f_norec f_rec parameters</code>  </li>
<li>In this way, <code>f_rec</code> will bring up <code>f_norec</code> whenever being called, so actually the recusive logic is still controled by <code>f_norec</code>. </li>
</ol>

<p>Here the important part is <code>f_norec</code> and its parameter <code>f</code> gives us the chance for correct substitution. </p>

<pre><code class="ocaml">let memo_rec f_norec =  
  let fref = ref (fun _ -&gt; assert false) in
  (* !fref below will have the new function defined next, which is
     the memoized one *)
  let h x = f_norec !fref x in 
  let f_mem = memoize h in
  fref := f_mem;
  f_mem
</code></pre>

<p>Now, <code>fref</code>'s value will become the memoized one with <code>f_norec</code>. Since <code>f_norec</code> controls the logic and real work, we do not lose any functionality but can remember every <em>argument, result</em> pairs along the recursive way.</p>

<h1 id="summary">Summary</h1>

<p>In this post, we just list out three quite typical cases where imperative programming can be helpful. There are many others, such as <a href="http://typeocaml.com/2014/11/13/magic-of-thunk-lazy/">lazy</a>, etc. </p>

<p>Moreover, one more suggestion on using imperative style is that <em>don't expose imperative interface to public if you can</em>. That means we should try to embed imperative code inside pure function as much as possible, so that the users of our functions cannot access the mutable parts. This way can let our functional code continue being pure enough while enjoying the juice of imperative programming internally.</p>

<hr>

<p><strong>[1].</strong> glacialthinker has commented <a href="http://www.reddit.com/r/ocaml/comments/2t49p9/mutable_and_when_shall_we_use_imperative/cnvryku">here</a>. This technique is called <em>untying the recursive knot</em>.</p>

<p><a href="http://en.wikipedia.org/wiki/Mystique_%28comics%29">Mystique</a> in the head image is another major character in <a href="http://en.wikipedia.org/wiki/X-Men">X-Men's world</a>. <em>She is a shapeshifter who can mimic the appearance and voice of any person with exquisite precision.</em> Similar like the <em>mutable</em> in OCaml that always sticks to the same type once being created, human is the only <em>thing</em> she can mutate to.</p>]]></description><link>http://typeocaml.com/2015/01/20/mutable/</link><guid isPermaLink="false">4e81b457-a896-4648-8eba-bcfa739af291</guid><category><![CDATA[mutable]]></category><category><![CDATA[shuffle]]></category><category><![CDATA[imperative programming]]></category><category><![CDATA[binary search]]></category><category><![CDATA[memoize]]></category><dc:creator><![CDATA[Jackson Tale]]></dc:creator><pubDate>Wed, 21 Jan 2015 01:09:42 GMT</pubDate></item><item><title><![CDATA[Immutable]]></title><description><![CDATA[<p><img src="http://typeocaml.com/content/images/2014/12/Immutable.jpg#hero" alt="immutable"></p>

<p>In <strong>pure functional programming</strong>, everything is immutable. Strings, lists, values of customised types etc cannot be changed once being created. For example, a list such as <code>[1;2;3]</code> does not have any operation that can alter its elements. If you want the stuff inside to be changed, you need to create a new list based on it. Suppose you want to change the first element of <code>[1;2;3]</code> to be <code>4</code>, then you have to <code>let new_list = 4::List.tl [1;2;3]</code> or directly <code>let new_list = [4;2;3]</code>, however, you don't have ways to do something like <code>old_list.first_element = 4</code>.  </p>

<p>If you have got used to popular imperative programming languages such C, Java, Python, etc, you may feel that things being immutable sounds quite inconvenient. Yes, maybe sometimes being immutable forces us to do more things. In the example above, if we are able to do <code>old_list.first_element = 4</code>, it seems more natural and straightforward. However, please do not overlook the power of being immutable. It provides us extra safety, and <strong>more importantly, it leads to a different paradigm - functional programming style</strong>.</p>

<p>Before we start to dive into immutables, there are two things that need to be clarified first. </p>

<h1 id="shadowing">Shadowing</h1>

<p>People who start to learn OCaml may see something, like the trivial code below, is allowed:</p>

<pre><code class="ocaml">let f x =  
  let y = 1 in
  let y = 2 in
  x * y
</code></pre>

<p>There are two <code>y</code>s and it seems that <code>y</code> has been changed from <code>1</code> to <code>2</code>. A conclusion might be made that things in OCaml are actually mutable because <code>y</code> is mutated. This conclusion is wrong. In OCaml, it is called <em>shadowing</em>. </p>

<p>Basically, the two <code>y</code>s are different. After the binding of second <code>y</code> is defined, the first <code>y</code> is still there for the time being. Just because it happens to have the same name as second <code>y</code>, it is in the shadow and can never be accessed later in the term of <a href="http://www.cs.cornell.edu/Courses/cs3110/2014sp/lectures/3/lec03.html">scope</a>. Thus we should not say <code>y</code> is mutated and in OCaml <em>variable</em> / <em>binding</em> is indeed immutable.</p>

<p><img src="http://typeocaml.com/content/images/2015/01/shadow-1.jpg#small" alt="shadowed"></p>

<h1 id="mutablevariablesandvalues">Mutable Variables and Values</h1>

<p>The concept of being <em>immutable</em> or <em>mutable</em> was introduced because we need it to help us to predict whether something's possible change would affect other related things or not. In this section, we majorly talk about <em>mutable</em> in imperative programming as clear understading of <em>what being mutable means</em> can help us appreciate <em>immutable</em> a little more.  </p>

<p>It is easy to know <em>variable</em> is mutable in imperative programming. For example, we can do <code>int i = 0;</code>, then <code>i = 1;</code> and the same <code>i</code> is mutated. Altering a variable can affect other parts in the program, and it can be demonstrated using a <em>for loop</em> example:</p>

<pre><code class="java">/* The *for* scope repeatedly access `i` 
   and `i`'s change will affect each iteration. */

for (int i = 0; i &lt; 10; i++)  
  System.out.println(i);
</code></pre>

<p>Sometimes, even if a variable is mutated, it might not affect anything, like the example (in Java) below: </p>

<pre><code class="java">int[] a = {1;2;3};  
int[] b = a;

a = {5;6;7};

/* What is b now? */
</code></pre>

<p><code>a</code> was initially <code>{1,2,3}</code>. <code>b</code> has been declared to be equal to <code>a</code> so <code>b</code> has the same value as <code>{1,2,3}</code>. <code>a</code> later on was changed to <code>{5,6,7}</code>. Should <code>b</code> be changed to <code>{5,6,7}</code> as well? Of course not, <code>b</code> still remains as <code>{1,2,3}</code>. Thus, even if <code>a</code> is mutated, <code>b</code> is not affected. This is because in this case, the <em>value</em> underneath has not been mutated. Let's modify the code a little bit:</p>

<pre><code class="java">int[] a = {1,2,3};  
int[] b = a;

a[0] = 0;

/* What is b now? */
</code></pre>

<p><code>a[0] = 0;</code> altered the first element in the underlying array and <code>a</code> would become <code>{0,2,3}</code>. Since <em>array</em> in Java is <em>mutable</em>, <code>b</code> now becomes <code>{0,2,3}</code> too as <code>b</code> was assigned the identical array as <code>a</code> had initially. So the array value being mutable can lead to the case where if a mutable value is changed somewhere, all places that access it will be affected.  </p>

<p>A <em>mutable</em> value must provide a way for developers to alter itself through bindings, such as <code>a[0] = 0;</code> is the way for arrays, i.e., via <code>a[index]</code> developers can access the array <code>a</code> by <code>index</code> and <code>=</code> can directly assign the new element at that index in the array. </p>

<p>A <em>immutable</em> value does not provide such as way. We can check immutable type <em>String</em> in Java to confirm this.</p>

<p><img src="http://typeocaml.com/content/images/2015/01/immutable_mutable-1.jpg#small" alt="immutable_mutable"></p>

<p>To summarise, when dealing with <em>mutable</em>, especially when we test our imperative code, we should not forget possible changes of both <em>variable</em> and <em>value</em>.</p>

<p><strong>Note</strong> that OCaml does support <em>mutable</em> and it is a kind of hybrid of <em>functional</em> and <em>imperative</em>. However, we really should care about the <em>functional</em> side of OCaml more. For the <em>imperative</em> style of OCaml and when to use it, the next post will cover with details.</p>

<h1 id="extrasafetyfromimmutable">Extra Safety from Immutable</h1>

<p>As described before, if a mutable variable / value is altered in one place, we need to be cautious about all other places that may have access to it. The code of altering an array in the previous section is an example. Another example is supplying a mutable value to a method as argument.</p>

<pre><code class="java">public static int getMedian(int[] a) {  
    Arrays.sort(a);
    return a[a.length/2];
}

public static void main(String[] args) {  
    int[] x = {3,4,2,1,5,9,6};
    int median = getMedian(x);

    /* x is not {3,4,2,1,5,9,6} any more */
    ...
}
</code></pre>

<p><code>getMedian</code> will sort the supplied argument and the order of the elements in <code>x</code> will be changed after the call. If we need <code>x</code> to always maintain the original order, then the above code has serious flaw. It is not that bad if it is us who wrote <code>getMedian</code>, because we can just refine the code directly. However, if <code>getMedian</code> is in a third party library, even though we still can override this method, how can we know whether other method in the same library have this kind of flaw or not? A library would be useless if we cannot trust it completely. </p>

<p>Allowing mutables also introduces troubles for threading. When multiple threads try to alter a mutable value at the same time, we sometimes can just put a locker there to restrain the access to the value, with the sacrifice of make it single-threading at that point. However, if we have to precisely control the order of altering, things get much more complicated. This is why we have hundreds of books and articles to teach how to do a great multithreading in imperative programming languages. </p>

<p>If everything is immutable, then we do not need to worry about any of those any more. When we need to alter an immutable value, we create a new value that implements the change based on the old value and the old value is kept intact. All places that need access to the original value are very safe. As an example in OCaml:</p>

<pre><code class="ocaml">(* trivial way to get median in OCaml, simply for comparison to the imperative case *)
let get_median l =  
  (* we can't sort in place, have to return a new sorted list *)
  let sorted_l = List.sort compare l in
  let len = List.length l in
  List.nth (len/2) sorted_l (* here we use our new sorted list *)

let median_mul_hd =  
  let l = [3;4;2;1;5;9;6] in
  let median = get_median l in
  median * List.hd l (* the hd of l will not be 1, but still 3 - the original hd *)
</code></pre>

<p>With immutables, the burden of cautions on unexpected modification of values are  relieved for us. Hence, for OCaml, we do not need to spend time on studying materials such as <em>Item 39: Make defensive copies when needed</em> in <a href="http://www.amazon.co.uk/Effective-Java-Edition-Joshua-Bloch/dp/0321356683">Effective Java</a>. </p>

<p><img src="http://typeocaml.com/content/images/2015/01/extra_safety-2.jpg#small" alt="extra_safety"></p>

<p>Being immutable brings extra safety to our code and helps us to avoid possibly many trivial bugs like the ones described before. However, this is not free of charge. We may feel more restrictive and lose much flexibilities (<em>[1]</em>). Moreover, because we cannot alter anything, pure functional programming forces us to adapt to a new style, which will be illustrated next. </p>

<h1 id="functionalprogrammingstyle">Functional Programming Style</h1>

<p>As mentioned in <a href="http://typeocaml.com/2014/12/04/recursion-reloaded/">Recursion Reloaded</a>, we <em>cannot</em> use loops such in pure functional programming, because <em>mutable</em> is not in functional world. Actually, there was a little misinterpretation there: it is not <em>we cannot</em> but is <em>we are not able to</em>. </p>

<p>A typical <em>while loop</em> in Java looks like this:</p>

<pre><code class="java">int i = 0;  
while ( i &lt; 10 ) {  
   ...
   i++;
}

/* note that above is the same as
   for(int i = 0; i &lt; n; i++) ... */
</code></pre>

<p>The reason that the while loop works in Java is because:</p>

<ol>
<li><code>i</code> is defined before <code>while</code> scope.  </li>
<li>We go into <code>while</code> scope and <code>i</code> continues to be valid inside.  </li>
<li>Since <code>i</code> is mutable, <code>i</code>'s change is also valid inside <code>while</code>.  </li>
<li>So we can check the same <code>i</code> again and again, and also use it repeatedly inside <code>while</code>.</li>
</ol>

<p>Are we able to do the same thing in OCaml / Functional Programming? The answer is <strong>no</strong>.If you are not convinced, then we can try to assume we were able to and <strong>fake</strong> some OCaml syntax. </p>

<pre><code class="ocaml">(* fake OCaml code *)

let i = 0 in  
while i &lt; 10 do  
  ...
  let i = i + 1 ...
end while
</code></pre>

<ol>
<li><code>i</code> is defined before <em>while</em>, no problem.  </li>
<li>Initially, <code>while</code> gets <code>i</code> for the first time and check it against <code>10</code>, no problem.  </li>
<li><code>i</code> can be used for the first time inside <code>...</code>, still no problem.  </li>
<li>Then we need to increase <code>i</code> and the problem starts.  </li>
<li>Recall that <code>i</code> is immutable in OCaml. The <code>first i</code> after <code>let</code> in <code>let i = i + 1</code> is actually new and the <code>original i</code> is shadowed.  </li>
<li>The new <code>i</code> is created within the <code>while</code> scope, so after one iteration, it is invalid any more.  </li>
<li>Thus the second time at <code>while i &lt; 10 do</code>, the original <code>i</code> would be still 0 and the loop would stuck there forever. </li>
</ol>

<p>The above attempt proves that we can't do looping in pure functional programming any more. This is why we replace it with recursion as described in <a href="http://typeocaml.com/2014/12/04/recursion-reloaded/">Recursion Reloaded</a> before. </p>

<p>Furthermore, we can see that the execution runtime in imperative programming is normally driven by mutating states (like the <em>while loop</em> gets running by changing <code>i</code>). In functional programming, however, the execution continues by creating new things and giving them to the next call / expression / function. Just like in recursion, a state needs to be changed, so we give the same function the new state as argument. This is indeed <em>the functional programming style:</em> <strong>we create and then deliver</strong>.</p>

<p>One may still think <em>imperative</em> is easier and more straightforward than <em>functional</em>. Our brain likes <em>change and forget</em>, so for <em>imperative</em>'s easiness, maybe. However, if you say <em>imperative</em> is more straightforward, I doubt it.</p>

<p>Let's temporarily forget the programming / coding part and just have a look at something at high level. </p>

<blockquote>
  <p>Suppose there is process, in which there are two states: <code>A</code> and <code>B</code>. Most importantly, <code>State A</code> can change to <code>State B</code>. Now plese close your eyes and draw a diagram for this simple process in your mind. </p>
</blockquote>

<p>Done? </p>

<p>I bet you imagined this diagram as below:</p>

<p><img src="http://typeocaml.com/content/images/2015/01/state_true.jpg#small" alt="state_true"></p>

<p>But NOT </p>

<p><img src="http://typeocaml.com/content/images/2015/01/state_false.jpg#small" alt="state_false"></p>

<p>When we were really thinking of the trivial process, there must be two separate states in our mind and an explicit arrow would be there to clearly indicate the transition. This is much more nature than imagining just one state and the two situations inside. Afterall, this is called landscape and we often need it when we design something. </p>

<p>When we start to implement it, we might think differently. We sometimes intend to use the easy way we get used to. For example, in many cases we can just use one state variable and forget <code>State A</code> after transiting to <code>State B</code> during implementation, because always remembering <code>State A</code> may be unnecessary. This difference between design and implementation are always there and we are just not aware of it or we just feel it smoother due to our imperative habit. </p>

<p>Functional programming style does not have that difference. In the above example, if we implement it in OCaml, we will do exactly the same as the upper diagram, i.e., we create <code>State A</code> and when the state needs to be changed to <code>B</code>, we create a new <code>State B</code>. This is why I say <em>functional</em> is more straightforward because it directly reflects our intuitive design. If you are not convinced still, let's design and implement the <em>quicksort</em> in both imperative and functional styles as an demonstration.</p>

<h1 id="quicksort">Quicksort</h1>

<p>Quicksort is a classic sorting algorithm. </p>

<ol>
<li>If only one or no element is there, then we are done.  </li>
<li>Everytime we select a pivot element, e.g. the first element,  from all elements that we need to sort.  </li>
<li>We compare elements with the pivot, put the <em>smaller</em> elements on its left hand side and <em>larger</em> ones on its right hand side. Note that neither <em>smaller</em>s or <em>larger</em>s need to be in order.  </li>
<li>The pivot then gets fixed.  </li>
<li>Quicksort all elements on its left.  </li>
<li>Quicksort all elements on its right. </li>
</ol>

<p>The core idea of quicksort is that we partition all elements into 3 parts: <em>smaller</em>, <em>pivot</em> and <em>larger</em> in every iteration. So <em>smaller</em> elements won't need to be compared with <em>bigger</em> elements ever in the future, thus time is saved. In addition, although we split the elements into 3 parts, <em>pivot</em> will be fixed after one iteration and only <em>smaller</em> and <em>larger</em> will be taken account into the next iteration. Hence the number of effective parts, which cost time next, is actually 2. How many times we can get <em>smaller</em> and <em>larger</em> then? <em>O(logn)</em> times, right? So at most we will have <em>O(logn)</em> iterations. Hence The time complexity of quicksort is <em>O(nlogn)</em>.</p>

<h2 id="design">Design</h2>

<p>The key part of quicksort is <em>partitioning</em>, i.e., step 2 and 3. How can we do it? Again, let's design the process first without involving any coding details. </p>

<p>Say we have some elements <code>4, 1, 6, 3, 7</code>. You don't have to write any code and you just need to manually partition them once like step 2 and 3. How will you do it in your imagination or on paper? Could you please try it now?</p>

<p>Done?</p>

<p>I bet you imagined or wrote down the flow similar as below:</p>

<p><img src="http://typeocaml.com/content/images/2015/01/quicksort-1.jpg#small" alt="quicksort"></p>

<p>The mechanism of <em>partition</em> is not complicated. We get the <em>pivot</em> out first. Then get an element out of the rest of elements one by one. For each element, we compare it with the <em>pivot</em>. If it is smaller, then it goes to the left; otherwise, goes to the right. The whole process ends when no element remains. Simple enough? I believe even for non-developers, they would mannually do the <em>partition</em> like shown in the diagram. </p>

<p>Our design of <em>partition</em> is quite finished. It is time to implement it.</p>

<h2 id="imperativeimplementation">Imperative implementation</h2>

<p>Let's first try using Java. Can we follow the design in the diagram directly? I bet not. The design assumed that the pivot <code>4</code> will have two bags (initially empty): one on its left and the other on its right. Just this single point beats Java. In Java or other imperative programming languages, normally when we sort some elements, all elements are in an array and we prefer doing things in place if we are able to. That says, for example, if we want <code>1</code> to be on the left hand side of <code>4</code>, we would use <em>swap</em>. It is efficient and the correct way when adjusting the positions of elements in an array.</p>

<p>There are a number of ways to implement <em>partition</em> in Java and here the one presented in the book of <a href="http://algs4.cs.princeton.edu/23quicksort/">Algorithms, Robert Sedgewick and Kevin Wayne</a> is briefly presented as a diagram below:</p>

<p><img src="http://typeocaml.com/content/images/2015/01/quicksort_imperative-1.jpg#small" alt="quicksort_imperative"></p>

<p>We do not have <em>smaller bag</em> or <em>larger bag</em> any more. We do not do <em>throwing element into according bag</em> either. We have to maintain two additional pointers <code>i</code> and <code>j</code>. <code>i</code> is used to indicate the next element in action. If an element is smaller than the pivot, swapping it with the pivot will put it to the left. If an element is larger, then we swap it with <code>j</code>'s element. <code>j</code> can now decrease while <code>i</code> stays put because <code>i</code> now is a new element that was just swapped from <code>j</code>. The whole process stops when <code>i &gt; j</code>. </p>

<p>As we can see, the implementation is quite different from the high level design and much more complicated, isn't it? The design just tells us <em>we get a new element out, compare it with the pivot, and put it to the left or right depending on the comparison.</em>. We cannot have such a simple summary for the implementation above. More than that, we need to pay extra attention on <code>i</code> and <code>j</code> as <strong>manipulating indices of an array is always error-prone</strong>. </p>

<p>The Java code is directly copied from <a href="http://algs4.cs.princeton.edu/23quicksort/Quick.java.html">the book</a> to here:</p>

<pre><code class="java">private static int partition(Comparable[] a, int lo, int hi) {  
        int i = lo;
        int j = hi + 1;
        Comparable v = a[lo];
        while (true) { 
            // find item on lo to swap
            while (less(a[++i], v))
                if (i == hi) break;

            // find item on hi to swap
            while (less(v, a[--j]))
                if (j == lo) break;      // redundant since a[lo] acts as sentinel

            // check if pointers cross
            if (i &gt;= j) break;

            exch(a, i, j);
        }

        // put partitioning item v at a[j]
        exch(a, lo, j);

        // now, a[lo .. j-1] &lt;= a[j] &lt;= a[j+1 .. hi]
        return j;
    }
</code></pre>

<h2 id="functionalimplementation">Functional Implementation</h2>

<p>The functional implementation fits the design perfectly and We have to thank the <em>always creating new and deliver</em> of functional programming style for that.  </p>

<ol>
<li>The design asks for two bags around the pivot and we can directly do that: <code>(left, pivot, right)</code>.  </li>
<li>The design says if an element is <em>smaller</em>, then put to the left. We can again directly do that <code>if x &lt; pivot then (x::left, pivot, right)</code>.  </li>
<li>We can also directly handle <em>larger</em>: <code>else (left, pivot, x::right)</code>. </li>
</ol>

<p>For iterations, we can just use <em>recursion</em>. The complete OCaml code for <em>partition</em> is like this:</p>

<pre><code class="ocaml">let partition pivot l =  
  (* we can actually remove pivot in aux completely.
     we put it here to make it more meaningful *)
  let rec aux (left, pivot, right) = function
    | [] -&gt; (left, pivot, right)
    | x::rest -&gt;
      if x &lt; pivot then aux (x::left, pivot, right) rest
      else aux (left, pivot, x::right) rest
  in
  aux ([], pivot, []) l (* two bags are initially empty *)
</code></pre>

<p>If you know <code>fold</code> and remove pivot during the process, then it can be even simpler:</p>

<pre><code class="ocaml">(* using the List.fold from Jane Street's core lib *)
let partition_fold pivot l =  
  List.fold ~f:(
    fun (left, right) x -&gt; 
      if x &lt; pivot then (x::left, right)
      else (left, x::right)) ~init:([], []) l
</code></pre>

<p>One we get the functional <em>partition</em>, we can write <em>quicksort</em> easily:</p>

<pre><code class="ocaml">let rec quicksort = function  
  | [] | _::[] as l -&gt; l
  | pivot::rest -&gt;
    let left, right = partition_fold pivot rest in
    quicksort left @ (pivot::quicksort right)
</code></pre>

<h2 id="summary">Summary</h2>

<p>Now we have two implementations for <em>quicksort</em>: imperative and functional. Which one is more straightforward and simpler? </p>

<p>In fact, functional style is more than just being consistent with the design: <strong>it handles data directly, instead of via any intermedia layer in between</strong>. In imperative programming, we often use array and like we said before, we have to manipulate the indices. The <em>indices</em> stand between our minds and the data. In functional programming, it is different. We use immutable list and using indices makes not much sense any more (as it will be slow). So each time, we just care the head element and often it is more than enough. This is one of the reasons why I love OCaml. Afterall, we want to deal with data and why do we need any unnecessary gates to block our way while they pretend to help us?</p>

<p>One may say imperative programming is faster as we do not need to constantly allocate memory for new things. Yes, normally array is faster than list. And also doing things in place is more effient. However, OCaml has a very good type system and a great <a href="https://realworldocaml.org/v1/en/html/understanding-the-garbage-collector.html">GC</a>, so the performance is not bad at all even if we always creating and creating. </p>

<p>If you are interested, you can do the design and imperative implementation for <em>mergesort</em>, and you will find out that we have to create new auxiliary spaces just like we would do in functional programming. </p>

<h1 id="ocamlthehybrid">OCaml - the Hybrid</h1>

<p>So far in this post, we used quite a lot of comparisons between imperative and functional to prove <em>immutable is good</em> and <em>functional programming style is great</em>. Yes, I am a fan of OCaml and believe functional programming is a decent way to do coding. However, I am not saying imperative programming is bad (I do Java and Python for a living in daytime and become an OCamler at deep night). </p>

<p><em>Imperative</em> has its glories and OCaml actually never forgets that. That's why OCaml itself is a hybrid, i.e., you can just write OCaml code in imperative style. One of the reasons OCaml reserves imperative part is that sometimes we need to remember a state in one single place. Another reason can be that we need arrays for a potential performance boost. </p>

<p>Anyhow, OCaml is still a functional programming language and we should not forget that. Especially for beginners, please do pure functional programming in OCaml as much as possible. Do not bow to your imperative habit. For the question of <em>when should I bring up imperative style in OCaml</em> will be answered in the next post <a href="http://typeocaml.com/2015/01/20/mutable/">Mutable</a>. </p>

<hr>

<p><strong>[1].</strong> </p>

<p>People enjoy flexbilities and conveniences, and that's one of the reasons why many people fancy Java and especially Python. It feels free there and we can easily <a href="http://www.amazon.co.uk/Beginning-Python-Programming-Learn-Treading-ebook/dp/B00639H0AK/">learn them in 7 days</a> and implement our ideas with them quickly. However, be aware of the double sides of being flexible and convenient. </p>

<p>When we really want to make a proper product using Java or Python, we may need to read books on <em>what not to do even though they are allowed</em> (yeah, this is a point, if we should not use something in most cases, why it is allowed at all?). We have to be very careful in many corners and 30% - 50% of the time would be spent on testing. Eventually, <em>how to write beautiful code</em> might become <em>how to test beautifully</em>. </p>

<p>OCaml and other functional programming languages are on the opposite side - they are very restrictive, but restrictions are for the great of good. For example, we cannot freely use the best excuse of <em>sorry I can't return you a valid answer</em> - <strong>return null;</strong>. Instead, we have the <em>None</em>, which is part of <em>option</em>, to explicitly tell you that nothing can be returned. The elegant reward of using <em>option</em> is that when we try to access it, <strong>we have to deal with the <em>None</em></strong>. Thus <em>NullPointerException</em> does not exist in OCaml (<em>[2]</em>). </p>

<p><img src="http://typeocaml.com/content/images/2014/12/null.jpg#small" alt="null"></p>

<p>For <em>if</em> and <em>pattern matching</em>, OCaml forces us to cover all possible cases. It sounds troublesome during coding as we sometimes know that we don't care about some cases or some cases will never happen. Yes, we may ignore those cases in our working code in Java or Python, but later do we have to consider them in testing code? Often we do, right? </p>

<p>OCaml cuts off some flexibilities. As an outcome, to achieve a goal, we have quite limited number of ways and occasionally even just one way and that way might be very tough (we will see it in later posts on functional pearls). But trust me, after mastering OCaml at a certain level and looking at the very robust OCaml code you wrote, you would appreciate OCaml and recall this slogan: </p>

<blockquote>
  <p>"Less is more" - Andrea del Sarto, Robert Browning. </p>
</blockquote>

<p><strong>[2].</strong> "Options are important because they are the standard way in OCaml to encode a value that might not be there; there's no such thing as a NullPointerException in OCaml. " - <a href="https://realworldocaml.org/v1/en/html/a-guided-tour.html">Chapter 1 in Real World Ocaml</a></p>

<p><strong>Ps.</strong></p>

<p><a href="http://en.wikipedia.org/wiki/Wolverine_%28character%29">Wolverine</a> in the head image of this post is a major character in <a href="http://en.wikipedia.org/wiki/X-Men">X-Men's world</a>. Since the regeneration of his body cells is super fast, he will not be permernantly hurt or age. Just like Wolverine, <em>immutables</em> in OCaml will not change once created. However, unlike Wolverine, they can not be immortals because many of them would be recycled by the garbage collector at some point during the runtime.</p>]]></description><link>http://typeocaml.com/2015/01/02/immutable/</link><guid isPermaLink="false">d1f78d26-8d6e-451a-8237-1077c392815e</guid><category><![CDATA[functional programming style]]></category><category><![CDATA[quicksort ]]></category><category><![CDATA[execution model ]]></category><category><![CDATA[algorithm]]></category><dc:creator><![CDATA[Jackson Tale]]></dc:creator><pubDate>Fri, 02 Jan 2015 15:52:41 GMT</pubDate></item><item><title><![CDATA[Become a BST Ninja - Genin Level]]></title><description><![CDATA[<p><img src="http://typeocaml.com/content/images/2014/12/bst_ninja.jpg#hero" alt="bst_ninja"></p>

<p>Binary Search Tree (<em>BST</em>) is one of the most classic data structures. The definition for its structure is shown as below:</p>

<ul>
<li>It consists of <em>Nodes</em> and <em>Leaves</em>.</li>
<li>A <em>Node</em> has a child bst on the <em>left</em> side, a <em>key</em> (, a <em>data</em>), and a child bst on the <em>right</em> side. Note here <strong>a node's left or right child is not a node, instead, is indeed another binary search tree</strong>. </li>
<li>A <em>Leaf</em> has nothing but act only as a STOP sign. </li>
</ul>

<pre><code class="ocaml">type 'a bst_t =  
  | Leaf
  | Node of 'a bst_t * 'a * 'a bst_t (* Node (left, key, right) *)
(* a node may also carry a data associated with the key. 
   It is omitted here for neater demonstration *)
</code></pre>

<p>The important feature that makes BST unique is </p>

<ul>
<li>for any node
<ul><li>all keys from its <strong>left child are smaller</strong> than its own key</li>
<li>all keys from its <strong>right child are bigger</strong> (assumming keys are distinct)</li></ul></li>
</ul>

<p>And here is an example of BST:</p>

<p><img src="http://typeocaml.com/content/images/2014/12/example_bst.jpg" alt="example_bst"></p>

<p>Instead of continuing to present the basics of BST, this post will now focus on how to attack BST related problems with the most powerful weapon: <strong>Recursion</strong>. </p>

<h1 id="recursiononbst">Recursion on BST</h1>

<p>From <a href="http://typeocaml.com/2014/12/04/recursion-reloaded/">Recursion Reloaded</a>, we know that one way to model recursion is:</p>

<ol>
<li>Assume we already got a problem solver: <code>solve</code>.  </li>
<li>Don't think about what would happen in each iteration.  </li>
<li><strong>Split</strong> the problem to smallers sizes (<em>N = N1 + N2 + ...</em>).  </li>
<li>Solve those smaller problems like <code>solve N1</code>, <code>solve N2</code>, ... Here is the tricky part: still, we do not know or care what are inside <code>solve</code> and how <code>f</code> would do the job, we just believe that it will return the correct results.  </li>
<li>Now we have those results for smaller problems, how to <strong>wire</strong> them up to return the result for <em>N</em>? This is the ultimate question we need to answer.  </li>
<li>Of course, we do not forget the <strong>STOP sign</strong> for some edge cases.  </li>
<li>Together with point 5 and 6, we get our <code>solve</code>.</li>
</ol>

<p>A good thing coming from BST is that the <em>split</em> step has been done already, i.e., a BST problem can be always divided into <em>left child</em>, <em>root</em>, and <em>right child</em>.</p>

<p>Thus if we assume we already got <code>solve</code>, we just need to solve <em>left</em> and / or solve <em>right</em>, then do something with <em>root</em>, and finally wire all outcomes to obtain the final result. Again, we should of course never forget the STOP sign and in BST, usually it is the <em>Leaf</em>, i.e., we need to ask ourselves what if the BST is a <em>Leaf</em>. </p>

<p>The thinking flow is illustrated as the diagram below.</p>

<p><img src="http://typeocaml.com/content/images/2014/12/left_root_right-4.jpg" alt="solve"></p>

<p>Before we start to look at some problems, note that in the diagram above or <a href="http://typeocaml.com/2014/12/04/recursion-reloaded/">Recursion Reloaded</a>, we seem to always solve <em>both left and right</em>, or say, <em>all sub-problmes</em>. It is actually not necessary. For BST, sometimes <em>either left or right</em> is enough. Let's have a look at this case first. </p>

<h1 id="eitherleftorright">Either Left or Right</h1>

<p>Our starter for this section is the simplest yet very essential operation: <strong>insert</strong> a key to a BST.</p>

<h2 id="insert">Insert</h2>

<p>From the definition of BST, we know the basic rule is that if the new key is smaller than a root, then it belongs to the root's left child; otherwise, to the root's right child. Let's follow the modelling in the previous diagram to achieve this.</p>

<ol>
<li>We assume we already got <code>insert key bst</code>  </li>
<li>We know the problem can be split into <em>left</em>, <em>root</em>, and <em>right</em>.  </li>
<li>Because a new key can go either left or right, so we need to <em>deal_with root</em> first, i.e., compare the new key and the key of the root.  </li>
<li>Directly taken from the rule of BST, if the new key is smaller, then we need to <em>solve left</em> thus <code>insert key left</code>; otherwise <code>insert key right</code>.  </li>
<li>What if we get to a <em>Leaf</em>? It means we can finally place our new key there as a new <em>Node</em> and of course, at this moment both children of the new <em>Node</em> are <em>Leaves</em>.</li>
</ol>

<p><img src="http://typeocaml.com/content/images/2014/12/insert-2.jpg" alt="insert"></p>

<p>Note that the BST type in OCaml we defined early on is pure functional, which means every time we need to update something, we have to create new. That's why in the diagram, even if we just insert x to left or right, we need to construct a new <em>Node</em> because we are updating the left child or the right one. The code is shown as below.</p>

<pre><code class="ocaml">let rec insert x = function  
  | Leaf -&gt; Node (Leaf, x, Leaf) (* Leaf is a STOP *)
  | Node (left, k, right) -&gt;
    if x &lt; k then Node (insert x left, k, right) (* if x is smaller, go left *)
    else Node (left, k, insert x right) (* otherwise, go right *)
</code></pre>

<h2 id="member">Member</h2>

<p><code>member</code> is to check whether a given key exists in the BST or not. It is very similar to <code>insert</code>. There are three differences:</p>

<ol>
<li>When <em>dealing with root</em>, we need to see whether the given key equals to the root's key or not. If yes, then we hit it.  </li>
<li><code>member</code> is a readonly function, so we directly solve <em>left</em> or <em>right</em> without constructing new <em>Node</em>.  </li>
<li>If arriving at a <em>Leaf</em>, then we have nowhere to go any more and it means the given key is not in the BST.</li>
</ol>

<pre><code class="ocaml">let rec mem x = function  
  | Leaf -&gt; false
  | Node (left, k, right) -&gt;
    if x &lt; k then mem x left
    else if x = k then true
    else mem x right
</code></pre>

<h1 id="bothleftandright">Both Left and Right</h1>

<p>Usually when we need to retrieve some properties of a BST or possibly go through all nodes to get an answer, we have to solve both children. However, the modelling technique does not change. </p>

<h2 id="height">Height</h2>

<p>Recall from <a href="http://typeocaml.com/2014/11/26/height-depth-and-level-of-a-tree/">Some properties of a tree</a>, the height of a tree is the number of edges that the longest path (from the root to a leaf) has. From this definition, it seems easy to get the height. We simply try to find all possible paths from root and for each path we record its number of edges. The answer will be the max of them. It sounds straightforward, but if you really try to write the code in this way, I bet the code would be a bit messy. Honestly, I never wrote in this way and I will never do that.</p>

<p>Another way is to think recursively. First let analyse a little bit about the longest path matter.</p>

<p><img src="http://typeocaml.com/content/images/2014/12/height.jpg#small" alt="height"></p>

<p>As we can see from the above diagram, <em>Root</em> has two edges: one to <em>Left</em> and the other to <em>Right</em>. So whatever the longest path from <em>Root</em> might be, it must pass either <em>Left</em> or <em>Right</em>. If we somehow could obtain the longest path from the root of <em>Left</em> and the longest path from the root of <em>Right</em>, the longest path from <em>Root</em> should be the bigger one of the two paths, right?</p>

<p>Let's now assume we already got <code>height</code> and it will return the height of a BST. Then we can obtain <code>h_left</code> and <code>h_right</code>. The answer is what is the <code>h</code> (height of <em>Root</em>)? Note that the height implies the longest path already (that's the definition). So from the paragraph above, What we need to do is getting <code>max h_left h_right</code>. Since <em>Root</em> has an edge to either child, <code>h = 1 + max h_left h_right</code>.</p>

<p>Don't forget the <em>STOP</em> sign: the height of a Leaf is 0.</p>

<pre><code class="ocaml">let rec height = function  
  | Leaf -&gt; 0
  | Node (left, _, right) -&gt; 1 + max (height left) (height right)
</code></pre>

<p>Simple, isn't it?</p>

<h2 id="keysatacertaindepth">Keys at a certain depth</h2>

<p>So far, it seems our hypothetic <code>solve</code> function takes only the sub-probem as parameter. In many cases this is not enough. Sometimes we need to supply <strong>more arguments</strong> to help <code>solve</code>. For example, in the problem of retriving all keys at a certain depth definitely needs <em>current depth</em> information.</p>

<p><img src="http://typeocaml.com/content/images/2014/12/depth-1.jpg#small" alt="depth"></p>

<p>Only with the help of <code>current_depth</code>, the <em>Root</em> can know whether it belongs to the final results. </p>

<ol>
<li>If <code>current_depth = target_depth</code>, then <em>Root</em> should be collected. Also we do not continue to solve <em>Left</em> or <em>Right</em> as we know their depths will never equal to <em>target_deapth</em>.  </li>
<li>Otherwise, we need to solve both <em>Left</em> and <em>Right</em> with argument of <code>1 + current_depth</code>.  </li>
<li>Assume our <code>solve</code> is working. Then <code>solve left (1+current_depth)</code> would return a list of target nodes and so does <code>solve right (1+current_depth)</code>. We simply then concatenate two target lists.  </li>
<li>STOP sign: <em>Leaf</em> is not even a <em>Node</em>, so the result will be empty list. </li>
</ol>

<p>The code is like this:</p>

<pre><code class="ocaml">let rec from_depth d cur_d = function  
  | Leaf -&gt; []
  | Node (left, k, right) -&gt;
    if cur_d = d then [k]
    else from_depth d (cur_d + 1) left @ from_depth d (cur_d + 1) right

let all_keys_at depth bst = from_depth depth 0 bst  
</code></pre>

<h1 id="genin">Genin</h1>

<p>From <a href="http://en.wikipedia.org/wiki/Ninja">Ninja Wiki</a></p>

<blockquote>
  <p>A system of rank existed. A jōnin ("upper man") was the highest rank, representing the group and hiring out mercenaries. This is followed by the chūnin ("middle man"), assistants to the jōnin. At the bottom was the genin ("lower man"), field agents drawn from the lower class and assigned to carry out actual missions.</p>
</blockquote>

<hr>

<p><strong>Ps.</strong> </p>

<p>Some readers contacted me. They hope that maybe I can use more advanced knowledge or harder examples in my posts and the current ones might seem a little boring. I think I need to explain a bit here. </p>

<p>The general idea behind <em>Many things about OCaml</em> is not to write a cookbook for certain problems related to OCaml or be a place where quick solution is there and copy / paste sample code would do the trick. Instead, <em>Many things</em> means some important aspects in OCaml that might be overlooked, or some particular problems that can show the greatness of OCaml, or the elegant OCaml solutions for some typical data structures and algorithms, etc. As long as something are valuable and that value shows only in OCaml or Functional Programming, I would like to add them all in here one by one. </p>

<p>Fortunately or unfortunately, even though I have only limited experiences in OCaml, I found that the <em>many</em> is actually quite big. And due to this <em>many</em>, I had to make a plan to present them all in a progressive way. Topics can interleave with each other in terms of time order as we do not want to have the same food for a month. More importantly, however, all should go from simple / easy to advanced / hard. In order to present some advanced topic, we need to make sure we have a solid foundation. This is why, for example, I even produced a post for <a href="http://typeocaml.com/2014/11/26/height-depth-and-level-of-a-tree/">the properties of a tree</a> although they are so basic. This is also why I <a href="http://typeocaml.com/2014/12/04/recursion-reloaded/">reloaded recursion</a> since recursion is everywhere in OCaml. They are a kind of preparations. </p>

<p>Moreover, I believe in fundamentals. Fundamentals are normally concise and contain the true essence. But sometimes they can be easily overlooked or ignored and we may need to experience a certain number of difficult problems afterwards, then start to look back and appreciate the fundamentals.</p>

<p>The reason of using simple examples is that it makes my life easier for demonstrations. I love visualisations and one graph can be better than thousands of words. For complicated problems and solutions, it is a bit more difficult to draw a nice and clean diagram to show the true idea behind. I will try to do so later on, but even if I could achieve it in this early stage, some readers might easily get lost or confused because of the unavoidable complication of the graph. As a result, the point of grasping fundamentals might be missed. </p>

<p>Anyway, please don't worry too much. Attractive problems in OCaml are always there. For example, in my plan, I will later start to present a number (maybe 15 ~ 17) of my beloved <a href="http://www.cambridge.org/gb/academic/subjects/computer-science/programming-languages-and-applied-logic/pearls-functional-algorithm-design">Functional Pearls</a> in OCaml and if you are really chasing for some awesomeness, I hope they would satisfy you.</p>]]></description><link>http://typeocaml.com/2014/12/19/how-to-become-a-bst-ninja-genin/</link><guid isPermaLink="false">d1c3aac1-465e-4346-8488-a34426eb7998</guid><category><![CDATA[binary search tree]]></category><category><![CDATA[data structure]]></category><category><![CDATA[ninja]]></category><category><![CDATA[recursion]]></category><dc:creator><![CDATA[Jackson Tale]]></dc:creator><pubDate>Fri, 19 Dec 2014 12:28:00 GMT</pubDate></item><item><title><![CDATA[Recursion Reloaded]]></title><description><![CDATA[<p><img src="http://typeocaml.com/content/images/2014/12/infinity-cubes-room.jpg#hero" alt="recursion_reloaded"></p>

<p>One essential of computer programming is <em>repeating some operations</em>. This repetition has two forms: <em>for / while loop</em> and <em>recursion</em>. </p>

<p><strong>Loop</strong></p>

<ul>
<li>We directly setup a boundary via <em>for</em> or <em>while</em>.</li>
<li>Certain conditions change inside the boundary.</li>
<li>And operations are executed based on the changing conditions.</li>
<li>It ends when hitting the boundary.</li>
</ul>

<p>if asked to write the <code>sum</code> method in Java, it might be more intuitive to have this code:</p>

<pre><code class="java">/* Java */
public int sum(int[] a) {  
  int s = 0;
  for (int i = 1; i &lt;= n; i++)
    s += a[i];
  return s
}
</code></pre>

<p><strong>Recursion</strong></p>

<ul>
<li>We write a function for the operations that need to be repeated.</li>
<li>The repetition is achieved by invoking the function inside itself. </li>
<li>We may not specify an explicit boundary, yet we still need to set a STOP sign inside the function to tell it when to stop invoking itself.</li>
<li>It ends when hitting the STOP sign.</li>
</ul>

<p>The recursive <code>sum</code> in OCaml can look like this:</p>

<pre><code class="ocaml">(* OCaml *)
let sum = function  
  | [] -&gt; 0 (*STOP sign*)
  | hd::tl -&gt; hd + sum tl
</code></pre>

<p><strong>loop or recursion?</strong></p>

<p>In imperative programming, developers may use <em>loop</em> more often than recursion as it seems to be more straightforward. </p>

<p>However, in functional programming, we almost (<em>[1]</em>) cannot do <em>loop</em>, and <em>recursion</em> is our only option. The major reason is that <em>loop</em> always needs to maintain mutable states inside the clause to change the conditions or pass intermediate results through iterations. Unfortunately, in functional programming, mutables are not allowed (<em>[2]</em>) and also intermediates must be passed via function calls not state changing. </p>

<p>So, if we really wish to get into the OCaml world, we have to get used to recursion. If you feel a bit hard, then this post is supposed to help you a little bit and show you the lovely side of recursion. </p>

<h1 id="doyoudislikerecursion">Do you dislike recursion?</h1>

<p>Honestly, I hated recursion in the beginning. In order to <strong>write a recursive function</strong> or <strong>validate one's correctness</strong>, I thought I had to always somehow simulate the execution flow in my head and imagine divings into one level after another and every time when I did that, my brain felt a bit lost after some levels and sometimes I had to use pen &amp; paper. </p>

<p>This pain is natural. Human's brain feels much more comfortable on linear tasks than recursive ones. For example, if we are asked to finish the flow of first finish <em>task-1</em> -> <em>task-2</em> -> <em>task-3</em> -> <em>task-4</em> -> <em>done</em>, it seems concise and easy. On the other hand, if we are asked to finish <em>task-1</em>, inside which we need to finish <em>task-2</em> and <em>task-3</em>, and inside <em>task-2</em> we need to finish <em>task-4</em> and <em>task-5</em>, and inside <em>task-3</em> we need...(<em>[3]</em>), our brain may not that happy, does it? </p>

<p>What is the difference between these two cases? </p>

<p>In the first case, when we do <em>task-1</em>, we do not need to care about <em>task-2</em>; and after we finish <em>task-1</em>, we just move on and forget <em>task-2</em>. Thus, we just focus and remember one thing at one time. </p>

<p>In the second case, when do do <em>task-1</em>, we not only need to foresee a bit on <em>task-2</em> and <em>task-3</em>, but also can't forget <em>task-1</em>; and we need to still keep <em>task-2</em> in mind after we begin <em>task-4</em>...</p>

<p>So the difference is very obvious: we remember / track more things in case 2 than in case 1. </p>

<p>Let's investigate this difference further in the paradigm of the two different <code>sum</code> functions written early.</p>

<h2 id="linearway">Linear way</h2>

<p>Summing [9;14;12;6;], what will we do? </p>

<ol>
<li>We will do <code>9 + 14</code> first, we get <code>23</code> and we put the <code>23</code> somewhere, say, place <code>S</code>.  </li>
<li>Next number is <code>12</code>, then we check <code>S</code>, oh it is <code>23</code>, so we do <code>23 + 12</code> and get <code>35</code>.  </li>
<li>Now, we do not need the previous result <code>23</code> any more and update <code>S</code> with <code>35</code>.  </li>
<li>Next one is <code>6</code>, ...</li>
</ol>

<p><img src="http://typeocaml.com/content/images/2014/12/linear.jpg#small" alt="linear"></p>

<p>If we look closer into the diagram above, we will find out that at any single step, we need to care only <code>S</code> and can forget anything happened before. For example, in step 1, we get 2 numbers from the list, calculate, store it to <code>S</code> and forget the 2 numbers; then go to step 2, we need to retrieve from <code>S</code>, get the 3rd number, then update <code>S</code> with new result and forget anything else...</p>

<p>Along the flow, we need to retrieve one number from the list at one time and forget it after done with it. We also need to remember / track <code>S</code>, but it is just a single place; even if its value changes, we do not care about its old value. In total, we just have to bear <strong>2 things</strong> in mind at all time, no matter the how big the list can be.</p>

<p>For a contrast, let's take a look at the recursive way.</p>

<h2 id="recursiveway">Recursive way</h2>

<p>If we try to analyse the recursive <code>sum</code>, we get</p>

<p><img src="http://typeocaml.com/content/images/2014/12/recursive.jpg#small" alt="recursive"></p>

<p>After we retrieve the first number, 9, from the list, we cannot do anything yet and have to continue to retrieve 14 without forgetting 9, and so on so forth. It is easy to see that we need to remember <strong>4 things</strong> (marked as red square) if we use our brain to track the flow. It might be fine if there are only 4 numbers. Yet if the list has 100 random numbers, we need to remember <strong>100 things</strong> and our brains would be fried.</p>

<p>Basically, as long as we try to simulate the complete recursive / iteration flow, we cannot avoid remembering potentially big number of things. So what is the solution to escape this pain? The answer is simple: <strong>we do not simulate</strong>. </p>

<p>Actually, for many problems that need recursion, we do not need to look into the details of recursion and we do not need to iterate the function in our heads. <strong>The trick is the way of modeling the recursion</strong>.</p>

<h1 id="recursionshouldbeloved">Recursion should be loved</h1>

<p>Let's revise the recursive <code>sum</code> function:</p>

<pre><code class="ocaml">let sum = function  
  | [] -&gt; 0 (*STOP sign*)
  | hd::tl -&gt; hd + sum tl
</code></pre>

<p>One <strong>bad way</strong> to interpret its repeatition process is </p>

<ol>
<li>We get an element out  </li>
<li>On the lefthand side of <code>+</code>, we hold it  </li>
<li>On the righthand side of <code>+</code>, we do point 1 again.  </li>
<li>After STOP, we do the plus on the previous numbers that were held, one by one</li>
</ol>

<p>This way is bad because it involves simulating the flow.</p>

<p>The <strong>good way</strong> to interpret is:</p>

<ol>
<li>Someone tells me <code>sum</code> can do the job of summing a list  </li>
<li>We don't care what exactly <code>sum</code> is doing  </li>
<li>If you give me a list and ask me to sum, then I just get the head (<code>hd</code>) out, and add it with <code>sum</code> of the rest  </li>
<li>Of course, what if the list is empty, then <code>sum</code> should return 0</li>
</ol>

<p>Unlike the bad way, this modelling has actually removed the iteration part from recursion, and been purely based on logic level: <strong>sum of list = hd + sum of rest</strong>. </p>

<p>To summary this process of modelling:</p>

<ul>
<li>I need to write a recursive function <code>f</code> to solve a problem</li>
<li>I won't think the exact steps or details inside <code>f</code></li>
<li>I just assume <code>f</code> is already there and correct</li>
<li>If the problem size is <em>N</em>, then I divide it into <em>X</em> and <em>Y</em> where <em>X + Y = N</em></li>
<li>If <code>f</code> is correct, then <code>f X</code> and <code>f Y</code> are both correct, right?</li>
<li>So to solve <code>N</code>, we just need to do <code>f X</code> and <code>f Y</code>, then think out <strong>some specific operations</strong> to wire the results together.</li>
<li>Of course, <code>f</code> should recognise STOP signs.</li>
</ul>

<p>So what we really need to do for recursion are:</p>

<ol>
<li>Think how to divid <code>N</code> to <code>X</code> and <code>Y</code>  </li>
<li>Think how to deal with the results from <code>f X</code> and <code>f Y</code> in order to get result of <code>f N</code>  </li>
<li>Set the STOP sign(s)</li>
</ol>

<p>Let's rewrite <code>sum</code> to fully demenstrate it</p>

<ol>
<li>We need to sum a list  </li>
<li>I don't know how to write <code>sum</code>, but I don't care and just assume <code>sum</code> is there  </li>
<li>a list <code>l</code> can be divid to <code>[hd]</code> + <code>tl</code>  </li>
<li>So <code>sum l = sum [hd] + sum tl</code> should make sense.  </li>
<li>Of course, STOP signs here can be two: <code>sum [] = 0</code> and <code>sum [x] = x</code>.</li>
</ol>

<pre><code class="ocaml">let sum = function  
  | [] -&gt; 0 (*STOP sign*) 
  | [x] -&gt; x (*STOP sign*)
  | hd::tl -&gt; sum [hd] + sum tl (* Logic *)
(* note sum [hd] can directly be hd, I rewrote in this way to be consistent to the modelling *)
</code></pre>

<p>I am not sure I express this high level logic based modelling clearly or not, but anyway we need more practices.</p>

<h2 id="mergetwosortedlists">Merge two sorted lists</h2>

<p>We need a <code>merge</code> function to merge two sorted lists so the output list is a combined sorted list.</p>

<h3 id="nxy">N = X + Y</h3>

<p>Because the head of the final combined list should be always min, so we care about the first elements from two lists as each is already the min inside its owner. <code>l1 = hd1 + tl1</code> and <code>l2 = hd2 + tl2</code>. </p>

<h3 id="fnwirefxfy">f N = wire (f X)  (f Y)</h3>

<p>We will have two cases here.</p>

<p>If hd1 &lt; hd2, then X = tl1 and Y = l2, then the wiring operation is just to add hd1 as the head of <code>merge X Y</code></p>

<p>If hd1 >= hd2, then X = l1 and Y = tl2, then the wiring operation is just to add hd2 as the head of <code>merge X Y</code></p>

<h3 id="stopsign">STOP sign</h3>

<p>If one of the lists is empty, then just return the other (no matter it is empty or not).</p>

<h3 id="code">Code</h3>

<p>Then it should be easy to write the code from the above modelling.</p>

<pre><code class="ocaml">let merge = function  
  | [], l | l, [] -&gt; l (*STOP sign, always written as first*) 
  | hd1::tl1 as l1, hd2::tl2 as l2 -&gt; 
    if hd1 &lt; hd2 then hd1::merge (tl1, l2)
    else hd2::merge (l1, tl2)
</code></pre>

<p>The idea can be demonstrated by the diagram below:</p>

<p><img src="http://typeocaml.com/content/images/2014/12/merge.jpg" alt="merge"></p>

<h2 id="mergesort">Mergesort</h2>

<p>Mergesort is a way to sort a list.</p>

<h3 id="nxy">N = X + Y</h3>

<p>We can split N evenly so X = N / 2 and Y = N - N / 2.</p>

<h3 id="fnwirefxfy">f N = wire (f X)  (f Y)</h3>

<p>What if we already mergesorted X and mergesorted Y? We simply <code>merge</code> the two results, right? </p>

<h3 id="stopsign">STOP sign</h3>

<p>If the list has just 0 or 1 element, we simply don't do anything but return.</p>

<h3 id="code">Code</h3>

<pre><code class="ocaml">(* split_evenly is actually recursive too
   We here just ignore the details and use List.fold_left *)
let split_evenly l = List.fold_left ~f:(fun (l1, l2) x -&gt; (l2, x::l1)) ~init:([], []) l

let rec mergesort l =  
  match l with
    | [] | hd::[] as l -&gt; l
    | _ -&gt; 
      let l1, l2 = split_evenly l in
      merge (mergesort l1) (mergesort l2)
</code></pre>

<h1 id="morerecursionswillfollow">More recursions will follow</h1>

<p>So far, all examples used in this post are quite trivial and easy. I chose these easy ones because I wish to present the idea in the simplest way. Many other recursion problems are more complicated, such as permutations, combinations, etc. I will write more posts for those.</p>

<p>One of the execellent use case of recursion is Binary Search Tree. In BST, we will see that the size of a problems is naturally split into 3. Depending on the goal, we deal with <strong>all or partial</strong> of the 3 sub-problems. I will demonstrate all these in the next post.</p>

<p>Again, remember, when dealing with recursion, don't try to follow the execution flow. Instead, focus on splitting the problem into smaller ones and try to combine the results. This is also called <em>divide and conquer</em> and actually it is the true nature of recursion. After all, no matter the size of the problem can be, it is anyway the same function that solve the cases of <code>size = 0</code>, <code>size = 1</code>, and <code>size = n &gt; 2</code>, right?</p>

<hr>

<p><strong>[1]</strong> OCaml allows imperative style, but it is not encouraged. We should use imperative programming in OCaml only if we have to.</p>

<p><strong>[2]</strong> OCaml allows mutables and sometimes they are useful in some cases like in <a href="http://typeocaml.com/2014/11/13/magic-of-thunk-lazy/">lazy</a> or <em>memorise</em>. However, in most cases, we are not encouraged to use mutables.</p>

<p><strong>[3]</strong> I already got lost even when I am trying to design this case</p>]]></description><link>http://typeocaml.com/2014/12/04/recursion-reloaded/</link><guid isPermaLink="false">225b3286-d2ca-4bfa-b98a-b1e980a91991</guid><category><![CDATA[recursion]]></category><category><![CDATA[merge]]></category><category><![CDATA[mergesort]]></category><category><![CDATA[algorithm]]></category><dc:creator><![CDATA[Jackson Tale]]></dc:creator><pubDate>Thu, 04 Dec 2014 15:44:18 GMT</pubDate></item><item><title><![CDATA[Height, Depth and Level of a Tree]]></title><description><![CDATA[<p><img src="http://typeocaml.com/content/images/2014/11/groot_tree2.jpg#hero" alt="tree"></p>

<p>This is a post on the three important properties of trees: <em>height</em>, <em>depth</em> and <em>level</em>, together with <em>edge</em> and <em>path</em>. I bet that most people already know what they are and <a href="http://en.wikipedia.org/wiki/Tree_%28data_structure%29">tree (data structure) on wiki</a> also explains them briefly. </p>

<p>The reason why I still decided to produce such a trivial page is that I will later on write a series of articles focusing on <a href="http://en.wikipedia.org/wiki/Binary_search_tree">binary search tree</a> in OCaml. The starters among them will be quite basic and related to these three properties. </p>

<p>In order to be less boring, the properties are presented in a visual way and I try to fulfill details (some might be easily overlooked) as much as possible.</p>

<h1 id="edge">Edge</h1>

<blockquote>
  <p>Edge – connection between one node to another. </p>
</blockquote>

<p><img src="http://typeocaml.com/content/images/2014/11/edge-1.jpg#small" alt="edge"></p>

<p>An example of edge is shown above between <em>A</em> and <em>B</em>. Basically, an edge is a line between two nodes, <strong>or a node and a leaf</strong>. </p>

<h1 id="path">Path</h1>

<blockquote>
  <p>Path – a sequence of nodes and edges connecting a node with a descendant.</p>
</blockquote>

<p><img src="http://typeocaml.com/content/images/2014/11/path-1.jpg#small" alt="path"></p>

<p>A path starts from a node and ends at another node or a leaf. Please don't look over the following points:</p>

<ol>
<li>When we talk about a path, it includes all nodes and all edges along the path, <em>not just edges</em>.  </li>
<li>The direction of a path is strictly from top to bottom and cannot be changed in middle. In the diagram, we can't really talk about a path from <em>B</em> to <em>F</em> although <em>B</em> is above <em>F</em>. Also there will be no path starting from a leaf or from a child node to a parent node. (<em>[1]</em>)</li>
</ol>

<h1 id="height">Height</h1>

<blockquote>
  <p>Height of node – The height of a node is the number of edges on the longest downward path between that node and a leaf.</p>
</blockquote>

<p>At first, we can see the above wiki definition has a redundant term - <em>downward</em> - inside. As we already know from previous section, path can only be downward. </p>

<p><img src="http://typeocaml.com/content/images/2014/11/height-3.jpg#small" alt="height"></p>

<p>When looking at height:</p>

<ol>
<li>Every node has height. So <em>B</em> can have height, so does <em>A</em>, <em>C</em> and <em>D</em>.  </li>
<li>Leaf cannot have height as there will be no path starting from a leaf.  </li>
<li>It is the longest path from the node <strong>to a leaf</strong>. So <em>A</em>'s height is the number of edges of the path to <em>E</em>, NOT to <em>G</em>. And its height is 3.</li>
</ol>

<p><strong>The height of the root is 1.</strong></p>

<blockquote>
  <p>Height of tree –The height of a tree is the number of edges on the longest downward path between the root and a leaf.</p>
</blockquote>

<p>So <strong>the height of a tree is the height of its root</strong>. </p>

<p>Frequently, we may be asked the question: <em>what is the max number of nodes a tree can have if the height of the tree is h?</em>. Of course the answer is $ 2^h-1 $ . When $ h = 1 $ , the number of node inside is 1, which is just the root; also when a tree has just root, the height of the root is 1. Hence, the two inductions match.</p>

<p>How about giving a height of 0? Then it means we don't have any <em>node</em> in the tree; but still we may have <em>leaf</em> inside (note that in this case we may not call it <em>root</em> of the tree as it makes not much sense). This is why in most languages, the type of a tree can be a leaf alone. </p>

<pre><code class="OCaml">type 'a bst =  
  | Leaf 
  | Node of 'a bst * 'a * 'a bst
</code></pre>

<p>Moreover, when we use $2^h-1$ to calculate the max number of nodes, leaves are not taken into account. <em>Leaf</em> is not <em>Node</em>. It carries no key or data,  and acts only like a STOP sign. We need to remember this when we deal with properties of trees.</p>

<h1 id="depth">Depth</h1>

<blockquote>
  <p>Depth –The depth of a node is the number of edges from the node to the tree's root node.</p>
</blockquote>

<p><img src="http://typeocaml.com/content/images/2014/11/depth-1.jpg#small" alt="depth"></p>

<p>We don't care about path any more when depth pops in. We just count how many edges between the targeting node and the root, ignoring directions. For example, <em>D</em>'s depth is 2.</p>

<p>Recall that when talking about height, we actually imply a baseline located at bottom. For depath, the baseline is at top which is root level. That's why we call it depth. </p>

<p>Note that <strong>the depth of the root is 0</strong>.</p>

<h1 id="level">Level</h1>

<blockquote>
  <p>Level – The level of a node is defined by 1 + the number of connections between the node and the root.</p>
</blockquote>

<p><img src="http://typeocaml.com/content/images/2014/11/level.jpg#small" alt="level"></p>

<p>Simply, <strong>level is depth plus 1.</strong></p>

<p>The important thing to remember is when talking about level, it <strong>starts from 1</strong> and <strong>the level of the root is 1</strong>. We need to be careful about this when solving problems related to level. </p>

<hr>

<p><strong>[1]</strong> Although point 2 stands, sometimes some problems may talk about paths in an arbitrary way, like <em>the path between B and F</em>. We have to live with that while deep in our hearts remembering the precise definition.</p>

<p><strong>ps.</strong> <a href="http://www.yworks.com/en/products/yfiles/yed/">yEd - Graph Editor</a> has been used to create all diagrams here.</p>]]></description><link>http://typeocaml.com/2014/11/26/height-depth-and-level-of-a-tree/</link><guid isPermaLink="false">f2793046-99a2-4652-bda6-5b385fb6eb56</guid><category><![CDATA[binary search tree]]></category><category><![CDATA[data structure]]></category><dc:creator><![CDATA[Jackson Tale]]></dc:creator><pubDate>Wed, 26 Nov 2014 22:43:46 GMT</pubDate></item><item><title><![CDATA[The Magic of Thunk - Async]]></title><description><![CDATA[<p><img src="http://typeocaml.com/content/images/2014/11/async2.jpg#hero" alt="async"></p>

<p>Currently in post-production.</p>

<p>Sorry, I still haven't finished this post. </p>

<p>As this will be the last post in the <em>magic of thunk</em> series, I really don't want to just introduce the <em>Async</em> library and its API, as <a href="https://github.com/janestreet?query=async">janestreet@github</a> and <a href="https://realworldocaml.org/v1/en/html/concurrent-programming-with-async.html">realworldocaml</a> have already done a pretty good job. </p>

<p>What I am looking for is the design of <em>Async</em> and the magic of <em>thunk</em> that hides inside its implementations. Since <em>Async</em> is sophisticated, it is a non-trivial task for me. I have to read the <a href="https://github.com/janestreet/async_kernel/tree/master/lib">source code</a> and it will take a while. </p>]]></description><link>http://typeocaml.com/2014/11/13/magic-of-thunk-async/</link><guid isPermaLink="false">7b36835a-5aa6-4173-af9e-83b9fa6ecdb7</guid><dc:creator><![CDATA[Jackson Tale]]></dc:creator><pubDate>Thu, 13 Nov 2014 23:04:59 GMT</pubDate></item></channel></rss>