<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Shattered Terminal</title>
	
	<link>http://shatteredterminal.com</link>
	<description>i don't have a tagline yet</description>
	<lastBuildDate>Thu, 12 Nov 2009 02:07:37 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/ShatteredTerminal" type="application/rss+xml" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
		<title>Google Wave account first preview</title>
		<link>http://feedproxy.google.com/~r/ShatteredTerminal/~3/91_W1pU9ri8/</link>
		<comments>http://shatteredterminal.com/2009/11/google-wave-account-first-preview/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 16:17:18 +0000</pubDate>
		<dc:creator>shards</dc:creator>
				<category><![CDATA[Random]]></category>
		<category><![CDATA[collaboration]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[wave]]></category>

		<guid isPermaLink="false">http://shatteredterminal.com/?p=221</guid>
		<description>I finally had a chance to play around with my Google Wave account, now that I&amp;#8217;m slightly freer. Well, to be really honest, at first, I was a little lost. I didn&amp;#8217;t have many contacts with Wave accounts yet (at least not in my highly contacted group of friends). Plus, I was clueless on what [...]</description>
			<content:encoded><![CDATA[<p>I finally had a chance to play around with my Google Wave account, now that I&#8217;m slightly freer. Well, to be really honest, at first, I was a little lost. I didn&#8217;t have many contacts with Wave accounts yet (at least not in my highly contacted group of friends). Plus, I was clueless on what I wanted to do. Well, the most natural step to take would be to invite more friends to join Wave. That was exactly what I did. I invited a couple of friends to Wave. (Yes, I was pretty lucky to have a Wave account from a friend who is a Googler, hence the extra invites.)</p>
<p>Didn&#8217;t take long before a few of them got the invites soon afterwards. I think it takes the Wave team at least a day or two to send an invite once you nominate your friends. Anyway, now we have more interesting stuffs to do.</p>
<p>The first wave: I started a wave on the recipe of the chicken katsu my girlfriend and I cooked last weekend. I might not look like it, but I do cook often enough, and the katsu was really good! Even my girlfriend&#8217;s sister, who has a high standard for food, liked it. Well, back to the point, it was kind of fun to write the recipe in Wave. But wait a sec, I can do that just using Google Docs, can&#8217;t I? Or even this blog. Well, let&#8217;s put that thought on hold for a moment&#8230;</p>
<p>The second wave: my girlfriend went online and she started playing with her Wave account. She was initially confused. So we both started a wave (oh, and I shared the katsu recipe wave with her) and started experimenting. This is where Wave really shines. We were able to edit any of the sub-waves together and the changes appear live on the other person&#8217;s Wave account. I can see exactly where she&#8217;s editing and can even reply to her post before she finished writing. We also played (well, I did) with the playback function. Really cool!</p>
<p>The third wave: well, I am supposed to write an article for this small blog-based publication that my friend is running. Since she has a Wave account too (and, like me, has no idea what to do with it), I suggested that we might want to try writing the article as a wave. My idea would be to write the article (outline and the actual article), brainstorms, and have her editing the article as necessary. Thought that is a neat idea, but we&#8217;ll only be able to test that next week since I&#8217;m still kind of busy this week. Seems fun though! Imagine live collaboration on an article, bouncing ideas through a wave or gtalk, while writing the article at the same time. Plus, I&#8217;ll be able to see her edits appearing live on my wave.</p>
<p>Well, anyway, back to the thought that I put on hold some moments ago: Google Wave equals Google Docs? Is that true? Well, yes and no! Wave can indeed work like Google Docs (well, right now minus the spreadsheet/presentation stuffs, but I bet there will be a gadget to take care of that soon). And that is indeed the point! Wave is Google Docs + GTalk + GMail + wiki! It&#8217;s like this all-in-one, all encompassing collaborative solutions. Cool? Hell yeah. Will it work? Only time will tell.</p>
<p>Well, I had fun waving today. But I shall stop here. Still have a presentation to write for Monday and I need to get a draft of it by tomorrow. ):</p>
<img src="http://feeds.feedburner.com/~r/ShatteredTerminal/~4/91_W1pU9ri8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://shatteredterminal.com/2009/11/google-wave-account-first-preview/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://shatteredterminal.com/2009/11/google-wave-account-first-preview/</feedburner:origLink></item>
		<item>
		<title>Largest value sub-array [part 1]</title>
		<link>http://feedproxy.google.com/~r/ShatteredTerminal/~3/R1EYGk_m24c/</link>
		<comments>http://shatteredterminal.com/2009/11/largest-value-sub-array-part-1/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 05:01:27 +0000</pubDate>
		<dc:creator>shards</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[dynamic programming]]></category>

		<guid isPermaLink="false">http://shatteredterminal.com/?p=215</guid>
		<description>I was teaching a bunch of freshman the other day. One of the questions that came up was to determine the largest value sub-array given an array of integers. Obviously, the value is the array can be negative. There are two variants of the questions, one to find the actual maximum value when each of [...]</description>
			<content:encoded><![CDATA[<p>I was teaching a bunch of freshman the other day. One of the questions that came up was to determine the largest value sub-array given an array of integers. Obviously, the value is the array can be negative. There are two variants of the questions, one to find the actual maximum value when each of the members of the sub-array are added together, and the second variant is to actually find the start and ending location of the sub-array.</p>
<p>We will first consider the first variant to arrive at optimum answer.</p>
<p>A simple answer would be to perform brute force search in the array, considering each position as possible starting and ending point. Time complexity: O(n^2). Not very good eh? Can we improve on this? Yes, we can if we use dynamic programming. For many of us, the algorithm came up as obvious, but I realize that it is really not that simple for students new to programming to come up with a correct algorithm. To answer this, I tried to explain the concept behind the algorithm: for each element of the array, we find the maximum value sub-array that ends at that element. This value can either be the value of the element itself (meaning starting at the element and ending at the particular element) or the maximum value sub-array ending at the previous element added to the value of the element. (The latter only occurs if the maximum value sub-array at previous location is not negative.) There you go, we have a recurrence relation: given an array A, let v(k) be the maximum value of any sub-array ending at position k, where k ranging from 0 inclusive to N exclusive, N is the length of the array. Hence we have:</p>
<p>v(0) = A[0]<br />
v(k) = max{v(k-1) + A[k], A[k]} if k &gt; 0</p>
<p>The maximum value will be given by max{v_i} for i from 0 to N-1. To implement this in Java, we make several optimization. Firstly, we can opt for recursive method or dynamic programming. Both will take O(n) time but since we&#8217;re using Java, we would rather use dynamic programming since there is no <a href="http://en.wikipedia.org/wiki/Tail_recursion">tail call optimization</a> in Java. Then, rather than finding the maximum value using max{v_i} at the end, we keep a running maximum throughout the running of the algorithm and return it. We also note that v(k-1) + A[k] will only be greater than A[k] iff v(k-1) is greater than 0. Here is how the code goes (this is a rather faithful implementation, it uses the same variable names as the recurrence relation above to make it easier to see):</p>
<pre name="code" class="java">public static int calculateMaxValue(int[] A) {
  int[] v = new int[A.length];
  int max = v[0] = A[0];
  for (int i = 1; i < A.length; ++i) {
    v[i] = A[i];
    if (v[i-1] > 0) {
      v[i] += v[i-1];
    }

    if (v[i] > max) {
      max = v[i];
    }
  }
  return max;
}</pre>
<p>This algorithm has O(n) time complexity.</p>
<p>What else can we do to optimize this code? Well, we don&#8217;t really need to keep an array of maximum values. We notice that at any point of time, to calculate the value of v(k), we only need the value of A[k] and v(k-1). We just turn an O(n) space requirement to O(1).</p>
<pre name="code" class="java">public static int calculateMaxValue(int[] A) {
  int max = A[0], current = A[0];
  for (int i = 1; i < A.length; ++i) {
    if (current < 0) current = 0;
    current += A[i];

    if (current > max) max = current;
  }
  return max;
}</pre>
<p>Voila! We shall continue with the second variant next time. (:</p>
<img src="http://feeds.feedburner.com/~r/ShatteredTerminal/~4/R1EYGk_m24c" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://shatteredterminal.com/2009/11/largest-value-sub-array-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://shatteredterminal.com/2009/11/largest-value-sub-array-part-1/</feedburner:origLink></item>
		<item>
		<title>Random sample from a long linked list</title>
		<link>http://feedproxy.google.com/~r/ShatteredTerminal/~3/rYn1V8XxFdY/</link>
		<comments>http://shatteredterminal.com/2009/11/random-sample-from-a-long-linked-list/#comments</comments>
		<pubDate>Thu, 05 Nov 2009 04:08:35 +0000</pubDate>
		<dc:creator>shards</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[probability interview]]></category>

		<guid isPermaLink="false">http://shatteredterminal.com/?p=192</guid>
		<description>Sorry for the long no-update period. I had quite a few posts that I wrote half way in my posting queues but haven&amp;#8217;t got the time to finish them since I was very busy with work and research. Plus I&amp;#8217;m currently learning basic German and that really sucks out a lot of my free time. [...]</description>
			<content:encoded><![CDATA[<p>Sorry for the long no-update period. I had quite a few posts that I wrote half way in my posting queues but haven&#8217;t got the time to finish them since I was very busy with work and research. Plus I&#8217;m currently learning basic German and that really sucks out a lot of my free time. (Though German is really, really fun; I really hope that one day, I can actually work&mdash;maybe temporarily, maybe permanently&mdash; in Germany.)</p>
<p>Anyway, a friend of mine is currently applying for jobs in several &#8220;big&#8221; companies (you know, the Google-Microsoft-Apple kind?). So he was preparing for his interview by hunting quite a few online questions. One of the questions he asked reminded me of a question I used to use to exemplify the kind of questions these companies used in their technical interview:</p>
<blockquote><p>Given a head pointer to a (possibly very long) linked list of unknown length, devise a method to sample m members at random. Ensure that the method yields equal probability for each element in the linked list to be picked.</p></blockquote>
<p>Obviously we can traverse the list once to find the length, generate m random numbers from 1 to length of the list and traverse the list another time to pick up these items. A common question would be to prevent you from going through the list more than once. Say the list is very long, the disk I/O you need to get the items from harddisk (even after making sure the items are arranged well that it minimizes cache misses) would make traversal a very expensive operation and hence should be minimized.</p>
<p>The solution I have is inspired by the fact that if the linked list contained m or less elements, I have no choice but to pick all m of them. Hence, the main idea of the solution would be to pick the first m elements and keeping track of k&mdash;the number of elements we have seen so far. When we encounter a new element, the new element has an m/k chance of being picked. If it is picked, we dropped 1 of the previously selected m elements at random. We can easily prove that this indeed yields the correct probability via mathematical induction.</p>
<p>Now of course it won&#8217;t be fun to implement this in Java or C++, so I decided to use Scheme to code this, just for the fun of it. The solution is surprisingly short and pretty. Here goes:</p>
<pre name="code" class="scheme">(define (sample-m lst m)
  (define (helper curr k m-vec)
    (if (empty? curr)
        (if (< k m)
            lst
            (vector->list m-vec))
        (let ((pos (random k)))
          (cond ((<= k m)
                 (vector-set! m-vec
                              (- k 1)
                              (car curr)))
                ((< pos m)
                 (vector-set! m-vec
                              pos
                              (car curr))))
          (helper (cdr curr) (+ k 1) m-vec))))
  (helper lst 1 (make-vector m)))

;;; Let's test this!
(sample-m (build-list 1000 values) 7)</pre>
<p>EDIT: I decided to try writing a version for Java as well. Here is the Java code:</p>
<pre name="code" class="java">public class LinkedListSampler {
  private static Random rand = new Random();
  public static &lt;T&gt; List&lt;T&gt; sample(
      LinkedList&lt;T&gt; list, int m) {
    ArrayList&lt;T&gt; samples = new ArrayList&lt;T&gt;(m);
    int k = 0;
    for (T element : list) {
      int pos = k++;
      if (pos &lt; m) {
        samples.add(element);
      } else if ((pos = rand.nextInt(k)) &lt; m) {
        samples.set(pos, element);
      }
    }
    return samples;
  }
}</pre>
<p>EDIT 2: Btw, seriously, the Java code is just for fun. Just imagine that LinkedList does not have a size method, will ya? ;)</p>
<img src="http://feeds.feedburner.com/~r/ShatteredTerminal/~4/rYn1V8XxFdY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://shatteredterminal.com/2009/11/random-sample-from-a-long-linked-list/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://shatteredterminal.com/2009/11/random-sample-from-a-long-linked-list/</feedburner:origLink></item>
		<item>
		<title>Applying for J1 Waiver</title>
		<link>http://feedproxy.google.com/~r/ShatteredTerminal/~3/LLnPjpocGm0/</link>
		<comments>http://shatteredterminal.com/2009/10/applying-for-j1-waiver/#comments</comments>
		<pubDate>Thu, 01 Oct 2009 01:09:53 +0000</pubDate>
		<dc:creator>shards</dc:creator>
				<category><![CDATA[Random]]></category>

		<guid isPermaLink="false">http://shatteredterminal.com/?p=197</guid>
		<description>I am starting my J1 foreign residency requirement waiver application in the next few days. Anyone with such experience before? I&amp;#8217;ve heard that it is a long and painful wait. Sigh.</description>
			<content:encoded><![CDATA[<p>I am starting my J1 foreign residency requirement waiver application in the next few days. Anyone with such experience before? I&#8217;ve heard that it is a long and painful wait. Sigh.</p>
<img src="http://feeds.feedburner.com/~r/ShatteredTerminal/~4/LLnPjpocGm0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://shatteredterminal.com/2009/10/applying-for-j1-waiver/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://shatteredterminal.com/2009/10/applying-for-j1-waiver/</feedburner:origLink></item>
		<item>
		<title>ACL-IJCNLP ‘09 Blog</title>
		<link>http://feedproxy.google.com/~r/ShatteredTerminal/~3/9zhPZ5pJF_o/</link>
		<comments>http://shatteredterminal.com/2009/05/acl-ijcnlp-09-blog/#comments</comments>
		<pubDate>Wed, 13 May 2009 13:15:29 +0000</pubDate>
		<dc:creator>shards</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Random]]></category>
		<category><![CDATA[Self]]></category>
		<category><![CDATA[acl-ijcnlp]]></category>

		<guid isPermaLink="false">http://shatteredterminal.com/?p=187</guid>
		<description>I have been invited to co-ordinate the blog for ACL-IJCNLP &amp;#8216;09, a joint conference on natural language processing to be held in Singapore this August. We will be posting both general articles about NLP and computational linguistics for general public, and articles on things to do in Singapore and nearby regions. Stay tune to the [...]</description>
			<content:encoded><![CDATA[<p>I have been invited to co-ordinate the blog for ACL-IJCNLP &#8216;09, a joint conference on natural language processing to be held in Singapore this August. We will be posting both general articles about NLP and computational linguistics for general public, and articles on things to do in Singapore and nearby regions. Stay tune to the new blog! It will officially be launched next Monday, but you can already access it <a href="http://www.colips.org/blog/acl-ijcnlp-2009/">here</a> (sorry, about the design, we haven&#8217;t figured what design to use for the blog yet). Also check out the conference <a href="http://www.acl-ijcnlp-2009.org/">website</a>.</p>
<img src="http://feeds.feedburner.com/~r/ShatteredTerminal/~4/9zhPZ5pJF_o" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://shatteredterminal.com/2009/05/acl-ijcnlp-09-blog/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://shatteredterminal.com/2009/05/acl-ijcnlp-09-blog/</feedburner:origLink></item>
		<item>
		<title>Chrome Shorts</title>
		<link>http://feedproxy.google.com/~r/ShatteredTerminal/~3/Vbu85vs2ld8/</link>
		<comments>http://shatteredterminal.com/2009/04/chrome-shorts/#comments</comments>
		<pubDate>Wed, 29 Apr 2009 19:01:19 +0000</pubDate>
		<dc:creator>shards</dc:creator>
				<category><![CDATA[Random]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[film]]></category>
		<category><![CDATA[shorts]]></category>

		<guid isPermaLink="false">http://shatteredterminal.com/?p=183</guid>
		<description>OH MY GOD! The Chrome Shorts are really cute! It&amp;#8217;s as if I&amp;#8217;m turning into a small kids awestruck by some of the videos! Good timing! Have been pretty stressed up getting things right in my mind (while getting ready for exams).
Anyway, this one is the cutest! Shit! The cat and the video is just [...]</description>
			<content:encoded><![CDATA[<p>OH MY GOD! The <a href="http://chrome.blogspot.com/2009/04/11-short-films-about-browser.html">Chrome Shorts</a> are really cute! It&#8217;s as if I&#8217;m turning into a small kids awestruck by some of the videos! Good timing! Have been pretty stressed up getting things right in my mind (while getting ready for exams).</p>
<p>Anyway, this one is the cutest! Shit! The cat and the video is just so cute!</p>
<div style="margin: 0 auto;"><object width="480" height="295"><param name="movie" value="http://www.youtube.com/v/5535Ts-iOP0&#038;hl=en&#038;fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/5535Ts-iOP0&#038;hl=en&#038;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="295"></embed></object></div>
<p>(Watch the other 10 videos from YouTube&#8217;s <a href="http://www.youtube.com/googlechrome">Chrome channel</a>.</p>
<img src="http://feeds.feedburner.com/~r/ShatteredTerminal/~4/Vbu85vs2ld8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://shatteredterminal.com/2009/04/chrome-shorts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://shatteredterminal.com/2009/04/chrome-shorts/</feedburner:origLink></item>
		<item>
		<title>Introduction to Probability (book)</title>
		<link>http://feedproxy.google.com/~r/ShatteredTerminal/~3/252K7mHWVpU/</link>
		<comments>http://shatteredterminal.com/2009/04/introduction-to-probability-book/#comments</comments>
		<pubDate>Wed, 29 Apr 2009 11:12:12 +0000</pubDate>
		<dc:creator>shards</dc:creator>
				<category><![CDATA[Books]]></category>

		<guid isPermaLink="false">http://shatteredterminal.com/?p=177</guid>
		<description>I have finally decided to get this book. Have been struggling quite a bit with some more complex probability for mathematical and systems modeling and for my research. So I thought getting more rigorous grounding would help. Seems that a lot of people are recommending this book, so I thought I&amp;#8217;ll give it a try. [...]</description>
			<content:encoded><![CDATA[<div style="float:left; margin: 0 15px 15px 0;"><a href="http://www.amazon.com/gp/product/188652923X?ie=UTF8&#038;tag=shatteredterminal-20&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=188652923X"><img alt="Introduction to Probability, 2e" src="https://images-na.ssl-images-amazon.com/images/I/21pg1bYGvXL._SL160_.jpg" class="alignnone" width="116" height="144" /></a></div>
<p>I have finally decided to get this book. Have been struggling quite a bit with some more complex probability for mathematical and systems modeling and for my research. So I thought getting more rigorous grounding would help. Seems that a lot of people are recommending this book, so I thought I&#8217;ll give it a try. Will update after I completed at least several chapters of the book. (Well, the book itself won&#8217;t arrive for another week or so.)</p>
<img src="http://feeds.feedburner.com/~r/ShatteredTerminal/~4/252K7mHWVpU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://shatteredterminal.com/2009/04/introduction-to-probability-book/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://shatteredterminal.com/2009/04/introduction-to-probability-book/</feedburner:origLink></item>
		<item>
		<title>Closure in Java</title>
		<link>http://feedproxy.google.com/~r/ShatteredTerminal/~3/pNyrpT0FQnk/</link>
		<comments>http://shatteredterminal.com/2009/04/closure-in-java/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 12:56:07 +0000</pubDate>
		<dc:creator>shards</dc:creator>
				<category><![CDATA[Dynamic Languages]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[closure]]></category>

		<guid isPermaLink="false">http://shatteredterminal.com/?p=160</guid>
		<description>I believe Closure should be part of any modern language, so I was delighted to read about Closure for Java (currently a JSR draft I believe) from here. Currently, Closure is not implemented in Java and is impossible to implement in its natural form. We can attempt to implement closures using anonymous objects, but that [...]</description>
			<content:encoded><![CDATA[<p>I believe Closure should be part of any modern language, so I was delighted to read about Closure for Java (currently a JSR draft I believe) from <a href="http://www.javac.info/">here</a>. Currently, Closure is not implemented in Java and is impossible to implement in its natural form. We can attempt to implement closures using anonymous objects, but that comes with two main issue: (1) it can not access non-final variables defined in its enclosing code; (2) you have to define closure interface for every possible scenario. We really can&#8217;t do anything with the first problem; but, as we see later, we can simplify the syntax considerably. Here is an example:</p>
<pre name="code" class="java">
public interface ClosureIntReturnInt {
  public int invoke(int arg1);
}

@Test
public void testNaiveClosure() {
  final int a = 1; // This must be final!
  ClosureIntReturnInt addA =
      new ClosureIntReturnInt() {
    public int invoke(int v) {
      return v + a;
    }
  };

  assertEquals(3, addA.invoke(2));
}
</pre>
<p>This is obviously not a very good solution. So my first instinct would be to genericize the closure interface. Sure enough, it simplifies the problem by quite a bit. Here is my genericize Closure interface:</p>
<pre name="code" class="java">
public interface Closure0Arg&lt;R&gt; {
  public R invoke();
}
public interface Closure1Arg&lt;R, A1&gt; {
  public R invoke(A1 arg1);
}
public interface Closure2Args&lt;R, A1, A2&gt; {
  public R invoke(A1 arg1, A2 arg2);
}
.
.
.
</pre>
<p>Sure enough, this works fine and it becomes much easier to use. It is of course still inconvenient for people who came from functional programming world. The problem is: (1) there is no universal Closure, that means you have to keep track of the Closure type as type annotation, many, including me would love to ditch the cumbersome type annotation; (2) you have to write the interface for each number of arguments (much better than writing for each argument type of course, but still&#8230;).</p>
<p>Of course, OTOH, this is the best you can do while maintaining static checking ability. Here is an example usage:</p>
<pre name="code" class="java">
@Test
public void testClosure1Arg() {
  Closure1Arg intToString =
      new Closure1Arg&lt;String, Integer&gt;() {
    public String invoke(Integer v) {
      return v.toString();
    }
  };

  assertEquals("5", intToString.invoke(5));
}
</pre>
<p>A sharp reader would have noticed several (not-very-correct?) things happening here. First, we eliminate the generic from <code>intToString</code> type annotation. This does not change the semantics of the code and make the code looks cleaner; however, it does create an &#8220;unchecked&#8221; warning with the Java compiler. Secondly, we utilize autoboxing freely in this implementation. Since we are utilizing generics, <code>R</code>, <code>A1</code>, &#8230;, <code>An</code> must all be objects. This is obviously undesirable and ugly. However, due to autoboxing, this is no longer an issue (except performance-wise).</p>
<p>So far, this is really the best we can do while preserving static type checking. However, if we ignore additional security provided by static type checking, we can go a step further: we can introduce a <code>Closure</code> base class; the rest of the closures interface (<code>Closure1Arg</code>, etc.) will become an <strong>abstract class</strong> that extends the <code>Closure</code> class. This is where all the interesting stuffs are happening. Here is the source code for the <code>Closure</code> class.</p>
<pre name="code" class="java">
public class Closure&lt;R&gt; {
  @SuppressWarnings("unchecked")
  public R invoke(Object... args) {
    Class[] classes = new Class[args.length];
    // This is okay since generic type annotation
    // is stripped after compilation. We only
    // need to find invoke method with
    // the right number of params.
    Arrays.fill(classes, Object.class);

    try {
      // Search for correct invoke method
      // and execute it.
      Method method =
          this.getClass().getMethod(
              "invoke", classes);
      return (R) method.invoke(this, args);
    } catch (Exception e) {
      // TODO: handle exceptions correctly.
      // ClosureException is a runtime exception.
      throw new ClosureException("Error", e);
    }
  }
}

// e.g. of ClosureNArg abstract class.
public abstract class Closure1Arg&lt;R, A1&gt;
    extends Closure&lt;R&gt; {
  public abstract R invoke(A1 arg);
}
</pre>
<p>This code completely sacrifices static checking. Now we can simply have each closures to be stored in variables of <code>Closure</code> type. When <code>invoke</code> is called, the method from the base class (above) is called. It will find the correct (i.e. more specialized) <code>invoke</code> method (declared in the concrete anonymous object derived from the subclass) to call based on the type of the arguments to invoke. Here is how we can use it:</p>
<pre name="code" class="java">
@Test
public void testClosure1() {
  Closure&lt;Integer&gt; addOne =
      new Closure1Arg&lt;Integer, Integer&gt;() {
    public Integer invoke(Integer arg) {
      return arg + 1;
    }
  };
  assertEquals(3, (int) addOne.invoke(2));
}

@Test
public void testClosure2() {
  Closure&lt;Double&gt; add =
      new Closure2Args&lt;Double, Double, Double&gt;() {
    public Double invoke(Double a, Double b) {
      return a + b;
    }
  };
  assertEquals(7.5, add.invoke(4.2, 3.3));
}
</pre>
<p>Sweet! Now this is neat! Of course, we have ignored much of the static checking and replace them with dynamic, runtime checking. I have removed much of the exception checking code in <code>Closure&lt;R&gt;</code> base class to save space and focus on the meat. Again, I&#8217;d draw readers&#8217; attention to several important code fragments:</p>
<ol>
<li>We catch most of the checked exception and replaced them with unchecked runtime exception to make the usage much cleaner, this follows more closely to dynamic, interpreted language rather than static language (as with Java);</li>
<li>We readily suppress warning with <code>@SuppressWarnings</code> (heh!);</li>
<li>The code, arguably, takes a bit of performance hit, so users who are more concerned about performance should probably not use this (squeezing performance usually means messier code; closure is for elegance, not mess);</li>
<li>You may want to write simple script to autogenerate ClosureNArgs (N from 0 to however many arguments you think is reasonable; I personally generate up to 7 arguments);</li>
<li>You probably want to generate closures for void return value as well; that would make things messier (much messier) though. It is probably easier to return <code>null</code> instead.</li>
<li>Here, I opt to go for clean <code>ClosureNArgs</code> subclasses. Others may opt to add some ugliness to the subclasses and make the base class cleaner (and likely result in faster closure code). I will likely experiment with this further, and try to implement variable binding as well.</ol>
<p>I found it very interesting to implement Closure in Java; hope you do too. :)</p>
<p>EDIT: This is interesting, wonder how I missed this earlier: <a href="http://www.javac.info/closures-v05.html">Closures for the Java Programming Language (v0.5)</a>.</p>
<p>EDIT 2: I simplified <code>Closure&#038;ltR&gt;</code> a little bit more. The simplification is a result of stripping of the generic type annotation after compilation. So the base class need only hunt for invoke method with the right number of parameters.</p>
<img src="http://feeds.feedburner.com/~r/ShatteredTerminal/~4/pNyrpT0FQnk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://shatteredterminal.com/2009/04/closure-in-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://shatteredterminal.com/2009/04/closure-in-java/</feedburner:origLink></item>
		<item>
		<title>The teaching of computer science</title>
		<link>http://feedproxy.google.com/~r/ShatteredTerminal/~3/qBYicMfL7sY/</link>
		<comments>http://shatteredterminal.com/2009/04/the-teaching-of-computer-science/#comments</comments>
		<pubDate>Mon, 06 Apr 2009 20:04:33 +0000</pubDate>
		<dc:creator>shards</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Issues]]></category>
		<category><![CDATA[teaching]]></category>
		<category><![CDATA[women]]></category>

		<guid isPermaLink="false">http://shatteredterminal.com/?p=151</guid>
		<description>Today&amp;#8217;s ACM TechNews includes an article on CMU trying to buck trends of having few women in Computer Science. I agree wholeheartedly.
However, before we even get there, computer science is seriously in need of polished publicity. I have talked with several undergraduates and high school students recently and encouraged them to take up computer science. [...]</description>
			<content:encoded><![CDATA[<div id="attachment_152" class="wp-caption alignleft" style="width: 250px"><img class="size-full wp-image-152" title="Kids &amp; Computers" src="http://shatteredterminal.com/wp-content/uploads/2009/04/355874159_28c960e61b_m.jpg" alt="Kids &amp; Computers" width="240" height="240" /><p class="wp-caption-text">Kids &amp; Computers</p></div>
<p>Today&#8217;s ACM TechNews includes an <a href="http://www.pittsburghlive.com/x/pittsburghtrib/news/mostread/s_618862.html">article</a> on CMU trying to buck trends of having few women in Computer Science. I agree wholeheartedly.</p>
<p>However, before we even get there, computer science is seriously in need of polished publicity. I have talked with several undergraduates and high school students recently and encouraged them to take up computer science. In general, most of them were impressed when they heard that I majored in Computer Science. They thought that it is pretty cool as a major. However, when I asked them whether they are considering (especially the high school students) to major in computer science, the response I got was roughly this: no. &#8220;Why not?&#8221; They replied back that computer science involve lots of programming and they think that programming is hard, really hard. They also strongly equate computer science with programming and only programming. I do believe that programming is not easy, especially at the beginning, but it is not harder than, say, solving difficult physics questions, or designing chemistry experiment to confirm a hypothesis. (I was lucky to be introduced to programming, with LOGO and Basic—yes, Basic, unfortunately—in late elementary school; but most of these people have never touched any programming language before.) Few of them also think that programming is geeky, something that I would never refute; I think being geeky is cool.</p>
<p>Furthermore, even if programming were taught in schools before university, I have a strong feeling that they are being taught wrongly. Instead of being taught to appreciate the beauty of programming (recursion, abstraction, closure, memoization, etc.), teachers were more focused on getting the syntax right. That, in itself, is not too bad. However, the choice of language really do reveal the weakness of the method. Teaching C++ or Java as a first programming language is definitely not a good idea. These languages are very thick with syntax. Example to the point, I have seen loops being taught as a syntax; as for its concept, teachers keep reiterating that it is used to make a particular code loops over and over until the condition turns to become false. The explanation is correct. On the other hand, such explanation rarely extract the awe and understanding of the power of loop construct.</p>
<p>(Granted, at high school level, I am only familiar with Cambridge &#8216;A&#8217; Level syllabus for Computing, which uses C/C++, I might have too narrow a viewpoint, or even outdated.)</p>
<p>So the first thing we should straighten out is to clean up the way programming should be taught to students. I would start with Javascript (hey, something that can be applied right away on their own websites is cool and fun!), Python, or Scheme. (Yes, you&#8217;re right, I think type system only make teaching programming more convoluted without offering much direct benefits.) Picking good teachers is no longer optional. The aim should be to make students appreciate computer science as a diverse, exciting, and fun field. It should definitely not be aimed to teach students to be proficient in one (or, worse, two) programming language. Probably introducing them at younger age would make it even more effective, as students get higher exposure to it and the curriculum gets more refined as it is harder to teach the younger students. (In fact, it is probably more rational to teach visual programming technique. About half a year ago, I watched a Google Tech Talk on <a href="http://www.youtube.com/watch?v=faJ8N0giqzw">tangible functional programming</a>, where the concept of value, pair, and function/lambda is translated into intuitive visual system that allows even stronger form of composability.)</p>
<p>Certainly, putting some into good publicity will not hurt. Though I do think that we should put more effort into integrating computer science into early education (just like other sciences) to let the younger generation figures out how suitable is the major for themselves, before the stigma attached to CS becomes too deeply rooted in them.</p>
<p><strong>Acknowledgment:</strong> Photo was published by <a href="http://www.flickr.com/photos/shapeshift/">shapeshift</a> under Creative Commons (Attribution &amp; Share-Alike); <a href="http://www.flickr.com/photos/shapeshift/355874159/">link</a> to flickr page.</p>
<img src="http://feeds.feedburner.com/~r/ShatteredTerminal/~4/qBYicMfL7sY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://shatteredterminal.com/2009/04/the-teaching-of-computer-science/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://shatteredterminal.com/2009/04/the-teaching-of-computer-science/</feedburner:origLink></item>
		<item>
		<title>Steve Souders’ tech talk on writing fast code</title>
		<link>http://feedproxy.google.com/~r/ShatteredTerminal/~3/EOygPLpBsRE/</link>
		<comments>http://shatteredterminal.com/2009/04/steve-souders-tech-talk-on-writing-fast-code/#comments</comments>
		<pubDate>Sat, 04 Apr 2009 03:52:27 +0000</pubDate>
		<dc:creator>shards</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Web Programming]]></category>
		<category><![CDATA[web performance]]></category>

		<guid isPermaLink="false">http://shatteredterminal.com/?p=147</guid>
		<description>This guy is my hero on web performance technique, so I was real happy when this video was published recently in googletechtalks YouTube channel (check out the channel, it has many, many other interesting videos).
In this tech talk, he built up upon the previous tech talk (which I happened to watch live, but could not [...]</description>
			<content:encoded><![CDATA[<p><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/52gL93S3usU&#038;hl=en&#038;fs=1&#038;color1=0x2b405b&#038;color2=0x6b8ab6"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/52gL93S3usU&#038;hl=en&#038;fs=1&#038;color1=0x2b405b&#038;color2=0x6b8ab6" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></p>
<p>This guy is my hero on web performance technique, so I was real happy when this video was <a href="http://googland-dev.blogspot.com/2009/03/gd-steve-souders-life-too-short-write.html">published</a> recently in <a href="http://www.youtube.com/user/googletechtalks">googletechtalks</a> YouTube channel (check out the channel, it has many, many other interesting videos).</p>
<p>In this tech talk, he built up upon the previous tech talk (which I happened to watch live, but could not find it online) and talk about how you can take advantage of parallel Javascript downloads while maintaining any coupling you have between external scripts and inline scripts that you have. One of the techniques involve a modification of John Resig&#8217;s <a href="http://ejohn.org/blog/degrading-script-tags/">degrading script tags</a>. He also mentioned problems with iframe preventing onload events to be fired earlier. Finally, he made clear how you could flush your data early to ensure that you utilize chunked transfer. The last bit was particularly interesting. It has been in my mind recently and I have experimented quite a bit with PHP to perform this. Soon I&#8217;m going to try to figure out whether a Python (non-Apache) web server can perform similarly (I believe so). I already wrote a testing web server (based on <a href="http://docs.python.org/library/basehttpserver.html">HttpServer</a> class).</p>
<p>In PHP/Apache case, there were quite a few difficulties in making sure that chunked transfer is performed. One is to make sure that you have enough data (and specifically flush PHP output buffering otherwise). Another involves figuring out Apache&#8217;s limitation on sending a single chunk (you have to have enough data before Apache agree to push these data; worse still, if you activate gzipping, the data must exceed the minimum gzip window). Of course, the most interesting problems would be to figure out how to structure the page to ensure that you get the most out of chunked transfer. In another word, you would want to transfer as much dumb data (that can be generated real fast) as possible to utilize the time taken for the server to generate the difficult content as efficiently as possible (at that time, the browser can start downloading CSS, some images, and maybe some Javascript). Also note that the browser will start partial rendering of the page; however, the rest of the page will only be rendered when the rest of the data comes (which can be very long when you&#8217;re unlucky). So you need to make sure that the page renders fine with partial data.</p>
<p>Souders&#8217; talk revealed several more considerations that escape my own experiments in this. One is that some proxy server will buffer chunked transfer; the effect of which is that the user will get the entire page in a single monolithic transfer. Also, some browsers (Chrome and Safari) will not start partial render unless there&#8217;s enough data (2KB for Chrome, and 1KB for Safari).</p>
<img src="http://feeds.feedburner.com/~r/ShatteredTerminal/~4/EOygPLpBsRE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://shatteredterminal.com/2009/04/steve-souders-tech-talk-on-writing-fast-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://shatteredterminal.com/2009/04/steve-souders-tech-talk-on-writing-fast-code/</feedburner:origLink></item>
	</channel>
</rss>
