<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>eric the fruitbat &#187; code</title>
	<atom:link href="http://www.cogitolingua.net/blog/category/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cogitolingua.net/blog</link>
	<description>Sounding out the Noosphere.</description>
	<lastBuildDate>Fri, 03 Feb 2012 23:40:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Where&#8217;d that null come from?</title>
		<link>http://www.cogitolingua.net/blog/2011/12/01/whered-that-null-come-from/</link>
		<comments>http://www.cogitolingua.net/blog/2011/12/01/whered-that-null-come-from/#comments</comments>
		<pubDate>Thu, 01 Dec 2011 09:48:07 +0000</pubDate>
		<dc:creator>erich</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[coding tricks]]></category>
		<category><![CDATA[NullObject pattern]]></category>

		<guid isPermaLink="false">http://www.cogitolingua.net/blog/?p=937</guid>
		<description><![CDATA[<p>One of the most annoying things that can happen to a computer programmer is the dreaded NullPointerException, or in C++, the segfault that occurs due to dereferencing a null pointer. The null pointer error has this &#8216;feature&#8217; which makes it a &#8216;pleasure&#8217; to debug: the source of the null can be arbitrarily far away from [...]]]></description>
			<content:encoded><![CDATA[<p>One of the most annoying things that can happen to a computer programmer is the dreaded <code>NullPointerException</code>, or in C++, the segfault that occurs due to dereferencing a null pointer. The null pointer error has this &#8216;feature&#8217; which makes it a &#8216;pleasure&#8217; to debug: the source of the null can be arbitrarily far away from its use. I&#8217;ve come up with an interesting technique for tracking down the source:</p>
<ol>
<li>Use the <code>NullObject</code> pattern, so that the null pointer instead points at a null-behaving object.</li>
<li>Gift all <code>NullObject</code>s with an identification number.</li>
<li>Place an assertion that stops the debugger at the point when a <code>NullObject</code> with the same Id as the one which originally caused the <code>NullPointerException</code> is constructed.</li>
</ol>
<p>That first part will likely be the trickiest to pull off. In C++ there are several issues to consider. Is the null pointer of a user-created type (<code>Thing*</code>) or built-in (<code>int*</code>)? Is it easy to introduce a constructor which automatically changes <code>Thing *t = null;</code> into <code>Thing *t = new NullThing()</code>? Can this coercion also be done for subclasses (because a null subclass pointer can be type-converted to a base class pointer before the dereference)? Is it worth trying to change all <code>Thing</code> pointers to <code>Thing</code> references, just to make sure you catch everything?</p>
<p>One final issue: this technique will only work for deterministic code. Otherwise no guarantee can be made on the issuing of Id&#8217;s within the <code>NullObject</code> constructor (easiest done with a global incrementing counter).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cogitolingua.net/blog/2011/12/01/whered-that-null-come-from/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Progress Phallus</title>
		<link>http://www.cogitolingua.net/blog/2011/09/25/the-progress-phallus/</link>
		<comments>http://www.cogitolingua.net/blog/2011/09/25/the-progress-phallus/#comments</comments>
		<pubDate>Sun, 25 Sep 2011 23:31:04 +0000</pubDate>
		<dc:creator>erich</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Fun]]></category>

		<guid isPermaLink="false">http://www.cogitolingua.net/blog/?p=775</guid>
		<description><![CDATA[<p>My friend Ray runs numerical simulations and wanted to have a decent progress bar for his code. A bit of web searching revealed some code, that takes care of this automatically. However, we thought that an ordinary progress bar is simply too conventional. We should gay it up with some ascii art into a beautiful [...]]]></description>
			<content:encoded><![CDATA[<p>My friend Ray runs numerical simulations and wanted to have a decent progress bar for his code. A bit of web searching revealed <a href="http://nakkaya.com/2009/11/08/command-line-progress-bar/">some code</a>, that takes care of this automatically. However, we thought that an ordinary progress bar is simply too conventional. We should gay it up with some ascii art into a beautiful progress phallus!</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include &lt;unistd.h&gt;</span>
<span style="color: #339900;">#include &lt;iostream&gt;</span>
<span style="color: #339900;">#include &lt;string&gt;</span>
&nbsp;
<span style="color: #0000ff;">void</span> printProgBar<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> percent<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    std<span style="color: #008080;">::</span><span style="color: #007788;">string</span> bar<span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> i <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> i <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">50</span><span style="color: #008080;">;</span> i<span style="color: #000040;">++</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>i <span style="color: #000080;">&lt;</span> <span style="color: #008000;">&#40;</span>percent<span style="color: #000040;">/</span><span style="color: #0000dd;">2</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
            bar.<span style="color: #007788;">replace</span><span style="color: #008000;">&#40;</span>i, <span style="color: #0000dd;">1</span>, <span style="color: #FF0000;">&quot;=&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>i <span style="color: #000080;">==</span> <span style="color: #008000;">&#40;</span>percent<span style="color: #000040;">/</span><span style="color: #0000dd;">2</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
            bar.<span style="color: #007788;">replace</span><span style="color: #008000;">&#40;</span>i, <span style="color: #0000dd;">1</span>, <span style="color: #FF0000;">&quot;D&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #008000;">&#123;</span>
            bar.<span style="color: #007788;">replace</span><span style="color: #008000;">&#40;</span>i, <span style="color: #0000dd;">1</span>, <span style="color: #FF0000;">&quot; &quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>percent <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">100</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;<span style="color: #000099; font-weight: bold;">\r</span>&quot;</span> <span style="color: #FF0000;">&quot;8&quot;</span> <span style="color: #000080;">&lt;&lt;</span> bar <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;@ &quot;</span><span style="color: #008080;">;</span>
        std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span>.<span style="color: #007788;">width</span><span style="color: #008000;">&#40;</span> <span style="color: #0000dd;">3</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> percent <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;%     &quot;</span> <span style="color: #000080;">&lt;&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">flush</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #008000;">&#123;</span>
        std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;<span style="color: #000099; font-weight: bold;">\r</span>&quot;</span> <span style="color: #FF0000;">&quot;8&quot;</span> <span style="color: #000080;">&lt;&lt;</span> bar<span style="color: #008080;">;</span>
        std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;D~~~~ ~~~ ~&quot;</span> <span style="color: #000080;">&lt;&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">flush</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> i<span style="color: #000080;">=</span><span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> i<span style="color: #000080;">&lt;=</span><span style="color: #0000dd;">95</span><span style="color: #008080;">;</span> i<span style="color: #000040;">+</span><span style="color: #000080;">=</span><span style="color: #0000dd;">10</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        sleep<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        printProgBar<span style="color: #008000;">&#40;</span>i<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">endl</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
    <span style="color: #0000ff;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> i<span style="color: #000080;">=</span><span style="color: #0000dd;">95</span><span style="color: #008080;">;</span> i<span style="color: #000080;">&lt;=</span><span style="color: #0000dd;">100</span><span style="color: #008080;">;</span> <span style="color: #000040;">++</span>i<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        sleep<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        printProgBar<span style="color: #008000;">&#40;</span>i<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">endl</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
    std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">endl</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<pre>
8D                                                 @   0%
8=====D                                            @  10%
8==========D                                       @  20%
8===============D                                  @  30%
8====================D                             @  40%
8=========================D                        @  50%
8==============================D                   @  60%
8===================================D              @  70%
8========================================D         @  80%
8=============================================D    @  90%
8===============================================D  @  95%
8================================================D @  96%
8================================================D @  97%
8=================================================D@  98%
8=================================================D@  99%
8==================================================D~~~~ ~~~ ~
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.cogitolingua.net/blog/2011/09/25/the-progress-phallus/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Higher-Order Functions in Java</title>
		<link>http://www.cogitolingua.net/blog/2011/07/22/higher-order-functions-in-java/</link>
		<comments>http://www.cogitolingua.net/blog/2011/07/22/higher-order-functions-in-java/#comments</comments>
		<pubDate>Sat, 23 Jul 2011 04:21:01 +0000</pubDate>
		<dc:creator>erich</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Comp*]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Fun]]></category>

		<guid isPermaLink="false">http://www.cogitolingua.net/blog/?p=543</guid>
		<description><![CDATA[<p> This Summer I&#8217;ve been teaching Intro to Computer Languages. It&#8217;s a really awesome class, with alot of good material in it. Last week, my students got back the results of their midterms, and were disappointed in their scores. Immediately, I heard some clamoring for an extra credit. Not only was the average midterm score [...]]]></description>
			<content:encoded><![CDATA[<p>
This Summer I&#8217;ve been teaching <a href="http://www.ics.uci.edu/~ehenniga/ics141/index.html">Intro to Computer Languages</a>.  It&#8217;s a really awesome class, with alot of good material in it.  Last week, my students got back the results of their midterms, and were disappointed in their scores.  Immediately, I heard some clamoring for an extra credit. Not only was the average midterm score pretty low, but also the class has been jumping rapidly from one topic to another. The schedule was originally planned for a 10 week course, but has been compressed for a 6 week Summer Session.  I don&#8217;t think that student learning rate improves by almost a factor of 2 just because it&#8217;s summer an the lecture is 3hrs instead of the normal 1hr 30min. Quite the contrary, I think retention is best achieved as a result of long-term exposure to material, precisely the opposite of our current situation.</p>
<p>
Prior to the midterm, in Project 2, we had done an exercise writing a in-order iterator over a binary search tree. This exercise had two important components: (1) The iterator allows pausing between elements. So, it must have a way to remember where it left off the last time an element was returned. (2) The binary search tree could be storing any type of data. So, the entire project had to satisify the typing constraints of Java&#8217;s generics system.</p>
<p>
Then, in the following week (I told you the class moves quick), We used Haskell in Project 3 to cover the concept of <a href="http://en.wikipedia.org/wiki/Higher-order_function">Higher Order Functions</a> (HOF). Now, most of my students have had their minds trained on Java, which doesn&#8217;t provide <a href="http://en.wikipedia.org/wiki/First-class_function">first class functions</a>. So, the concept that a function might take other functions as arguments or return a function as a result is really foreign.</p>
<p>
Since my students were clamoring for some extra credit, I tried to think up something that might tie together what has been done so far. My predecessor, <a href="http://alexthornton.net/Blog.aspx">Alex Thornton</a>, had done a Higher Order Function implementation in C# as a fun and interesting demo for his last lecture. Now, I don&#8217;t know C#, but I&#8217;m pretty sure that I could do the same in Java.  It turns out you can create for yourself a java Framework that provides this higher order functions, with a bit of work.  Although, as we shall see, it&#8217;s verbose and clunky.</p>
<p>
Let&#8217;s begin by defining what a function looks like. Since Java doesn&#8217;t support first-class functions, we start by defining a <a href="http://en.wikipedia.org/wiki/Function_object">Function Object</a>.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> IFunction<span style="color: #339933;">&lt;</span>A, B<span style="color: #339933;">&gt;</span> <span style="color: #009900;">&#123;</span>
	B call<span style="color: #009900;">&#40;</span>A arg<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Basically, any object that wishes to act as a function from A &rarr; B, implements the IFunction interface, so that it has a <code>call</code> method.</p>
<p>
Next, I try and think of some task that would use some HOFs. So, let&#8217;s first create a list of <code>String</code>s, and print them out.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    ArrayList<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span> words <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    words.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;File&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    words.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Edit&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    words.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Source&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    words.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Refactor&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    words.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Navigate&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    words.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Search&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    words.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Project&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    words.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Run&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    words.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Window&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    words.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Help&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Starting With: &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    FunctionLib.<span style="color: #006633;">map</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> PrintFunction<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, words<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>
Instead of using the normal for-each loop to I print out all the elements in a list, I map a <code>PrintFunction</code> (specialized on <code>String</code>) onto the list. Let&#8217;s look at the HOF <code>map</code> first. We know from using Haskell that <code>map</code> takes a function and a list, and applies that function to every element in the list.  So, <code>map</code> takes two arguments: (1) a function from A &rarr; B, and (2) a list of A. Finally, after applying the function to every element, it returns a list of B. We collect all the HOFs we&#8217;ll implement into a <code>FunctionLib</code> class.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> FunctionLib <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// map :: (a -&gt; b) -&gt; [a] -&gt; [b]</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #339933;">&lt;</span>A,B<span style="color: #339933;">&gt;</span> List<span style="color: #339933;">&lt;</span>B<span style="color: #339933;">&gt;</span> map<span style="color: #009900;">&#40;</span>IFunction<span style="color: #339933;">&lt;</span>A, B<span style="color: #339933;">&gt;</span> fun, List<span style="color: #339933;">&lt;</span>A<span style="color: #339933;">&gt;</span> args<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        List<span style="color: #339933;">&lt;</span>B<span style="color: #339933;">&gt;</span> results <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>B<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span>A a <span style="color: #339933;">:</span> args<span style="color: #009900;">&#41;</span>
            results.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>fun.<span style="color: #006633;">call</span><span style="color: #009900;">&#40;</span>a<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> results<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>
I&#8217;m mappping a &lt;code&gt;PrintFunction&lt;/code&gt; that has the side-effect of printing each element it is called on. The primary difficulty with doing this is that according to my <code>IFunction</code> interface, I have to return something that fits in Java&#8217;s generics system. So, I specialize the return type parameter to <code>Object</code> and return <code>null</code>. Technically, the <code>map</code> method will remember the resulting <code>null</code>s, and build a list of them, which then gets discarded. A bit wasteful, but it&#8217;s an <a href="http://en.wikipedia.org/wiki/Eager_evaluation">eager language</a>, so there&#8217;s not much we can do to avoid that.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> PrintFunction<span style="color: #339933;">&lt;</span>E<span style="color: #339933;">&gt;</span> <span style="color: #000000; font-weight: bold;">implements</span> IFunction<span style="color: #339933;">&lt;</span>E, Object<span style="color: #339933;">&gt;</span> <span style="color: #009900;">&#123;</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> call<span style="color: #009900;">&#40;</span>E arg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>arg<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>
I don&#8217;t especially like creating a whole class file for each function I might want to pass into an HOF. Fortunately, Java supports <a href="http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm">anonymous classes</a>. Let&#8217;s create one for getting the length of a string, call it <code>lengthFunction</code>, and pass it into <code>map</code>, so that we get back an array of <code>Integer</code>s representing the lengths.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;The length of each String is: &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    IFunction<span style="color: #339933;">&lt;</span>String, Integer<span style="color: #339933;">&gt;</span> lengthFunction <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> IFunction<span style="color: #339933;">&lt;</span>String, Integer<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Integer</span> call<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> arg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">return</span> arg.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
    List<span style="color: #339933;">&lt;</span>Integer<span style="color: #339933;">&gt;</span> lengths<span style="color: #339933;">=</span> FunctionLib.<span style="color: #006633;">map</span><span style="color: #009900;">&#40;</span>lengthFunction, words<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    FunctionLib.<span style="color: #006633;">map</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> PrintFunction<span style="color: #339933;">&lt;</span>Integer<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, lengths<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Although, not creating a class file for each new function is nice, it&#8217;s still hideously verbose to create a whole class. Oh, do I wish that Java provided syntax for <a href="http://en.wikipedia.org/wiki/Lambda_(programming)">lambda</a>&#8216;s.</p>
<p>
Now that I have two lists, one of words and another of their lengths, I should be able to stitch them together. Haskell provides another HOF for precisely this task: <code>zip</code> is a function that takes two lists and returns a pair of their elements. The resulting list of pairs is the same length as the shortest input list.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> FunctionLib <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// zip :: [a] -&gt; [b] -&gt; [(a, b)]</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #339933;">&lt;</span>A,B<span style="color: #339933;">&gt;</span> List<span style="color: #339933;">&lt;</span>Pair<span style="color: #339933;">&lt;</span>A,B<span style="color: #339933;">&gt;&gt;</span> zip<span style="color: #009900;">&#40;</span>List<span style="color: #339933;">&lt;</span>A<span style="color: #339933;">&gt;</span> listA, List<span style="color: #339933;">&lt;</span>B<span style="color: #339933;">&amp;&gt;</span> listB<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        List<span style="color: #339933;">&lt;</span>Pair<span style="color: #339933;">&lt;</span>A,B<span style="color: #339933;">&gt;</span> results <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>Pair<span style="color: #339933;">&lt;</span>A,B<span style="color: #339933;">&gt;&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span> len <span style="color: #339933;">=</span> <span style="color: #003399;">Math</span>.<span style="color: #006633;">min</span><span style="color: #009900;">&#40;</span>listA.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, listB.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i<span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span>len<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            results.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span> <span style="color: #000000; font-weight: bold;">new</span> Pair<span style="color: #339933;">&lt;</span>A,B<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span>listA.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span>, listB.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">return</span> results<span style="color: #339933;">;</span>    
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>
Java is so hideously dysfunctional that it doesn&#8217;t come with a native <code>Pair</code> class. However, it&#8217;s easy to make one.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Pair<span style="color: #339933;">&lt;</span>A,B<span style="color: #339933;">&gt;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> A first<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> B second<span style="color: #339933;">;</span>
&nbsp;
    Pair<span style="color: #009900;">&#40;</span>A a, B b<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        first <span style="color: #339933;">=</span> a<span style="color: #339933;">;</span>
        second <span style="color: #339933;">=</span> b<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> toString<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">String</span> firstStr <span style="color: #339933;">=</span> first <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">?</span> first.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> <span style="color: #0000ff;">&quot;null&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">String</span> secondStr <span style="color: #339933;">=</span> second <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">?</span> second.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> <span style="color: #0000ff;">&quot;null&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;(&quot;</span> <span style="color: #339933;">+</span> firstStr <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;, &quot;</span> <span style="color: #339933;">+</span> secondStr <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;)&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>
After all that monstrous cruft, we can finally get the list of pairs containing each word and its length.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    List<span style="color: #339933;">&lt;</span>Pair<span style="color: #339933;">&lt;</span>String, Integer<span style="color: #339933;">&gt;&gt;</span> associations <span style="color: #339933;">=</span> FunctionLib.<span style="color: #006633;">zip</span><span style="color: #009900;">&#40;</span>words, lengths<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>
But we&#8217;ve yet to do anything really interesting with that. So, let&#8217;s filter the list for words that are greater than 5 letters long. Haskell also provides an HOF <code>filter</code> which takes a function that is applied to every element in the list, and a list on which to apply it, returning a list of those elements for which the function evaluated true.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> FunctionLib <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// filter :: (a -&gt; bool) -&gt; [a] -&gt; [a]</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #339933;">&lt;</span>A<span style="color: #339933;">&gt;</span> List<span style="color: #339933;">&lt;</span>A<span style="color: #339933;">&gt;</span> filter<span style="color: #009900;">&#40;</span>IFunction<span style="color: #339933;">&lt;</span>A, Boolean<span style="color: #339933;">&gt;</span> pred, List<span style="color: #339933;">&lt;</span>A<span style="color: #339933;">&gt;</span> listA<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        List<span style="color: #339933;">&lt;</span>A<span style="color: #339933;">&gt;</span> results <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>A<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span>A a <span style="color: #339933;">:</span> listA<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>pred.<span style="color: #006633;">call</span><span style="color: #009900;">&#40;</span>a<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
                results.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">return</span> results<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>
I use this function to pull out the pairs which have a string longer than 5 characters. Again, I again use the verbose anonymous class.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;The words with length bigger than 5 are:&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    IFunction<span style="color: #339933;">&lt;</span>Pair<span style="color: #339933;">&lt;</span>String, Integer<span style="color: #339933;">&gt;</span>, Boolean<span style="color: #339933;">&gt;</span> biggerThanFive <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> IFunction<span style="color: #339933;">&lt;</span>Pair<span style="color: #339933;">&lt;</span>String, Integer<span style="color: #339933;">&gt;</span>, Boolean<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Boolean</span> call<span style="color: #009900;">&#40;</span>Pair<span style="color: #339933;">&lt;</span>String, Integer<span style="color: #339933;">&gt;</span> arg<span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">return</span> arg.<span style="color: #006633;">second</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">5</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
    List<span style="color: #339933;">&lt;</span>Pair<span style="color: #339933;">&lt;</span>String, Integer<span style="color: #339933;">&gt;&gt;</span> longerThanFive <span style="color: #339933;">=</span> FunctionLib.<span style="color: #006633;">filter</span><span style="color: #009900;">&#40;</span>biggerThanFive, associations<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>
But, I&#8217;m really only interested in the strings, not the pairs. So, now I want a way to pull out only the first element of each pair.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    List<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span> stringsLongerThanFive <span style="color: #339933;">=</span> FunctionLib.<span style="color: #006633;">map</span><span style="color: #009900;">&#40;</span>Pair.<span style="color: #006633;">firstFunction</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span>.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #003399;">Integer</span>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>, longerThanFive<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    FunctionLib.<span style="color: #006633;">map</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> PrintFunction<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, stringsLongerThanFive<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>
Notice, that this time, I&#8217;ve given myself a convenience method, <code>Pair.firstFunction</code>. I&#8217;d really have preferred something like C++&#8217;s syntax here, but Java&#8217;s generic system has some pretty fundamental brokenness. First, as a result of <a href="http://download.oracle.com/javase/tutorial/java/generics/erasure.html">type-erasure</a>, the system doesn&#8217;t know what the type parameters into the function are at runtime. That makes an expression like <code>Pair&lt;String,Integer&gt;.firstFunction</code> invalid, because the type parameters are thrown away way before the method call takes place. Second, the type parameters to a generic method are determined via inspection on the types of the provided actual arguments. That makes an expression like <code>Pair.firstFunction&lt;String,Integer&gt;</code> invalid. You don&#8217;t pass type parameters at the function call site (as you would when you instantiate a generic object). Instead, as a workaround, you have to provide dummy actual arguments, that the typing system uses to specialize the call.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Pair<span style="color: #339933;">&lt;</span>A,B<span style="color: #339933;">&gt;</span> <span style="color: #009900;">&#123;</span>
    ...
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #339933;">&lt;</span>A,B<span style="color: #339933;">&gt;</span> IFunction<span style="color: #339933;">&lt;</span>Pair<span style="color: #339933;">&lt;</span>A, B<span style="color: #339933;">&gt;</span>, A<span style="color: #339933;">&gt;</span> firstFunction<span style="color: #009900;">&#40;</span>Class<span style="color: #339933;">&lt;</span>A<span style="color: #339933;">&gt;</span> a, Class<span style="color: #339933;">&lt;</span>B<span style="color: #339933;">&gt;</span> b<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> IFunction<span style="color: #339933;">&lt;</span>Pair<span style="color: #339933;">&lt;</span>A, B<span style="color: #339933;">&gt;</span>, A<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">public</span> A call<span style="color: #009900;">&#40;</span>Pair<span style="color: #339933;">&lt;</span>A, B<span style="color: #339933;">&gt;</span> arg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">return</span> arg.<span style="color: #006633;">first</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #339933;">&lt;</span>A,B<span style="color: #339933;">&gt;</span> IFunction<span style="color: #339933;">&lt;</span>Pair<span style="color: #339933;">&lt;</span>A,B<span style="color: #339933;">&gt;</span>, B<span style="color: #339933;">&gt;</span> secondFunction<span style="color: #009900;">&#40;</span>Class<span style="color: #339933;">&lt;</span>A<span style="color: #339933;">&gt;</span> a, Class<span style="color: #339933;">&lt;</span>B<span style="color: #339933;">&gt;</span> b<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> IFunction<span style="color: #339933;">&lt;</span>Pair<span style="color: #339933;">&lt;</span>A, B<span style="color: #339933;">&gt;</span>, B<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">public</span> B call<span style="color: #009900;">&#40;</span>Pair<span style="color: #339933;">&lt;</span>A, B<span style="color: #339933;">&gt;</span> arg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">return</span> arg.<span style="color: #006633;">second</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>
Things are a little bit different here than the <code>PrintFunction</code> we implemented earlier. We should like to keep the function that pulls out the first element of a pair in the <code>Pair</code> class. Doing this is not only trick because of Java&#8217;s generic type system deficiencies, but also because we can&#8217;t simply name a function as a reference (as you can in C). Instead, we create a <code>firstFunction</code> method, that when called with type parameters as actual arguments, returns an appropriately specialized <code>IFunction</code> which returns the first element when you pass it a pair in the <code>call</code>. Creation of the returned IFunction is also achieved via an anonymous class.</p>
<p>
We now turn to the coup de gr&acirc;ce. We have a list of all the strings with length bigger than 5, so let&#8217;s use an HOF to concatenate them. Haskell again provides us with a function, <code>foldl1</code> that will start at the beginning of a list and inductively apply a two argument function onto it, returning a single result. Essentially, if <code>+</code> were my string concatenation operator and my list were <code>[a, b, c, d, ...]</code> I&#8217;d be calculating <code>(..((a + b) + c) + d) + ..)</code>. It&#8217;s a bit tricky in our implementation though. We have to pass into the HOF a function that takes two arguments, but my <code>IFunction</code> interface is only able to represent functions of a single argument. What shall we do?</p>
<p>
<a href="http://en.wikipedia.org/wiki/Currying">Currying</a> to the rescue! Haskell types the first argument to <code>foldl1</code> as (a -&gt; a -&gt; a). Which you might na&iuml;vely think is an function of two arguments, but the arrow operator is right-associative. So, it&#8217;s actually parsed as (a -&gt; (a -&gt; a)), which is a function of one argument that returns a function of one argument. So, a function of two arguments is equivalent to a nested chain of functions, each accepting one argument. Which means, the <code>IFunction</code> interface is enough!</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> FunctionLib <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// foldl1 :: (a -&gt; a -&gt; a) -&gt; [a] -&gt; a</span>
    <span style="color: #666666; font-style: italic;">// In Haskell the function type operator -&gt; is right associative,</span>
    <span style="color: #666666; font-style: italic;">// So, the function description &quot;a -&gt; a -&gt; a&quot; is parsed as &quot;a -&gt; (a -&gt; a)&quot;</span>
    <span style="color: #666666; font-style: italic;">// This order of application is represented in the nesting of IFunction's below</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #339933;">&lt;</span>A<span style="color: #339933;">&gt;</span> A foldl1<span style="color: #009900;">&#40;</span>IFunction<span style="color: #339933;">&lt;</span>A, IFunction<span style="color: #339933;">&lt;</span>A,A<span style="color: #339933;">&gt;&gt;</span> fn, List<span style="color: #339933;">&lt;</span>A<span style="color: #339933;">&gt;</span> listA<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        A accumulator <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>listA.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span>
            <span style="color: #000000; font-weight: bold;">return</span> accumulator<span style="color: #339933;">;</span>
&nbsp;
        accumulator <span style="color: #339933;">=</span> listA.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>listA.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span>
            <span style="color: #000000; font-weight: bold;">return</span> accumulator<span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i<span style="color: #339933;">=</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span>listA.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #666666; font-style: italic;">// currying means two .call invocations</span>
            accumulator <span style="color: #339933;">=</span> fn.<span style="color: #006633;">call</span><span style="color: #009900;">&#40;</span>accumulator<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">call</span><span style="color: #009900;">&#40;</span>listA.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">return</span> accumulator<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>
Finally, I can wrap up this exercise by applying a concatenation operator to a call to <code>foldl1</code>. This ends up being some of the most ugly code that can be written. Unlike the previous calls to <code>map</code> and <code>filter</code>, I did not want to save the temporary function into a variable. Rather, I&#8217;ve written it inline. Unfortunately, because of the currying, we have to nest anonymous functions!</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;When we concatenate these we get:&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003399;">String</span> concat <span style="color: #339933;">=</span> FunctionLib.<span style="color: #006633;">foldl1</span><span style="color: #009900;">&#40;</span>
        <span style="color: #000000; font-weight: bold;">new</span> IFunction<span style="color: #339933;">&lt;</span>String, IFunction<span style="color: #339933;">&gt;</span>String, String<span style="color: #339933;">&gt;&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">public</span> IFunction<span style="color: #339933;">&lt;</span>String, String<span style="color: #339933;">&gt;</span> call<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> arg1<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> IFunction<span style="color: #339933;">&lt;</span>String, String<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> call<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> arg2<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                        <span style="color: #000000; font-weight: bold;">return</span> arg1 <span style="color: #339933;">+</span> arg2<span style="color: #339933;">;</span>
                    <span style="color: #009900;">&#125;</span>
                <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>,
        stringsLongerThanFive<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>concat<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>
What&#8217;s going on here? Remember, we are representing a function of two arguments as nested functions of a single argument. So for example, I want to concatenate the list <code>[a, b, c, d]</code>, I would pass in the concatenation operator, <code>(+)</code>. Inside of <code>foldl1</code>, we take out the first element, <code>a</code> and invoke the <code>call</code> method with the first argument. This returns <code>(a+)</code>, which is the concatenation operator with the first argument filled in. A second invocation is used to pass in the second argument, and that returns a string, which is saved in an accumulator.</p>
<p>
This level of indirection means that I have to have some way of returning a function with the first argument filled in.  I accomplish this by nesting anonymous classes and using a <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)">closure</a>. The outer <code>call</code> method takes <code>final String arg1</code> as an argument. <code>final</code> is necessary, because I have to tell Java that it is OK to &#8216;save&#8217; or &#8216;cache&#8217; this argument. I&#8217;m guaranteeing that I don&#8217;t have any code within this method that might change what <code>arg1</code> referrs to. Once I&#8217;ve made this guarantee, I&#8217;m able to create and return a <code>new IFunction</code> with its own <code>call(String arg2)</code> that uses the outer <code>arg1</code>.</p>
<p>
After going through all this awesome Computer Science (weird rules about the generics system, anonymous inner classes, currying, and closures), I decided that this is not something I could reasonably expect my students to do as extra credit. First, I would want extra credit to assist my student&#8217;s absorption of concepts, and yet still not be so difficult that it becomes a distraction to actual coursework. Second, it should be easy enough to help the students that need it to improve their grade. Although this example does hit the generics and higher-order functions topics, I think it has too many complex issues rolled together. For example, I&#8217;ve never actually had to use closures and anonymous inner classes before. Now, suddenly, I use them both in a single project!</p>
<p>UPDATE Mon Aug  8 19:56:37 PDT 2011: Jim Duey has a talk <a href="http://www.infoq.com/presentations/Functional-Programming-A-Pragmatic-Introduction">Functional Programming: A Pragmatic Introduction</a>. At around 30mins he shows how Laziness can be used to implement a message queue for concurrent programs.</p>
<p>UPDATE Tue Aug  9 11:30:16 PDT 2011: You can download the project source <a href="http://www.cogitolingua.net/blog/wp-content/uploads/2011/08/FunctionalJava.zip">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cogitolingua.net/blog/2011/07/22/higher-order-functions-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A language should be focused on writing Internal DSLs</title>
		<link>http://www.cogitolingua.net/blog/2011/05/18/a-language-should-be-focused-on-writing-internal-dsls/</link>
		<comments>http://www.cogitolingua.net/blog/2011/05/18/a-language-should-be-focused-on-writing-internal-dsls/#comments</comments>
		<pubDate>Thu, 19 May 2011 06:21:27 +0000</pubDate>
		<dc:creator>erich</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Comp*]]></category>
		<category><![CDATA[Ideas]]></category>
		<category><![CDATA[Language]]></category>

		<guid isPermaLink="false">http://www.cogitolingua.net/blog/?p=527</guid>
		<description><![CDATA[<p>I&#8217;ve been reading Martin Fowler&#8217;s book, Domain-Specific Languages, this weekend. He covered a number of ways in which you can structure your code to achieve what he terms an Internal DSL. Quite a bit is focused on the discussion of a fluent interface. It turns out in many languages there are only so many ways [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been reading Martin Fowler&#8217;s book, <em>Domain-Specific Languages</em>, this weekend. He covered a number of ways in which you can structure your code to achieve what he terms an <em>Internal DSL</em>. Quite a bit is focused on the discussion of a <a href="http://en.wikipedia.org/wiki/Fluent_interface">fluent interface</a>. It turns out in many languages there are only so many ways to structure the code so it looks like a DSL rather than the host language. Chapter 4 of the book explores a number of these techniques, and summarizes the results in a nice table, mapping language structure (for a DSL) to host language patterns:</p>
<table width="100%">
<tr>
<th>Structure</th>
<th>BNF</th>
<th>Consider&#8230;</th>
</tr>
<tr>
<td>Mandatory list</td>
<td><code>parent ::= first second third</code></td>
<td>Nested Function</td>
</tr>
<tr>
<td>Optional list</td>
<td><code>parent ::= first maybeSecond? maybeThird?</code></td>
<td>Method Chaining, Literal Map</td>
</tr>
<tr>
<td>Homogenous bag</td>
<td><code>parent ::= child*</code></td>
<td>Literal List, Function Sequence</td>
</tr>
<tr>
<td>Heterogenous bag</td>
<td><code>parent ::= (this | that | theOther)*</code></td>
<td>Method Chaining</td>
</tr>
<tr>
<td>Set</td>
<td><code>n/a</code></td>
<td>Literal Map</td>
</tr>
</table>
<p>What&#8217;s interesting about this mapping is that, we can use it to engineer a language whose sole purpose would be to solve problems by authoring and combining DSL&#8217;s (what the Lisper&#8217;s are always claiming they do through the use of macro&#8217;s).<br />
The focus here is to get a function call specification that can do a good job of representing all the control structures that are present within a grammar.<br />
So let&#8217;s take a careful look at <a href="http://en.wikipedia.org/wiki/Wirth_syntax_notation">Wirth&#8217;s syntax notation</a> to get a good idea of what needs to be modeled.</p>
<ul>
<li><b>Sequencing</b> is conveyed by a space-delimited list of grammar elements: <b>a b c d</b></li>
</li>
<li><b>Repitition</b> is denoted by curly brackets: <b>{a}</b> stands for <b>&epsilon; | a | aa | aaa | &#8230;</b></li>
<li><b>Optionality</b> is expressed by square brackets: <b>[a]b</b> stands for <b>ab | b</b></li>
<li><b>Grouping</b> is indicated by parenthesis: <b>(a|b)c</b> stands for <b>ac | ab</b></li>
</ul>
<p>Fowler gives some interesting suggestions, both in the above table and in the surrounding discussion within the book. I&#8217;d like to take some space here and explore each of the options, and how it relates to a Wirth-style grammar. Throughout this exposition, we&#8217;ll be using programming language constructs such as function calls and scoping to model the grammar rules typically seen in the above table. We&#8217;ll also assume that each grammar rule can be made to correspond to either a method or type (or both) in the implementors programming language.</p>
<ul>
<li><b>Mandatory list.</b> Within a grammar, a mandatory list is indistinguishable from a sequence. Within a programming language, the mandatory list can also be expressed as a list of arguments that must be provided to a function. We can even invoke compile-time checking by having each grammar rule correspond to a type. Fowler doesn&#8217;t quite go that far, but he does give this illustrative example:<br />
    <center></p>
<table width="100%">
<tr>
<th>Nested Function</th>
<th>Example declarations</th>
<tr>
<td>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">computer<span style="color: #008000;">&#40;</span>
    processor<span style="color: #008000;">&#40;</span>
        cores<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #008000;">&#41;</span>,
        speed<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2500</span><span style="color: #008000;">&#41;</span>,
        i386
    <span style="color: #008000;">&#41;</span>,
    disk<span style="color: #008000;">&#40;</span>
        size<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">150</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#41;</span>,
    disk<span style="color: #008000;">&#40;</span>
        size<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">75</span><span style="color: #008000;">&#41;</span>,
        speed<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">7200</span><span style="color: #008000;">&#41;</span>,
        sata<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#41;</span></pre></div></div>

</td>
<td>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">ComputerT computer<span style="color: #008000;">&#40;</span>ProcessorT, DiskT<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
ProcessorT processor<span style="color: #008000;">&#40;</span>CoresT, SpeedT, ArchT<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
DiskT disk<span style="color: #008000;">&#40;</span>SizeT<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

</td>
</tr>
</table>
<p>    </center>
</li>
<li><b>Optional List.</b> As long as each list can be clearly expressed, we can achieve an optional list via function overloading. This way the compiler will match up directly to the instance of the correct rule. However, this amount of explicitness comes at a cost: either we keep the number of optional choices in the grammar to a minimum, or we commit ourselves to writing a large number of very similar functions (as the optionality can explode exponentially). If optionality is given in the grammar as a grouping, then it may make sense to create a new function representing only that grouping. This can reduce the amount of function overloading by reducing the number of function signatures that need to be supported. Fowler recommends two options:
<p>    <center></p>
<table width="100%">
<tr>
<th>Method Chaining</th>
<th>Literal Map</th>
</tr>
<tr>
<td>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">computer<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    .<span style="color: #007788;">processor</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        .<span style="color: #007788;">cores</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #008000;">&#41;</span>,
        .<span style="color: #007788;">speed</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2500</span><span style="color: #008000;">&#41;</span>,
        .<span style="color: #007788;">i386</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    .<span style="color: #007788;">disk</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        .<span style="color: #007788;">size</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">150</span><span style="color: #008000;">&#41;</span>
    .<span style="color: #007788;">disk</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        .<span style="color: #007788;">size</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">75</span><span style="color: #008000;">&#41;</span>
        .<span style="color: #007788;">speed</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">7200</span><span style="color: #008000;">&#41;</span>
        .<span style="color: #007788;">sata</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    .<span style="color: #007788;">end</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span></pre></div></div>

</td>
<td>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">computer<span style="color:#006600; font-weight:bold;">&#40;</span>
    processor<span style="color:#006600; font-weight:bold;">&#40;</span>
        <span style="color:#ff3333; font-weight:bold;">:cores</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">2</span>,
        <span style="color:#ff3333; font-weight:bold;">:speed</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">2500</span>,
        <span style="color:#ff3333; font-weight:bold;">:type</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:i386</span>
    <span style="color:#006600; font-weight:bold;">&#41;</span>,
    disk<span style="color:#006600; font-weight:bold;">&#40;</span>
        <span style="color:#ff3333; font-weight:bold;">:size</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">150</span>
    <span style="color:#006600; font-weight:bold;">&#41;</span>,
    disk<span style="color:#006600; font-weight:bold;">&#40;</span>
        <span style="color:#ff3333; font-weight:bold;">:size</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">75</span>,
        <span style="color:#ff3333; font-weight:bold;">:speed</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">7200</span>,
        <span style="color:#ff3333; font-weight:bold;">:interface</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:sata</span>
    <span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

</td>
</tr>
</table>
<p>    </center></p>
<p>Although the Method Chaining approach readily allows for the assumption of default parameters (for example the speed of the first disk), the hierarchical structure here is not fully captured by the chain of method calls. To support such a chain as that in the example, it would be necessary to hold a ContextVariable that each method automatically recognizes. (for example, so that <code>size()</code> can refer to the last <code>disk</code> inserted. Because this context is kept implicit, the compiler will not be able to capture an invalid sequence of method calls (instead this much be caught by validity checking code at runtime). Furthermore, it is important to keep straight the terminology of each different component. For example, it is not clear that <code>speed(7200)</code> should refer to the last mentioned disk or to the last mentioned processor. Reshuffling the order of method calls can be highly problematic, and can result in unwanted side-effects if terminology becomes mixed up.</p>
<p>The Literal Map approach works pretty well for dynamic languages (python and ruby) which allow functions to accept a dictionary mapping terms to values. It would be nice to have named parameters in more of the static languages (Ada and C# have them, C/C++ and Java do not).  Having a statically type-checked language implement this feature, including the ability to overload with default values, would be ideal. There is also nothing that preserves the order of entries (which isn&#8217;t all that important in this example).
</li>
<li><b>Homogeneous Bag.</b> This is directly about modeling the <b>repetition</b> rule in Wirth&#8217;s syntax. In most programming languages, there do not exist easily used mechanisms for passing a <em>variable length list</em> of items.<br />
    <center></p>
<table width="100%">
<tr>
<th>Literal List</th>
<th>Function Sequence</th>
</tr>
<tr>
<td>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">martin.<span style="color: #007788;">follows</span><span style="color: #008000;">&#40;</span>
    <span style="color: #FF0000;">&quot;WardCunningham&quot;</span>,
    <span style="color: #FF0000;">&quot;bigballofmud&quot;</span>,
    <span style="color: #FF0000;">&quot;KentBeck&quot;</span>,
    <span style="color: #FF0000;">&quot;neal4d&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

</td>
<td>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">computer<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    processor<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        cores<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        speed<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2500</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        i386<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    disk<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        size<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">150</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    disk<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        size<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">75</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        speed<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">7200</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        sata<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

</td>
</tr>
</table>
<p>    </center></p>
<p>The Literal List approach can be implemented, in languages such as C, with the varargs mechanism. But it forgoes type-checking, and definitely doesn&#8217;t feel &#8216;built-in&#8217;. Dynamic languages are more permissive in this regard. For example, Python has the <code>*args</code> mechanism, and JavaScript allows access to the <code>arguments</code> array. In either case, it turns out, aside from creating, explicitly, your own separate list to pass in, there just really isn&#8217;t a great way to implement this pattern. All is not quite lost, however, as some language allow for the in-line initialization of arrays. For example,</p>
<ul>
<li>C++ allows passing of a streamed object: <code>m(StringArray() &lt;&lt; "blah" &lt;&lt; "hey" &lt;&lt; "yo")</code>, which isn&#8217;t quite what we want.</li>
<li>Java does a bit better with <code>m(new String[]{"blah", "hey", "yo"});</code> which sacrifices readability, but achieves the desired goal.</li>
<li>Java also allows declaration of a type-checked varargs <code>m(String...);</code> which is called like <code>m("blah", "hey", "yo")</code>, which is precisely what we want.</li>
</ul>
<p>The biggest drawback of using the varargs mechanism is that it lacks sequential composability. You cannot easily declare a function for the rule: <code>A := B* C*</code>. In this case, the more crufty, in-line instantiation mechanisms turn out to be better.</p>
<p>The Function Sequence approach lacks pretty much everything I&#8217;ve considered thus far: it&#8217;s sequencing isn&#8217;t type-checked, terminology can be confused, it requires a State Variable to maintain context. The only way in which it isn&#8217;t worse than Method Chaining is that the compiler can tell you on what line you crashed, provided you responsibly littered your code with <code>assert</code>&#8216;s.
</li>
<li><b>Heterogeneous Bag.</b> Because this is more about <b>repetition</b> of <b>optionality</b>, it&#8217;s probably best handled by combining previous approaches. For example, you could choose to factor out the group as it&#8217;s own separate type, and then have a vararg listing of these types. Method Chaining can be used for list of configuration parameters, especially if order isn&#8217;t really the concern. You couldn&#8217;t implement this with a dictionary or map though, because of the repetition aspect.
</li>
<li><b>Set.</b> Clearly the only approach to implementing an unordered collection of possibly heterogeneous types is a dictionary or associative array, best represented in the the Literal Map approach. Again, we&#8217;d like to have a clean syntax for this in our programming languages: type-checked keyword arguments.
</ul>
<p>For me, the most important aspect of this exposition has been the progressive realization that type-checked keyword arguments and inline-initialization are necessary elements to supporting a mini-DSL within your own programming language. Without these features, syntax too easily obscures what you are tying to express. It&#8217;s probably worth complicating both the semantics and parsing of the host language to provide these elements.</p>
<p>We also find that, using function calls as our implementation interface, the most difficult aspect of Wirth&#8217;s syntax is <b>repetition</b>. All the other rules fit very nicely into existing function interfaces. It would be very nice for more languages to support varargs in the way that Java has. However, I would like for this to be extended a bit further: it should be possible to have multiple vararg arguments, as long as they are type-distinguishable. For example, <code>m(String..., Integer...)</code>, should be callable with <code>m("a", "b", "c", 3, 1, 4, 1, 5, 9)</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cogitolingua.net/blog/2011/05/18/a-language-should-be-focused-on-writing-internal-dsls/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Const-correctness</title>
		<link>http://www.cogitolingua.net/blog/2011/02/16/const-correctness/</link>
		<comments>http://www.cogitolingua.net/blog/2011/02/16/const-correctness/#comments</comments>
		<pubDate>Thu, 17 Feb 2011 03:55:23 +0000</pubDate>
		<dc:creator>erich</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Comp*]]></category>
		<category><![CDATA[Information Flow]]></category>
		<category><![CDATA[Tech*]]></category>

		<guid isPermaLink="false">http://www.cogitolingua.net/blog/?p=453</guid>
		<description><![CDATA[<p>One of my fellow lab-mates has already posted about const-correctness, because of some similar issues. My work today, takes it a tiny bit further into sheer insanity.</p> <p>If you don&#8217;t start your program off using a const-correctness discipline, it&#8217;s very likely that you will find yourself in a world of hurt when you try to [...]]]></description>
			<content:encoded><![CDATA[<p>One of my fellow lab-mates has <a href="http://gforge.ssllab.org/~tmjackso/wordpress/archives/309">already posted</a> about const-correctness, because of some similar issues. My work today, takes it a tiny bit further into sheer insanity.</p>
<p>If you don&#8217;t start your program off using a const-correctness discipline, it&#8217;s very likely that you will find yourself in a world of hurt when you try to add it in later. I hit something like this today. In our system we have these labels, which are managed by a Factory and which are supposed to be immutable. Because all the labels are managed by a factory, we have a whole bunch of pointers:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">JSFlowLabel <span style="color: #000040;">*</span>lab <span style="color: #000080;">=</span> ...</pre></div></div>

<p>Although no bugs have come up as a result, we should have decided a long time ago, to enforce the immutable semantics with the compiler. So, after seeing a few suspicious lines today, (which turned out to be fine, but which raised my paranoia alarms) I decided that we should add const. Beginning with the Factory that produces these:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">JSFlowLabel <span style="color: #0000ff;">const</span><span style="color: #000040;">*</span> JSFlowLabel<span style="color: #008080;">::</span><span style="color: #007788;">create</span><span style="color: #008000;">&#40;</span>...<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>...<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Followed by a hundred changes to code like the above, and a few method call modifications.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">JSFlowLabel <span style="color: #0000ff;">const</span> <span style="color: #000040;">*</span>lab <span style="color: #000080;">=</span> ...
&nbsp;
<span style="color: #007788;">JSFlowLabel</span><span style="color: #008080;">::</span><span style="color: #007788;">join</span><span style="color: #008000;">&#40;</span>JSFlowLabel <span style="color: #0000ff;">const</span> <span style="color: #000040;">*</span>lab1, JSFlowLabel <span style="color: #0000ff;">const</span> <span style="color: #000040;">*</span>lab2<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>...<span style="color: #008000;">&#125;</span></pre></div></div>

<p>But, of course, just when you think you are nearing completion, there&#8217;s some line lurking somewhere to bite you.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">js<span style="color: #008080;">::</span><span style="color: #007788;">Value</span> val <span style="color: #000080;">=</span> ...
<span style="color: #007788;">JSFlowLabel</span> <span style="color: #0000ff;">const</span> <span style="color: #000040;">*</span>lab <span style="color: #000080;">=</span> ...
&nbsp;
<span style="color: #007788;">val</span>.<span style="color: #007788;">setPrivate</span><span style="color: #008000;">&#40;</span>lab<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>And what, pray tell, is the signature of <code>setPrivate(...)</code> ?</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> setPrivate<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span> <span style="color: #000040;">*</span>data<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>Oh, well that&#8217;s easy to fix, I think to myself. I&#8217;ll just overload a <code>const</code> version and dispatch.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> setPrivate<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span> <span style="color: #0000ff;">const</span> <span style="color: #000040;">*</span>data<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    setPrivate<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const_cast</span><span style="color: #000080;">&lt;</span><span style="color: #0000ff;">void</span> <span style="color: #000040;">*</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>data<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Having got this far, I still have some hope things will work out. I start the compiler to test my changes, and wonder a bit about what deep ruminations about data have led the compiler to draw such a sharp philosophical distinction between <code>void</code> and <code>const void</code>. And despite these wonderful distinctions, I&#8217;m still never allowed to make data of type <code>void</code>, only functions that can return a <code>void</code> whatever that means, &#8230; wait, can I have a function returning a <code>const void</code>? If I continue this line of thought, will I become as useless as a philosopher? Does enough rumination about <code>void</code> type your thoughts as <code>void</code>? Is the brain-rot setting in? Will I ever be able to recover the damage C++ has caused me?. Oh, yeah, back to my story&#8230;</p>
<p>So, I was thinking things might work themselves out, and (at worst) I&#8217;d have to make a few more wrapper overloads to some system-level functions. But NO! my very sanity was soon challenged by the compiler:</p>
<pre lang="">
../jsfun.cpp:1158: error: call of overloaded ‘setPrivate(NULL)’ is ambiguous
../jsobj.h:742: note: candidates are: void JSObject::setPrivate(void*)
../jsobj.h:747: note:                 void JSObject::setPrivate(const void*)
</pre>
<p>At this point my all my thoughts were dumped to <code>/dev/null</code>. The C++ typing system is clearly more depraved than I am, so it wins this round!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cogitolingua.net/blog/2011/02/16/const-correctness/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Type-dispatch with Exceptions</title>
		<link>http://www.cogitolingua.net/blog/2011/01/08/type-dispatch-with-exceptions/</link>
		<comments>http://www.cogitolingua.net/blog/2011/01/08/type-dispatch-with-exceptions/#comments</comments>
		<pubDate>Sat, 08 Jan 2011 09:00:03 +0000</pubDate>
		<dc:creator>erich</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Comp*]]></category>
		<category><![CDATA[Fun]]></category>
		<category><![CDATA[Ideas]]></category>

		<guid isPermaLink="false">http://www.cogitolingua.net/blog/?p=436</guid>
		<description><![CDATA[<p>I&#8217;m one of those Object Oriented programmers that consider type-inspection to be a design flaw. Much to my chagrin, I&#8217;ve found myself making occasional use of the Java instanceof keyword. In my most recent class lecture, we discussed Exceptions, and I later realized that one could essentially type-dispatch using the exception mechanism, because the catch [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m one of those Object Oriented programmers that consider type-inspection to be a design flaw. Much to my chagrin, I&#8217;ve found myself making occasional use of the Java  <code>instanceof</code> keyword. In my most recent class lecture, we discussed Exceptions, and I later realized that one could essentially type-dispatch using the exception mechanism, because the <code>catch</code> blocks will trigger on the exception type. I experimented a bit, and discovered that this trigger behaves polymorphically (as I expected). I don&#8217;t know what use this is, other than a bit of craziness and verbosity.</p>
<p>First, we&#8217;ll create a hierarchy of messages:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">class</span> Message <span style="color: #000000; font-weight: bold;">extends</span> <span style="color: #003399;">Throwable</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #003399;">String</span> contents<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> PrivateMessage <span style="color: #000000; font-weight: bold;">extends</span> Message
<span style="color: #009900;">&#123;</span>
    <span style="color: #003399;">String</span> msg <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>	
    <span style="color: #000000; font-weight: bold;">public</span> PrivateMessage<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> msg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">msg</span> <span style="color: #339933;">=</span> msg<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> contents<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;(private)&quot;</span> <span style="color: #339933;">+</span> msg<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> PrivateMessage <span style="color: #000000; font-weight: bold;">extends</span> Message
<span style="color: #009900;">&#123;</span>
    <span style="color: #003399;">String</span> msg <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>	
        <span style="color: #000000; font-weight: bold;">public</span> PrivateMessage<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> msg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">msg</span> <span style="color: #339933;">=</span> msg<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> contents<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;(private)&quot;</span> <span style="color: #339933;">+</span> msg<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Then we&#8217;ll create a Sender and Receiver to test out a message pass.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Sender
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">Receiver</span> r <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Receiver</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        r.<span style="color: #006633;">message</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> PrivateMessage<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;hello&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        r.<span style="color: #006633;">message</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> PublicMessage<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;world&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> <span style="color: #003399;">Receiver</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> message<span style="color: #009900;">&#40;</span>Message msg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> msg<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span>PrivateMessage pm<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;got a private message: &quot;</span> <span style="color: #339933;">+</span> pm.<span style="color: #006633;">contents</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span>PublicMessage pm<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;got a public message: &quot;</span> <span style="color: #339933;">+</span> pm.<span style="color: #006633;">contents</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span>Message m<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unknown message:&quot;</span> <span style="color: #339933;">+</span> m.<span style="color: #006633;">contents</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Lo, and Behold! when the program is run, we get the expected output:</p>
<pre lang="">
got a private message: (private)hello
got a public message: (public)world
</pre>
<p>I really have no idea if this feature is useful or just crazy verbiage for what could easily have been a daisy-chain of <code>instanceof</code> tests. Java makes it especially complicated because you must extend the <code>Throwable</code> class, in order to implement the messages as exceptions. Perhaps in languages without runtime type inspection this pattern might come in useful.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cogitolingua.net/blog/2011/01/08/type-dispatch-with-exceptions/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Interface Extension</title>
		<link>http://www.cogitolingua.net/blog/2010/11/07/interface-extension/</link>
		<comments>http://www.cogitolingua.net/blog/2010/11/07/interface-extension/#comments</comments>
		<pubDate>Mon, 08 Nov 2010 01:50:25 +0000</pubDate>
		<dc:creator>erich</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Comp*]]></category>
		<category><![CDATA[Ideas]]></category>

		<guid isPermaLink="false">http://www.cogitolingua.net/blog/?p=397</guid>
		<description><![CDATA[<p>I&#8217;ve been programming an alpha-beta AI to play variants of connect-k games. For example, connect-3 on a 3&#215;3 board with gravity off is tic-tac-toe, connect-5 on a 19&#215;19 board with gravity off is the basis of go-moku, while connect-4 on a 7×6 board with gravity on is connect four.</p> <p>Along the way, I&#8217;ve made myself [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been programming an <a href="http://en.wikipedia.org/wiki/Alpha-beta_pruning">alpha-beta</a> AI to play variants of connect-k games. For example, connect-3 on a 3&#215;3 board with gravity off is tic-tac-toe, connect-5 on a 19&#215;19 board with gravity off is the basis of <a href="http://en.wikipedia.org/wiki/Gomoku">go-moku</a>, while connect-4 on a 7×6 board with gravity on is <a href="http://en.wikipedia.org/wiki/Connect_Four">connect four</a>.</p>
<p>Along the way, I&#8217;ve made myself a class to store a board position. This is a simple class consisting of two <code lang="cpp">int</code>&#8216;s. I want to use <code>int</code> because it can store <code>-1</code> which is clearly an invalid position. I can then make a convenient method <code lang="cpp">bool isValid();</code> that can be used to query the position to see if it lies on the board. But, what about positions that are beyond the board size? The <code lang="cpp">isValid()</code> method should clearly say <code lang="cpp">false</code> if it does not lie on the board, yet the position class <em>shouldn&#8217;t</em> have knowledge about the board size!</p>
<p>Given the limitation of C++ (my implementation language of choice), I&#8217;ve given the board a method for testing the validity of a point: <code lang="cpp">bool isValid(Position const&#038; pos) const</code>. Semantically though, I&#8217;d rather say</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">pos.<span style="color: #007788;">isValid</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p> over</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">m_board<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>isValid<span style="color: #008000;">&#40;</span>pos<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>So, what do I <em>really</em> want? I want interface extensions! Within the board class, I would like to extend the methods that are available on the point class. I&#8217;m willing to limit the implementation of such methods to using all items within scope at the site of implementation, and all publicly visible methods on point itself. The plan is to allow something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">class</span> Board <span style="color: #008000;">&#123;</span>
    ...
    <span style="color: #0000ff;">void</span> move<span style="color: #008000;">&#40;</span>Player player, Point <span style="color: #0000ff;">const</span> <span style="color: #000040;">&amp;</span>pos<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
       ASSERT<span style="color: #008000;">&#40;</span>pos.<span style="color: #007788;">isValid</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
       ...
    <span style="color: #008000;">&#125;</span>
&nbsp;
    func <span style="color: #008000;">&#40;</span>Point p<span style="color: #008000;">&#41;</span> isValid<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">bool</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span> <span style="color: #000080;">&lt;</span> p.<span style="color: #007788;">x</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">&amp;&amp;</span> p.<span style="color: #007788;">x</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">&lt;</span> this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>numCols
             <span style="color: #000040;">&amp;&amp;</span> <span style="color: #0000dd;">0</span> <span style="color: #000080;">&lt;</span> p.<span style="color: #007788;">y</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">&amp;&amp;</span> p.<span style="color: #007788;">y</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">&lt;</span> this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>numRows<span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The declaration of <code lang="cpp">isValid()</code> is not valid C++. I&#8217;ve borrowed both the syntax and idea of interface extension from Google&#8217;s <a href="http://golang.org/">go</a>. The <code lang="cpp">this</code> pointer is, of course, implicit for all methods declared in the Board class, ala C++ rules. What&#8217;s funky though, is that the <code lang="cpp">isValid()</code> method now has <em>two</em> first arguments! When writing <code lang="cpp">pos.isValid()</code>, the position is explicitly present as a first argument, and the board is implicitly present because of scoping rules. So the call, which depends on data from both parties, is only valid for methods declared in the scope of the Board class.</p>
<p>Here&#8217;s a challenge: make a syntax that would clearly express the dependence on <em>two</em> first arguments!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cogitolingua.net/blog/2010/11/07/interface-extension/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Threaded Image Tiling</title>
		<link>http://www.cogitolingua.net/blog/2008/07/28/threaded-image-tiling/</link>
		<comments>http://www.cogitolingua.net/blog/2008/07/28/threaded-image-tiling/#comments</comments>
		<pubDate>Mon, 28 Jul 2008 07:24:31 +0000</pubDate>
		<dc:creator>erich</dc:creator>
				<category><![CDATA[code]]></category>

		<guid isPermaLink="false">http://cogitolingua.net/wordpress/index.php/2008/07/28/threaded-image-tiling/</guid>
		<description><![CDATA[<p>For quite some time now I&#8217;ve wanted to do a program that demonstrates Image Tiling using threads. Everyone should be familiar with the results of this technique, it&#8217;s used in Google Maps, Google Earth, NASA Worldwind, KDE&#8217;s Marble, and the like.</p> <p>So, to begin I started off looking for example of how this is accomplished [...]]]></description>
			<content:encoded><![CDATA[<p>For quite some time now I&#8217;ve wanted to do a program that demonstrates Image Tiling using threads. Everyone should be familiar with the results of this technique, it&#8217;s used in Google Maps, Google Earth, <a href="http://worldwind.arc.nasa.gov/">NASA Worldwind</a>, KDE&#8217;s <a href="http://edu.kde.org/marble/">Marble</a>, and the like.</p>
<p>So, to begin I started off looking for example of how this is accomplished in the real world. I found a series of posts about Marble&#8217;s Secrets (<a href="http://www.kdedevelopers.org/node/3269">Part I: Behind the Scenes</a>, <a href="http://www.kdedevelopers.org/node/3272">Part II: Walking in the shoes of Slartibartfast</a>, <a href="http://www.kdedevelopers.org/node/3275">Part III: The Earth in a Download</a>). While these didn&#8217;t tell me what happens in the gory detail, it gave me enough of an idea that I&#8217;m not too terribly lost when wandering around the <a href="http://edu.kde.org/marble/obtain.php">source code</a>.</p>
<p>The first thing I noticed is that Marble doesn&#8217;t use the QGraphics framework, and they opted to do all their own painting (I assume they went to the trouble so that they would be able to do Spherical distortion on their quadtiles). So, I&#8217;m not able to get away with easily stealing stuff from Marble.</p>
<p>Track 2: Since I&#8217;ve already done one project that would breakup an image into tiles; The real core of the problem becomes threading the loading and unloading of these tiles. So I turned to <a href="http://doc.trolltech.com/4.4/threads-mandelbrot.html">Trolltech&#8217;s Mandelbrot example</a>.</p>
<p>Before we begin, we should remember something about QThreads. Namely, that a QThread instance has affinity for the thread that created it, <b>not to itself</b>. I had to discover this the hard way; but the issue is discussed in <a href="http://chaos.troll.no/~ahanssen/devdays2007/DevDays2007-Threading.pdf">slide 42 of Bradly Huges&#8217; talk</a> at Trolltech&#8217;s DevDays, 2007. The point of this is that, if you make a subclass of QThread called MyThread, then objects created in MyThread&#8217;s constructor actually reside in the thread that instantiated MyThread. I initially expected them to reside in their own thread, to which the MyThread class would provide an interface. So, from a software engineering perspective, the thing to do is create a QThread and instantiate your worker objects, then move those objects to the QThread.</p>
<p>Now, grab a big image to play with, a map of the <a href="http://rodcorp.typepad.com/rodcorp/images/tube_walklines_final_lm.gif">London underground</a>, which is crisp and has detail that you won&#8217;t be able to decipher when zoomed out. (It&#8217;s also not geographically correct, hence the need for &#8216;walklines&#8217;)</p>
<p>From an engineering point of view it&#8217;s really convenient to be able to map from image coordinates and zoom level to a designated and unique TileId. This allows us to have very fast lookups for images that will be kept in hashtables and caches. To accomplish this we shamelessly swipe the <code>TileId</code> class from <code>Marble/src/lib</code>. A quick check of it&#8217;s internals reveals that it will be suitable to our needs.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">TileId<span style="color: #008080;">::</span><span style="color: #007788;">TileId</span><span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">int</span> zoomLevel, <span style="color: #0000ff;">int</span> tileX, <span style="color: #0000ff;">int</span> tileY <span style="color: #008000;">&#41;</span>
  <span style="color: #008080;">:</span> m_zoomLevel<span style="color: #008000;">&#40;</span> zoomLevel <span style="color: #008000;">&#41;</span>, m_tileX<span style="color: #008000;">&#40;</span> tileX <span style="color: #008000;">&#41;</span>, m_tileY<span style="color: #008000;">&#40;</span> tileY <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
TileId<span style="color: #008080;">::</span><span style="color: #007788;">TileId</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
  <span style="color: #008080;">:</span> m_zoomLevel<span style="color: #008000;">&#40;</span> <span style="color: #0000dd;">0</span> <span style="color: #008000;">&#41;</span>, m_tileX<span style="color: #008000;">&#40;</span> <span style="color: #0000dd;">0</span> <span style="color: #008000;">&#41;</span>, m_tileY<span style="color: #008000;">&#40;</span> <span style="color: #0000dd;">0</span> <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">bool</span> operator<span style="color: #000080;">==</span><span style="color: #008000;">&#40;</span> TileId <span style="color: #0000ff;">const</span><span style="color: #000040;">&amp;</span> lhs, TileId <span style="color: #0000ff;">const</span><span style="color: #000040;">&amp;</span> rhs <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">return</span> lhs.<span style="color: #007788;">m_zoomLevel</span> <span style="color: #000080;">==</span> rhs.<span style="color: #007788;">m_zoomLevel</span>
        <span style="color: #000040;">&amp;&amp;</span> lhs.<span style="color: #007788;">m_tileX</span> <span style="color: #000080;">==</span> rhs.<span style="color: #007788;">m_tileX</span>
        <span style="color: #000040;">&amp;&amp;</span> lhs.<span style="color: #007788;">m_tileY</span> <span style="color: #000080;">==</span> rhs.<span style="color: #007788;">m_tileY</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
uint qHash<span style="color: #008000;">&#40;</span> TileId <span style="color: #0000ff;">const</span><span style="color: #000040;">&amp;</span> tid <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    quint64 tmp <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>quint64<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span>tid.<span style="color: #007788;">m_zoomLevel</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #0000dd;">36</span><span style="color: #008000;">&#41;</span>
        <span style="color: #000040;">+</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>quint64<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span>tid.<span style="color: #007788;">m_tileX</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #0000dd;">18</span><span style="color: #008000;">&#41;</span>
        <span style="color: #000040;">+</span> <span style="color: #008000;">&#40;</span>quint64<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span>tid.<span style="color: #007788;">m_tileY</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">return</span> qHash<span style="color: #008000;">&#40;</span> tmp <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>We also want to add some convenience functions for the translation of <code>TileId</code>&#8216;s to actual image sizes. To do this we first add <code>tileSizeX</code> and <code>tileSizeY</code> parameters to the <code>TileId</code> header, and prototypes for the conversion functions.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">class</span> TileId
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
        ...
        <span style="color: #007788;">QRect</span> rect<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span><span style="color: #008080;">;</span>
        QSize size<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span><span style="color: #008080;">;</span>
        ...
    <span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
        ...
        <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">int</span> tileSizeX<span style="color: #008080;">;</span>
        <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">int</span> tileSizeY<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>And the requisite definitions:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">TileId<span style="color: #008080;">::</span><span style="color: #007788;">tileSizeX</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">25</span><span style="color: #008080;">;</span>
TileId<span style="color: #008080;">::</span><span style="color: #007788;">tileSizeY</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">25</span><span style="color: #008080;">;</span>
&nbsp;
QRect TileId<span style="color: #008080;">::</span><span style="color: #007788;">rect</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">return</span> QRect<span style="color: #008000;">&#40;</span> m_tileX, m_tileY,
                  m_zoomLevel <span style="color: #000040;">*</span> TileId<span style="color: #008080;">::</span><span style="color: #007788;">tileSizeX</span> <span style="color: #000040;">+</span> <span style="color: #0000dd;">1</span>,
                  m_zoomLevel <span style="color: #000040;">*</span> TileId<span style="color: #008080;">::</span><span style="color: #007788;">tileSizeY</span> <span style="color: #000040;">+</span> <span style="color: #0000dd;">1</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
QSize TileId<span style="color: #008080;">::</span><span style="color: #007788;">size</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">return</span> QSize<span style="color: #008000;">&#40;</span> TileId<span style="color: #008080;">::</span><span style="color: #007788;">tileSizeX</span><span style="color: #000040;">+</span><span style="color: #0000dd;">1</span>, TileId<span style="color: #008080;">::</span><span style="color: #007788;">tileSizeY</span><span style="color: #000040;">+</span><span style="color: #0000dd;">1</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The reason for the <code>+1</code>&#8216;s is that we wish to have one pixel of overlap on all our tiles, at all zoom levels. This slightly improves image rendering within the QGraphics framework. We&#8217;ll be treating the <code>rect()</code> as the clipped tile out of the source image, and the <code>size()</code> as the actual size that the tile will be once on screen. Given these formulae, a level 1 tile will mean native resolution, while a level 10 tile will be zoomed way out.</p>
<p>Initially I&#8217;d decided that we would load and unload the tiles dynamically onto/from a subclass of <code>QGraphicsScene</code>. After writing some code, and browsing around I realized that this may not be the best plan. The <code>QGraphicsScene</code> is really supposed to be a model for attached <code>QGraphicsView</code>&#8216;s, it&#8217;s setup so that you can have more than one view attached to a single model. I browsed around the internal code of <code>QGraphicsView</code> to see where it asks for rendered updates of the <code>QGraphicsScene</code> but wasn&#8217;t really able to find it. Anyway, it&#8217;s not clear to me that dynamic loading and unloading of <code>QGraphicsPixmapItem</code> is really the right way to go about this, especially so if I don&#8217;t have easy access to a list of regions (and zoomlevels) being viewed.</p>
<p>Looking back at the Marble project. They solved this problem by creating their own <code>MarbleMap</code> class that interacts with a custom <code>MarbleModel</code>. The <code>MarbleMap</code> gets Tiles (images), Vectors (political borders, coastlines), and Placemarks from the <code>MarbleModel</code>. It then uses this info to render a picture of the Globe with appropriate image projections by composition of layers. (Actually, <code>MarbleMap::paint()</code> calls <code>MarbleModel::paintGlobe()</code> and then paints the layers on top of that. Naturally they both use the custom <code>GeoPainter</code> class).</p>
<p>Right now I&#8217;m somewhat lost on where to head next, so I&#8217;ll be punting this topic until next weekend. So far my options seem to be:</p>
<ol>
<li>Make custom rendering widget and associated model, ala Marble</li>
<li>Go ahead with the Graphics Framework, but with the caveat that users might not be able to use more than one <code>QGraphicsView</code> on the customized scene.</li>
<ul>
<li>custom <code>QGraphicsPixmapItem</code> that knows how to fetch and delete it&#8217;s image data in it&#8217;s own <code>QThread</code>. The drawback being the spawing of as many threads as there are tiles.</li>
<li>potentially might have to create custom <code>QGraphicsView</code> that explicitly hand viewing parameters to a custom <code>QGraphicsScene</code></li>
<li>the custom <code>QGraphicsScene</code> could manage a set of worker threads, and store the pixmaps in a cache, then the <code>QGraphicsScene</code> is responsible for all the memory management of all items in the scene. At the moment this seem the most attractive path.</li>
</ul>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.cogitolingua.net/blog/2008/07/28/threaded-image-tiling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Bitstreams</title>
		<link>http://www.cogitolingua.net/blog/2008/03/17/bitstreams/</link>
		<comments>http://www.cogitolingua.net/blog/2008/03/17/bitstreams/#comments</comments>
		<pubDate>Mon, 17 Mar 2008 16:16:12 +0000</pubDate>
		<dc:creator>erich</dc:creator>
				<category><![CDATA[code]]></category>

		<guid isPermaLink="false">http://fruitbat.kicks-ass.net/wordpress/index.php/2008/03/17/bitstreams/</guid>
		<description><![CDATA[<p>This past weekend I spent an inordinate amount of time writing a small set of code that will allow the fetching of bits (rather than bytes) from a FILE *. For now this only supports reading, not writing. It&#8217;s meant to be used in an upcoming piece of work that transcodes mpeg video streams, into [...]]]></description>
			<content:encoded><![CDATA[<p>This past weekend I spent an inordinate amount of time writing a small set of code that will allow the fetching of bits (rather than bytes) from a <code>FILE *</code>. For now this only supports reading, not writing. It&#8217;s meant to be used in an upcoming piece of work that transcodes mpeg video streams, into image feature, or 3D-model streams. At any rate, it&#8217;s probably useful for other things as well. (Works for Macs and Linux, passed tests for both endian architectures).<br />
<a href='http://www.cogitolingua.net/blog/wp-content/uploads/2008/03/bitstream.h' title='bitstream.h'>bitstream.h</a><br />
<a href='http://www.cogitolingua.net/blog/wp-content/uploads/2008/03/test_bitstream.c' title='test_bitstream.c'>test_bitstream.c</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cogitolingua.net/blog/2008/03/17/bitstreams/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

