<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Reminiscential: of or pertaining to remembrance</title>
	<atom:link href="http://reminiscential.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://reminiscential.wordpress.com</link>
	<description>A blog about life, technology, language, politics, religion and everything else my brain stumbles upon randomly...</description>
	<lastBuildDate>Wed, 05 Oct 2011 16:07:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='reminiscential.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Reminiscential: of or pertaining to remembrance</title>
		<link>http://reminiscential.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://reminiscential.wordpress.com/osd.xml" title="Reminiscential: of or pertaining to remembrance" />
	<atom:link rel='hub' href='http://reminiscential.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Building a Google Reader plugin using Chrome extension</title>
		<link>http://reminiscential.wordpress.com/2011/10/04/building_google_reader_plugin/</link>
		<comments>http://reminiscential.wordpress.com/2011/10/04/building_google_reader_plugin/#comments</comments>
		<pubDate>Wed, 05 Oct 2011 04:02:20 +0000</pubDate>
		<dc:creator>Kevin J. Qiu</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[chrome extension]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://reminiscential.wordpress.com/?p=257</guid>
		<description><![CDATA[OK, ok, I understand. The title is a bit misleading. Google Reader isn&#8217;t open for 3rd party plugins, and there&#8217;s no indication that Google will ever. However, with Google Chrome extension, we can build such local &#8220;plugins&#8221;. What are we going to achieve? Anyone uses Google Reader to read DZone feeds? I do. DZone is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=257&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>OK, ok, I understand. The title is a bit misleading. <a href="http://reader.google.com">Google Reader</a> isn&#8217;t open for 3rd party plugins, and there&#8217;s no indication that Google will ever. However, with Google Chrome extension, we can build such local &#8220;plugins&#8221;.</p>
<h1>What are we going to achieve?</h1>
<p>Anyone uses Google Reader to read <a href="http://www.dzone.com">DZone</a> feeds? I do. DZone is a very good tech news aggregator and you can vote and comment on stories. With Google Reader, you get DZone feeds like the following. I don&#8217;t know about you but for me, sometimes I just want to read the original story without going to the DZone page. It&#8217;d be nice if they have a &#8220;click through&#8221; action (like the following) on the action bar that brings you to the original story.<br />
<a href="http://reminiscential.files.wordpress.com/2011/10/screenshot-google-reader-539-chromium.png"><img src="http://reminiscential.files.wordpress.com/2011/10/screenshot-google-reader-539-chromium.png?w=300&#038;h=100" alt="End goal" title="Screenshot-Google Reader (539) - Chromium" width="300" height="100" class="aligncenter size-medium wp-image-262" /></a></p>
<h1>Basic strategy</h1>
<p>So, how are we going to implement this feature? Chrome Extension code can be injected into the running page, and have full access to its DOM. Therefore, we can write code such that if the currently opened entry is a DZone entry, we insert &#8216;Click Through&#8217; action into the entry action bar (action bar is the bar underneath the main entry, where &#8216;Add Star&#8217;, &#8216;Like&#8217;, &#8216;Share&#8217; actions are). The &#8216;Click Through&#8217; action, when clicked, will read the feed URL, fetch it in the background, parse it and get the URL of the original story, and open the original URL in a separate tab.</p>
<p><a href="http://reminiscential.files.wordpress.com/2011/10/untitled-1.png"><img class="aligncenter size-medium wp-image-261" title="strategy" src="http://reminiscential.files.wordpress.com/2011/10/untitled-1.png?w=300&#038;h=231" alt="" width="300" height="231" /></a></p>
<h1>Create a manifest</h1>
<p>A Chrome extension must have a manifest.json file containing the metadata of the extension.</p>
<pre class="brush: jscript;">
{
    &quot;name&quot;:&quot;GReader&quot;,
    &quot;version&quot;:&quot;1.0&quot;,
    &quot;description&quot;:&quot;Enhanced Google Reader experience&quot;,
    &quot;permissions&quot;: [
        &quot;http://*.dzone.com/&quot;
    ],
    &quot;background_page&quot;:&quot;background.html&quot;,
    &quot;content_scripts&quot;:[{
        &quot;matches&quot;:[
            &quot;*://www.google.com/reader/view/*&quot;
        ],
        &quot;js&quot;:[
            &quot;lib/jquery-1.6.4.min.js&quot;,
            &quot;src/greader.js&quot;
        ],
        &quot;run_at&quot;:&quot;document_idle&quot;
    }]
}
</pre>
<p>Here we</p>
<ul>
<li>specify that the extension needs to access any URL on dzone.com including its subdomains.</li>
<li>specify the background page</li>
<li>specify the content script</li>
</ul>
<p>The &#8220;run_at&#8221; property will dictate when the content script is going to be run. Because Google Reader is a full AJAX application, we want our script to be run when the document is fully rendered.<br />
We also specify the &#8220;matches&#8221; property, so our content script is only activated when the URL matches.</p>
<h1>The content script</h1>
<p>We start with:</p>
<pre class="brush: jscript;">
(function($) {

})(jQuery);
</pre>
<p>This creates a function scope, which separates our $ variable apart from the current page&#8217;s $ variable. Google Reader (I assume, is using Google&#8217;s own closure library), already defines $ and it&#8217;s not the jQuery object. This idiom gives $ as jQuery.</p>
<p>We want to insert the &#8220;Click through&#8221; action in the entry action bar. To achieve this, we will need to listen on &#8220;DOMNodeInserted&#8221; event, and when such event happens and the node inserted is of the right CSS class name (&#8220;entry-action&#8221; here), we proceed to manipulate the DOM to add our customized actions.</p>
<pre class="brush: jscript;">
    $(&quot;#entries&quot;).live('DOMNodeInserted', function(e) {
        if (!e.target.className.match(/entry\-actions/))
            return;

        var entryAction = new EntryAction($(e.target));
        if (entryAction.entry.url.match(/^http\:\/\/feeds\.dzone\.com/)) {
            entryAction.addAction({
                'name':'Click Through',
                'fn':function(entry) {
                    chrome.extension.sendRequest({&quot;type&quot;:&quot;fetch_entry&quot;, &quot;url&quot;:entry.url}, function(response) {
                        var matched = /&lt;div class=&quot;ldTitle&quot;&gt;(.*?)&lt;\/div&gt;/.exec(response.data);
                        var href = ($(matched[1]).attr(&quot;href&quot;));
                        if (href !== null) {
                            chrome.extension.sendRequest({&quot;type&quot;:&quot;open_tab&quot;, &quot;url&quot;:href}, function(response) {
                                // TODO: do something afterwards?
                            });
                        }
                    });
                }
            });
        }
    });
</pre>
<p>Here I built a little bit of abstraction around the raw entry action bar. It&#8217;s encapsulated in EntryAction class, which I&#8217;ll show in a moment. Basically, if the current displaying entry&#8217;s feed URL starts with feed.dzone.com, I&#8217;ll build the &#8220;click through&#8221; action, and set the click handler. It sends the feed URL to the background script. The background script will do the cross-site request to fetch the feed content and send it back. Then the content script will regex match the content to get the original story&#8217;s URL, and ask chrome to open the URL in a new tab.</p>
<p>Here&#8217;s the code for EntryAction:</p>
<pre class="brush: jscript;">
    var EntryAction = function(element) {
        this.element = element;
        var entryElmt = this.element.parent(&quot;.entry&quot;);
        var url = $(entryElmt).find(&quot;.entry-title-link&quot;).attr('href');
        this.entry = {
            &quot;url&quot; : url
        };
    };

    EntryAction.prototype.addAction = function(action) {
        var that = this;
        var onclick = function(e) {
            var actionFunc = action['fn'];
            actionFunc(that.entry);
        }

        this.element.append($(&quot;&lt;span&gt;&quot;)
            .addClass(&quot;link unselectable&quot;)
            .text(action['name'])
            .click(onclick));
    };
</pre>
<p>I won&#8217;t delve too much into this code. It makes assumptions about the structure of the DOM that Google Reader renders into. This does make the extension brittle but that&#8217;s the reality we have to deal with for client-side scripting. Luckily, Google Reader markup doesn&#8217;t change very often. For people new to object-oriented Javascript, this is one way to create a &#8220;class&#8221; (prototype) and put &#8220;instance&#8221; methods on a &#8220;class&#8221;.</p>
<h1>Background.html</h1>
<p>Unlike content scripts, which is injected and runs in the target page, the background page runs in its own process (the extension&#8217;s process) and keeps running while the extension is active. It&#8217;s comparable to the &#8220;server&#8221; side of the extension. For our extension&#8217;s purpose, we&#8217;re using the background script to make requests to 3rd party web sites (DZone).</p>
<pre class="brush: xml;">
&lt;html&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;lib/jquery-1.6.4.min.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
    (function($) {
        chrome.extension.onRequest.addListener(
            function(request, sender, sendResponse) {
                if (request.type === 'fetch_entry') {
                    $.get(request.url, function(data) {
                        sendResponse({&quot;data&quot;:data});
                    });
                } else if (request.type === 'open_tab') {
                    chrome.tabs.create({'url':request.url});
                    sendResponse({&quot;status&quot;:&quot;ok&quot;});
                }
            }
        );
    })(jQuery);
&lt;/script&gt;
&lt;/html&gt;
</pre>
<p>We register handlers for events that our &#8220;client&#8221; (the content script) is able to raise. Here we deal with 2 kinds of events: fetch_entry and open_tab.
<ul>
<li>Although Chrome 13 allows cross-site requests from content scripts, I&#8217;m actually quite fond of this pattern of delegating requests to the background page.</li>
<li>chrome.tabs isn&#8217;t accessible in the content script. That&#8217;s why open_tab is an event the client (the content script) can raise and delegate chrome specific API calls to the background script.
</ul>
<h1>After Thoughts</h1>
<p>That&#8217;s it! That&#8217;s my first Chrome extension. It&#8217;s not earth shattering or anything but I learned quite a lot. I like Chrome extension development &#8212; it&#8217;s straightforward and simple. The architecture is quite simple yet powerful. The code is on <a href="https://github.com/kevinjqiu/greader" target="_blank">Github</a> and I plan to expand it to a framework for customizing Google Reader experience. Here are a few things we can do with the extension:</p>
<ul>
<li>Link &#8220;Share&#8221; action to twitter/Google+</li>
<li>Click on &#8220;Like&#8221; action to automatically vote up on DZone (or any other news aggregator)</li>
<li>Share with comment on Google Reader puts the comment on the entry on DZone (or any other news aggregator)</li>
<li>endless opportunities&#8230;</li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/reminiscential.wordpress.com/257/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/reminiscential.wordpress.com/257/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/reminiscential.wordpress.com/257/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/reminiscential.wordpress.com/257/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/reminiscential.wordpress.com/257/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/reminiscential.wordpress.com/257/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/reminiscential.wordpress.com/257/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/reminiscential.wordpress.com/257/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/reminiscential.wordpress.com/257/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/reminiscential.wordpress.com/257/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/reminiscential.wordpress.com/257/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/reminiscential.wordpress.com/257/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/reminiscential.wordpress.com/257/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/reminiscential.wordpress.com/257/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=257&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://reminiscential.wordpress.com/2011/10/04/building_google_reader_plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/696a8f13a7fcf0b4265fe801f18ba7b5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kevinjqiu</media:title>
		</media:content>

		<media:content url="http://reminiscential.files.wordpress.com/2011/10/screenshot-google-reader-539-chromium.png?w=300" medium="image">
			<media:title type="html">Screenshot-Google Reader (539) - Chromium</media:title>
		</media:content>

		<media:content url="http://reminiscential.files.wordpress.com/2011/10/untitled-1.png?w=300" medium="image">
			<media:title type="html">strategy</media:title>
		</media:content>
	</item>
		<item>
		<title>Spectrum.vim &#8211; My first Vim plugin</title>
		<link>http://reminiscential.wordpress.com/2011/04/20/spectrum-vim-my-first-vim-plugin/</link>
		<comments>http://reminiscential.wordpress.com/2011/04/20/spectrum-vim-my-first-vim-plugin/#comments</comments>
		<pubDate>Thu, 21 Apr 2011 04:18:49 +0000</pubDate>
		<dc:creator>Kevin J. Qiu</dc:creator>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[vim]]></category>

		<guid isPermaLink="false">http://reminiscential.wordpress.com/?p=247</guid>
		<description><![CDATA[Spectrum is a vim colorscheme roulette. Ever getting tired of staring at the same colorscheme every day? Having hundreds of colorschemes in your repo but too lazy to deterministically pick one? Spectrum helps you by randomly pick colorschemes from your vim runtime path or from the <a href="http://inspiration.sweyla.com/code/">web</a>.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=247&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Over the past few months, I&#8217;ve been using Vim as my primary development tool at work and at home, and I have to say, I&#8217;m addicted to it! I&#8217;m thinking about writing a blog post of why I get hooked on <a href="http://walking-without-crutches.heroku.com/">&#8220;walking without crutches&#8221;</a>, but for this post, I&#8217;m just going to introduce you to my first plugin in Vim &#8211; <a href="https://github.com/kevinjqiu/spectrum.vim">Spectrum</a>.</p>
<h3>Introduction</h3>
<p>Spectrum is a vim colorscheme roulette. Ever getting tired of staring at the same colorscheme every day? Having hundreds of colorschemes in your repo but too lazy to deterministically pick one? Spectrum helps you by randomly pick colorschemes from your vim runtime path or from the <a href="http://inspiration.sweyla.com/code/">web</a>. From there, you have the chance of voting up a colorscheme so Spectrum will have a higher probability to pick it or voting down a colorscheme so you wouldn&#8217;t see it again.</p>
<h3>Development</h3>
<p>To be honest, I&#8217;m not a fan of <a href="http://en.wikipedia.org/wiki/Vimscript">Vim script</a> &#8211; the language is not very expressive and doesn&#8217;t have a lot of object oriented features. Semi-fortunately, since Vim 7, they have added support for Python, Ruby and Perl scripts. I said &#8216;semi-fortunately&#8217; because the support isn&#8217;t too comprehensive. For most core vim features, you still have to resort to calling Vim commands to achieve them, but at least I don&#8217;t have to use Vim script for the most part.</p>
<p>Spectrum is written in Python, and use the &#8220;vim&#8220; module to interact with the hosting Vim instance. There is a bit of bootstrapping to do if you want to separate most of the Python code out of the entry point vim script (see https://github.com/kevinjqiu/spectrum.vim/blob/master/plugin/spectrum.vim). Many vim plugins written in Python require you to install the python code into your Python runtime before you can use them, but for a simple module like Spectrum, I opted for monkey patching syspath to include modules in the plugin folder.</p>
<p>Anyhow, give it a try and hope you like it.</p>
<p>https://github.com/kevinjqiu/spectrum.vim</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/reminiscential.wordpress.com/247/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/reminiscential.wordpress.com/247/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/reminiscential.wordpress.com/247/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/reminiscential.wordpress.com/247/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/reminiscential.wordpress.com/247/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/reminiscential.wordpress.com/247/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/reminiscential.wordpress.com/247/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/reminiscential.wordpress.com/247/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/reminiscential.wordpress.com/247/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/reminiscential.wordpress.com/247/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/reminiscential.wordpress.com/247/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/reminiscential.wordpress.com/247/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/reminiscential.wordpress.com/247/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/reminiscential.wordpress.com/247/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=247&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://reminiscential.wordpress.com/2011/04/20/spectrum-vim-my-first-vim-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/696a8f13a7fcf0b4265fe801f18ba7b5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kevinjqiu</media:title>
		</media:content>
	</item>
		<item>
		<title>Scala Simple Build Tool &#8212; Not so simple after all, at least for now&#8230;</title>
		<link>http://reminiscential.wordpress.com/2011/03/17/scala-simple-build-tool-not-so-simple-after-all-at-least-for-now/</link>
		<comments>http://reminiscential.wordpress.com/2011/03/17/scala-simple-build-tool-not-so-simple-after-all-at-least-for-now/#comments</comments>
		<pubDate>Fri, 18 Mar 2011 04:18:39 +0000</pubDate>
		<dc:creator>Kevin J. Qiu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[build]]></category>
		<category><![CDATA[sbt]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://reminiscential.wordpress.com/?p=242</guid>
		<description><![CDATA[Update:I got sbt working by building directly from the master branch from their github repo. The current version is 0.7.5. The tagged 0.9.4 version is actually an older version. Anyway, tried it and kinda loved it. This is just another late night rambling&#8230;I was trying to get a proper scala build system setup. I was [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=242&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Update:</strong>I got sbt working by building directly from the master branch from their github repo. The current version is 0.7.5. The tagged 0.9.4 version is actually an older version. Anyway, tried it and kinda loved it.</p>
<p>This is just another late night rambling&#8230;I was trying to get a proper scala build system setup. I was using Maven scala plugin for a while, but longing for something simpler and more scalanic (is there such a word?). I was pretty <a href="http://reminiscential.wordpress.com/2011/02/11/cake-the-yummy-clojure-build-system/">happy</a> at <a href="https://github.com/ninjudd/cake">Cake</a>, the Clojure build system and expected SBT to allow me to break away from using Maven to build Scala projects&#8230;boy, was I wrong&#8230;</p>
<p>First off, when you google &#8216;simple build tool&#8217;, you get a link to the SBT <a href="http://code.google.com/p/simple-build-tool/">Google code home page</a>. Well, nothing wrong there, except the &#8220;latest&#8221; version on Google code was 0.7.4 and it was half a year ago&#8230;Maybe it&#8217;s not that outdated, so I downloaded it, followed <a href="http://code.google.com/p/simple-build-tool/wiki/Setup">this</a> instruction and setup my ~/bin/sbt script. Running it, it asked me to setup projects, and it only supported up until Scala 2.7.7&#8230;Hrm, 2.8 was out for a while now, so obviously, SBT 0.7.4 isn&#8217;t the latest. Reading their home page more carefully, they&#8217;re moving the repository to <a href="https://github.com/harrah/xsbt">Github</a>. Awesome! I&#8217;d pick Github over Google Code any time too.</p>
<p>Heading over to their Github repo, and found the latest stable version is 0.9.2. Good! So it should support Scala 2.8 now! Downloaded the zip, unzipped it, and of course it wasn&#8217;t executable. You need to build it. There&#8217;s a README.md, so quickly I less&#8217;ed it. For step 1, it asked me to go to the setup wiki page on Google Code (!), which is the steps I did setting up 0.7.4&#8230;I guess they&#8217;re using 0.7.4 as a bootstrapping build&#8230;Anyways, I did that. Step 2 was to run `sbt update &#8220;project Launcher&#8221; proguard &#8220;project Simple Build Tool&#8221; &#8220;publish-local&#8221;`. Of course it didn&#8217;t work. It&#8217;s complained 0.7.4 version of sbt-launch can&#8217;t download Scala 2.7.7 from any of the repository&#8230;bummer! But hey, I can download Scala 2.7.7 lib from Maven! So I quickly updated pom.xml of one of my projects to use Scala 2.7.7 and did an upgrade. Now 2.7.7 is happily in my local Maven repo. Ran that command again, hooray! It started to build, and judging by the number of packages it&#8217;s building, &#8220;simple&#8221; isn&#8217;t the first adjective that comes into my mind. Anyway, it&#8217;s building at least, so even if it&#8217;s a little complicated, so be it&#8230;Except&#8230;of course it broke half way&#8230; and why?</p>
<blockquote><p>
[info]   Post-analysis: 107 classes.<br />
[info] == Precompiled 2.7.7 / compile ==<br />
[info]<br />
[info]    Precompiled 2.8.0 / compile &#8230;<br />
[info]<br />
[info] == Precompiled 2.8.0 / compile ==<br />
[info]   Source analysis: 9 new/modified, 0 indirectly invalidated, 0 removed.<br />
[info] Compiling main sources&#8230;<br />
[warn] there were deprecation warnings; re-run with -deprecation for details<br />
[warn] one warning found<br />
[info] Compilation successful.<br />
[info]   Post-analysis: 108 classes.<br />
[info] == Precompiled 2.8.0 / compile ==<br />
java.lang.OutOfMemoryError: PermGen space<br />
        at java.lang.ClassLoader.defineClass1(Native Method)<br />
        at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)<br />
        at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
</p></blockquote>
<p>You&#8217;ve gotta be kidding me! I set -Xmx512M and it&#8217;s not enough? And why is it building every version of Scala *from source*?? Is there something called a&#8230;JAR? </p>
<p>Anyway, increased -Xmx from 512 to 1024M, ran again, wait, and same thing happened again! Out of PermGen space&#8230;urrgh&#8230;</p>
<p>I decided to give up, at least for the day&#8230; SBT is anything but simple, at least from my experience. I know it&#8217;s open source and people put efforts into it without compensation, so I shouldn&#8217;t be critical about it. I&#8217;ll give it a try again, and hopefully it&#8217;s worth the time investment.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/reminiscential.wordpress.com/242/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/reminiscential.wordpress.com/242/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/reminiscential.wordpress.com/242/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/reminiscential.wordpress.com/242/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/reminiscential.wordpress.com/242/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/reminiscential.wordpress.com/242/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/reminiscential.wordpress.com/242/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/reminiscential.wordpress.com/242/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/reminiscential.wordpress.com/242/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/reminiscential.wordpress.com/242/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/reminiscential.wordpress.com/242/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/reminiscential.wordpress.com/242/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/reminiscential.wordpress.com/242/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/reminiscential.wordpress.com/242/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=242&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://reminiscential.wordpress.com/2011/03/17/scala-simple-build-tool-not-so-simple-after-all-at-least-for-now/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/696a8f13a7fcf0b4265fe801f18ba7b5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kevinjqiu</media:title>
		</media:content>
	</item>
		<item>
		<title>Write sudoku solver in Clojure</title>
		<link>http://reminiscential.wordpress.com/2011/03/02/write-sudoku-solver-in-clojure/</link>
		<comments>http://reminiscential.wordpress.com/2011/03/02/write-sudoku-solver-in-clojure/#comments</comments>
		<pubDate>Thu, 03 Mar 2011 03:57:08 +0000</pubDate>
		<dc:creator>Kevin J. Qiu</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[clojure]]></category>

		<guid isPermaLink="false">http://reminiscential.wordpress.com/?p=238</guid>
		<description><![CDATA[&#8230;yeah, because the world just needs another Sudoku solver. Well, I&#8217;m not trying to solve world hunger with it, but just an attempt to practice Clojure, I took (read: stole) Peter Norvig&#8217;s sudoku solver algorithm (written in Python) and adapted it into Clojure. I put it up on Github under sudoku-clj. The algorithm itself isn&#8217;t [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=238&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>&#8230;yeah, because the world just needs another <a href="http://en.wikipedia.org/wiki/Sudoku">Sudoku</a> solver. Well, I&#8217;m not trying to solve world hunger with it, but just an attempt to practice <a href="http://clojure.org">Clojure</a>, I took (read: stole) Peter Norvig&#8217;s <a href="http://norvig.com/sudoku.html">sudoku solver</a> algorithm (written in Python) and adapted it into Clojure. I put it up on Github under <a href="https://github.com/kevinjqiu/sudoku-clj">sudoku-clj</a>. The algorithm itself isn&#8217;t *that* hard to understand. The porting to a lisp-y syntax made the code a little longer than its Python counterpart. I&#8217;m sure seasoned Lisp/Clojure users can point out dozens of places where more idiomatic/succinct syntax can be used (If you happen to be one, do tell, by the way).</p>
<p>Here&#8217;s a few things I noticed:</p>
<ul>
<li> Mutable states in clojure are captured using `ref`s. The object itself (in this case, the grid, which is a hash map) doesn&#8217;t mutate, but the reference is changed to point to different grid objects that represent a configuration at a given step.</li>
<li>Clojure sequences are Lazy. A few times I tried to print out the current state (remaining digits) of the square, but if you simply do <code>(println seq)</code>, you will get a Java-ish toString() output of the sequence object. You need to force the lazy sequence to be evaluated by <code>(println (apply str seq))</code>. Needless to say, you lose the advantage of lazy sequences, so use it sparingly.</li>
<li>Python&#8217;s list comprehension syntax is fabulous. Clojure&#8217;s counterpart for comprehension doesn&#8217;t feel as elegent, nor is map a function onto a sequence to achieve that (the way I used it)</li>
<li><a href="http://reminiscential.wordpress.com/2011/02/11/cake-the-yummy-clojure-build-system/">Cake</a> is yummy!</li>
<li>The performance isn&#8217;t great&#8230;I must have done something wrong, but the easy sudoku grid took about 2 seconds (with the JVM already booted), while the Python algorithm solves it in a fraction of a second.</li>
<li>Because assign/eliminate are mutually recursive, my current implementation uses the naive way of doing recursion, i.e., let the stack grow. Clojure has a function `trampoline`, which adds a level of indirection that applies to mutually recursive functions. It uses `recur` at tail end position (basically translates the recursive calls into loops) which doesn&#8217;t fill your process&#8217;s stack. It might not be obvious (to me anyways) how one can do that with a few levels of function calls in between assign/eliminate, but I&#8217;m sure there&#8217;s a way</li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/reminiscential.wordpress.com/238/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/reminiscential.wordpress.com/238/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/reminiscential.wordpress.com/238/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/reminiscential.wordpress.com/238/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/reminiscential.wordpress.com/238/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/reminiscential.wordpress.com/238/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/reminiscential.wordpress.com/238/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/reminiscential.wordpress.com/238/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/reminiscential.wordpress.com/238/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/reminiscential.wordpress.com/238/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/reminiscential.wordpress.com/238/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/reminiscential.wordpress.com/238/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/reminiscential.wordpress.com/238/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/reminiscential.wordpress.com/238/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=238&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://reminiscential.wordpress.com/2011/03/02/write-sudoku-solver-in-clojure/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/696a8f13a7fcf0b4265fe801f18ba7b5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kevinjqiu</media:title>
		</media:content>
	</item>
		<item>
		<title>Cake &#8211; the yummy Clojure build system</title>
		<link>http://reminiscential.wordpress.com/2011/02/11/cake-the-yummy-clojure-build-system/</link>
		<comments>http://reminiscential.wordpress.com/2011/02/11/cake-the-yummy-clojure-build-system/#comments</comments>
		<pubDate>Fri, 11 Feb 2011 05:42:56 +0000</pubDate>
		<dc:creator>Kevin J. Qiu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[clojure]]></category>

		<guid isPermaLink="false">http://reminiscential.wordpress.com/?p=230</guid>
		<description><![CDATA[About 10 minutes ago I heard about cake clojure build system, and gave it a try. And 10 minutes later, it won me over! Wow, it addresses all the pain points of leiningen BLAZINGLY FAST Sorry for using all CAPS but I&#8217;m very excited about this improvement over leiningen &#8212; OK, it may not be [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=230&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>About 10 minutes ago I heard about <a href="https://github.com/ninjudd/cake">cake</a> clojure build system, and gave it a try. And 10 minutes later, it won me over! Wow, it addresses all the pain points of <a href="https://github.com/technomancy/leiningen">leiningen</a></p>
<p><strong>BLAZINGLY FAST</strong><br />
Sorry for using all CAPS but I&#8217;m very excited about this improvement over leiningen &#8212; OK, it may not be the fault of leiningen that JVM cold startup time is non-trivial but hey, someone came up with an idea of having a long running JVM process in the background, so subsequent clojure tasks reuse the same JVM instance. Cake folks integrated that nicely. It takes about 10-15 seconds to boot up a JVM but subsequent cake tasks or execution of clojure code is virtually instant! Comparing to leiningen, which doesn&#8217;t take this approach and every single task (such as common ones like lein test) takes around 5 seconds. This adds up quickly and makes you less efficient. The speed improvement alone is enough for me to switch to cake.</p>
<p><strong>Advanced REPL functionalities: tab completion, history</strong><br />
It just works. Very useful for having instant feedbacks while exploring the language and API. No more manually adding jLine to your classpath or hack around tab completion wrapper&#8230;It just works! (I know I said it already)</p>
<p><strong>run clojure files directly</strong><br />
OK, leiningen can do this too, but through <a href="https://github.com/sids/lein-run">plugin</a>. I feel this is a very handy functionality, which probably should be included in the core.</p>
<p><strong>autotest</strong><br />
Detects your code change and automatically run your test suites! Sweet.</p>
<p><strong>compatible with leiningen project definition files</strong><br />
Cake understand project.clj, so I don&#8217;t need to do anything for my existing leiningen projects. Change directory to the project and `cake` away <img src='http://s0.wp.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Overall, it just works out of the box. No more mucking around with dev-dependencies and other chores and let you focus on what you&#8217;d love to do.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/reminiscential.wordpress.com/230/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/reminiscential.wordpress.com/230/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/reminiscential.wordpress.com/230/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/reminiscential.wordpress.com/230/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/reminiscential.wordpress.com/230/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/reminiscential.wordpress.com/230/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/reminiscential.wordpress.com/230/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/reminiscential.wordpress.com/230/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/reminiscential.wordpress.com/230/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/reminiscential.wordpress.com/230/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/reminiscential.wordpress.com/230/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/reminiscential.wordpress.com/230/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/reminiscential.wordpress.com/230/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/reminiscential.wordpress.com/230/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=230&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://reminiscential.wordpress.com/2011/02/11/cake-the-yummy-clojure-build-system/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/696a8f13a7fcf0b4265fe801f18ba7b5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kevinjqiu</media:title>
		</media:content>
	</item>
		<item>
		<title>New Year&#8217;s Resolution</title>
		<link>http://reminiscential.wordpress.com/2011/01/02/new-years-resolution/</link>
		<comments>http://reminiscential.wordpress.com/2011/01/02/new-years-resolution/#comments</comments>
		<pubDate>Mon, 03 Jan 2011 04:45:50 +0000</pubDate>
		<dc:creator>Kevin J. Qiu</dc:creator>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://reminiscential.wordpress.com/?p=228</guid>
		<description><![CDATA[2011 here we come! In the spirit of continual learning, I&#8217;m going to write down the technology I&#8217;d love to learn this year. Haskell Now that I&#8217;m more interested in functional languages, I&#8217;d love to look into this &#8220;pure&#8221; functional language that inspired countless other ones of its kind. Lift Last year I scratched the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=228&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>2011 here we come! In the spirit of continual learning, I&#8217;m going to write down the technology I&#8217;d love to learn this year.</p>
<ul>
<li><a href="http://haskell.org">Haskell</a></li>
<p>Now that I&#8217;m more interested in functional languages, I&#8217;d love to look into this &#8220;pure&#8221; functional language that inspired countless other ones of its kind.</p>
<li><a href="http://liftweb.net">Lift</a></li>
<p>Last year I scratched the surface of <a href="http://www.scala-lang.org">Scala</a>, a hybrid JVM language. I&#8217;m very fond of it, and think it has tremendous potential. Twitter and FourSquare are already using Scala, so it has been put to the test of some pretty high-profile usages.  Lift is the most popular web framework built on top of Scala. It claims to have the rapid application development benefits from Rails and the benefits from statically typed language. </p>
<li>More advanced features of <a href="http://clojure.org">Clojure</a></li>
<p>In the past two years, I explored Clojure and on off. I love the Lisp idea of <a href="http://en.wikipedia.org/wiki/Homoiconicity">homoiconicity</a> which unifies programming and meta-programming. That said, I haven&#8217;t been using macro in Clojure too much, and there are other cool ideas of Clojure I haven&#8217;t been able to explore deeply, such as protocols and <a href="http://en.wikipedia.org/wiki/Software_transactional_memory">software transactional memory</a> (STM)</p>
<li><a href="http://www.ruby-lang.org/en/">Ruby</a> and <a href="http://rubyonrails.org/">Rails 3</a></li>
<p>For the past few years, I&#8217;ve been refraining myself from learning Ruby, because I&#8217;m already quite adept at Python, and I feel I should be learning languages that are different from what I already know. However, the more I heard about Ruby and its ideas, the more interesting it appears to me. On top of that, Rails 3 has come out, and it appears to have improved significantly. Moreover, there are a lot of advancement in the Ruby VM world such as JRuby, which means Ruby applications don&#8217;t have to run on the old and dreadful (hear-say) MRI. I wouldn&#8217;t mind taking Ruby and Rails out for a spin this year.</p>
<li><a href="http://www.android.com/">Android</a></li>
<p>Last year I got an HTC Legend Android phone, with the intention of developing for Android at some point of time. It didn&#8217;t work out that way, though, but Android continues to be a very interesting and fast growing platform. Mobile *is* the future, and I&#8217;d like to poke into the Android world this year, primarily because it&#8217;s open source. iOS is equally interesting technically, but I don&#8217;t own a Mac and I don&#8217;t like the idea of paying Apple $99 for SDK even though I don&#8217;t intend to publish on AppStore.</p>
</ul>
<p>I think that&#8217;s enough for a year&#8230;or is it? There&#8217;s a few more technologies I wish to learn or keep up with:</p>
<ul>
<li>GWT and Google App Engine</li>
<p>2 years of professional GWT development made me a firm fan of this Google technology. I got out of GWT for different reasons, but I love the engineering effort they put into GWT. It may not take over the world but it&#8217;s definitely a solid player in the front-end web development arena. Especially now they integrated with the Spring framework and made deploying to App Engine easy, it may pick up more traction this year. I think the Java language is both the pros and cons of GWT. I&#8217;d love to see an alternative language (Scala) being implemented for GWT, but it may not happen any time soon.</p>
<li>A &#8220;NoSQL&#8221; database</li>
<p>Let&#8217;s face it, &#8220;NoSQL&#8221; is a terrible name, but it grabs people&#8217;s attention. I flirted with <a href="http://couchdb.apache.org/">CouchDB</a> briefly last year, and would love to continue this journey this year. Also, <a href="http://www.mongodb.org/">MongoDB</a> seems interesting too.</p>
<li>Node.js</li>
<p>It&#8217;s the least I think I&#8217;d learn this year. It&#8217;s hot in the geekdom right now, and it has its value, for example, having both the server and client side written in Javascript eliminates the need to implement the validation logic in two different languages. However, I&#8217;m just not a big fan of Javascript. I think it&#8217;s a language that&#8217;s by a chain of serendipitous events became the world&#8217;s most widely used language. It carries a huge historical burden, and although it has cool features, some other modern languages have them too and do better. Regardless, given the stardom status of Node.js, it deserves some looking into <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/reminiscential.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/reminiscential.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/reminiscential.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/reminiscential.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/reminiscential.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/reminiscential.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/reminiscential.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/reminiscential.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/reminiscential.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/reminiscential.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/reminiscential.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/reminiscential.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/reminiscential.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/reminiscential.wordpress.com/228/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=228&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://reminiscential.wordpress.com/2011/01/02/new-years-resolution/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/696a8f13a7fcf0b4265fe801f18ba7b5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kevinjqiu</media:title>
		</media:content>
	</item>
		<item>
		<title>Use Python decorator to curry functions</title>
		<link>http://reminiscential.wordpress.com/2010/10/22/use-python-decorator-to-curry-functions/</link>
		<comments>http://reminiscential.wordpress.com/2010/10/22/use-python-decorator-to-curry-functions/#comments</comments>
		<pubDate>Fri, 22 Oct 2010 19:32:28 +0000</pubDate>
		<dc:creator>Kevin J. Qiu</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://reminiscential.wordpress.com/?p=223</guid>
		<description><![CDATA[It&#8217;s been a while since the last time I wrote about Python. This morning, I was listening to a podcast on my way to work. They were discussing functional programming and dynamic languages&#8230;I learned Python before I went into Computer Science, and then I learned about functional programming and through learning of Scala and Clojure, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=223&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a while since the last time I wrote about Python. This morning, I was listening to a podcast on my way to work. They were discussing functional programming and dynamic languages&#8230;I learned Python before I went into Computer Science, and then I learned about functional programming and through learning of Scala and Clojure, my functional programming concepts have been enriched. As I was listening, it suddenly appeared to me that there isn&#8217;t a way in Python to <a href="http://en.wikipedia.org/wiki/Currying" target="_blank">curry</a> a function. Not that it&#8217;s critical to everyday development, but wouldn&#8217;t it be neat if I can curry a function in Python?</p>
<p>Then the hosts of the podcast discussed how dynamic languages are so flexible that you can pretty much do anything to it. &#8220;You can take a function as parameter, return a function from a function, and so on.&#8221; Hey, isn&#8217;t that what Python&#8217;s <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=240808" target="_blank">decorator</a> can do? I learned decorators before, but I haven&#8217;t used it beyond the scope of creating properties and certainly haven&#8217;t written any decorators. I thought this would be a good exercise for learning decorators.</p>
<p>Here&#8217;s a simple example of what function currying: suppose you have a method</p>
<pre class="brush: python;">
def add(x,y):
  return x+y
</pre>
<p>Then calling add(1,2) should be the same as add(1)(2). add(1) is what they call a partially applied function. It&#8217;s a function that takes one parameter.</p>
<p>Our goal here is to write a decorator &#8220;curried&#8221; that takes a function with n parameters and transform it in a way that can be applied n times and get the final result.</p>
<p>We&#8217;ll start with unit tests first:</p>
<pre class="brush: python;">
import unittest

class CurryTest(unittest.TestCase):

	def test_with_no_args(self):
		@curried
		def do_nothing():
			return &quot;&quot;
		self.assertEquals(&quot;&quot;, do_nothing())

	def test_with_int_args(self):
		@curried
		def add_int(x,y):
			return x+y
		self.assertEquals(3, add_int(1)(2))
	def test_with_str_args(self):
		@curried
		def add_str(x,y):
			return &quot;%s%s&quot;%(x,y)
		self.assertEquals(&quot;ab&quot;, add_str(&quot;a&quot;)(&quot;b&quot;))
</pre>
<p>So we make sure that a currying on a function takes no parameter is valid but should be a pass through, and also the &#8220;curried&#8221; decorator can be applied to any function with arguments (excluding positional arguments and keyword arguments)</p>
<p>A decorator is simply a function that takes a function as parameter:</p>
<pre class="brush: python;">
def curried(fn):
  pass
</pre>
<p>and @curried is simply a syntactic sugar for:</p>
<pre class="brush: python;">
def fn(...): ...
fn=curried(fn)
</pre>
<p>So, now we can write &#8220;curried&#8221; decorator.<br />
To make the test for function with no argument pass, in curried() function, we can test to see if fn has arguments. Python&#8217;s standard library provides inspect.getargspec method:</p>
<pre class="brush: python;">
def curried(fn):
  argspec = inspect.getargspec(fn)
  if len(argspec.args)==0:
    return fn
  else:
    # later
</pre>
<p>Now the first test passes.</p>
<p>For the other two cases, here&#8217;s the strategy. In Python, when a class defines __call__ method, the instance of that class is said to be &#8220;callable&#8221;. For instance:</p>
<pre class="brush: python;">
class A(object):
  def __call__(self, arg):
    return arg

f=A()
f(&quot;echo&quot;)  # this gives you &quot;echo&quot;
</pre>
<p>This is very similar to Scala&#8217;s apply() function. Now that we have this in our inventory, we can define a `PartialFunction` class, take all the required parameters of the original function, and allow them to be applied one at a time. So the __call__ method of PartialFunc will look like this:</p>
<pre class="brush: python;">
def __call__(self, value):
  # Xxx
</pre>
<p>If all the required parameters are passed in, PartialFunc should evaluate the original function with the complete argument list. Otherwise, PartialFunc stores the parameter in an instance variable, and returns itself.</p>
<p>Here&#8217;s the complete code:</p>
<pre class="brush: python;">
class PartialFunc(object):
	def __init__(self, fn, argspec):
		self.fn = fn
		self.argspec = argspec
		self.args = []

	def __call__(self, value):
		self.args.append(value)
		if len(self.args) == len(self.argspec.args):
			arglist = &quot;,&quot;.join([&quot;self.args[%d]&quot;%i for i in range(0, len(self.args))])
			return eval(&quot;self.fn(&quot; + arglist + &quot;)&quot;)
		else:
			return self
</pre>
<p>and the curried decorator:</p>
<pre class="brush: python;">
def curried(fn):
	argspec = inspect.getargspec(fn)
	if len(argspec.args) == 0:
		return fn
	else:
		return PartialFunc(fn, argspec)
</pre>
<p>It&#8217;s pretty straightforward. When the parameters are complete, I construct a python statement that calls the original function with the complete argument list, and then pass the statement into an eval statement. I know evals are evil, but I can&#8217;t find a way in Python to dynamically change the signature of the original method and make it accept a variable length argument (varargs).</p>
<p>So this is it. It&#8217;s quite simple. Python methods can have varargs and keyword args, the situation gets a little more complicated. The thing is, both varargs and keyword args are not mandatory, so it&#8217;s hard for the curried function to know whether the argument list has been completed&#8230;Also, if you take default values into account, it could get even more complicated. </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/reminiscential.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/reminiscential.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/reminiscential.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/reminiscential.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/reminiscential.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/reminiscential.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/reminiscential.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/reminiscential.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/reminiscential.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/reminiscential.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/reminiscential.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/reminiscential.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/reminiscential.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/reminiscential.wordpress.com/223/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=223&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://reminiscential.wordpress.com/2010/10/22/use-python-decorator-to-curry-functions/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/696a8f13a7fcf0b4265fe801f18ba7b5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kevinjqiu</media:title>
		</media:content>
	</item>
		<item>
		<title>My impression on Scala so far</title>
		<link>http://reminiscential.wordpress.com/2010/10/07/my-impression-on-scala-so-far/</link>
		<comments>http://reminiscential.wordpress.com/2010/10/07/my-impression-on-scala-so-far/#comments</comments>
		<pubDate>Fri, 08 Oct 2010 03:53:24 +0000</pubDate>
		<dc:creator>Kevin J. Qiu</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://reminiscential.wordpress.com/?p=216</guid>
		<description><![CDATA[I&#8217;ve been exploring Scala on and off for some time now. Here&#8217;s my highly subjective and very limited impression of Scala. What I like about Scala: 0) It&#8217;s statically-typed language. That&#8217;s right! I don&#8217;t care what you ninjas say. As much as I love dynamic languages, I just prefer statically typed language for big projects. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=216&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been exploring Scala on and off for some time now. Here&#8217;s my highly subjective and very limited impression of Scala.</p>
<p>What I like about Scala:</p>
<h2>0) It&#8217;s statically-typed language.</h2>
<p>That&#8217;s right! I don&#8217;t care what you ninjas say. As much as I love dynamic languages, I just prefer statically typed language for big projects. The benefit of having type information is enormous for a project with a large code base. I know you have to write unit tests for it anyways, but when 80% of your unit test code is checking types, it&#8217;s just counter-productive.</p>
<h2>1) The ability to combine functional programming style with OOP.</h2>
<p>This is what Scala is known for &#8211; a hybrid language that boasts the better in both OOP world and FP world. I&#8217;m not a functional programming purist, but I think Scala did a good job blending the functional programming elements into OOP. Writing Scala programs, I find myself much more empowered to be able to choose from both styles where I see fit. The ability to pass functions around and apply high order functions can significantly reduce boilerplate code and visual clutter.</p>
<h2>2) The ability to create your own control flow (well, sort of).</h2>
<p>I had a <a href="http://reminiscential.wordpress.com/2010/09/29/scala-use-function-currying/" target="_blank">blog post</a> about how to use function curry to create a customized control flow. This is very empowering and yet, it&#8217;s not an one-off syntactic sugar that&#8217;s sprinkled randomly into the language like some other language would do. Customization of control flow is a result of combining generic language features (such as currying, by-name parameter, implicit conversion, etc).</p>
<h2>3) Object instead of static</h2>
<p>Scala does away with the Java static keyword. Instead, it provides &#8220;object&#8221; keyword to define a class that only has one instance. It has the same power as singleton design pattern, without the extra boilerplate code. (if you think implementing singleton in Java is simple, think again. Especially in the multi-threaded context). Also, you can use the same construct to define &#8220;companion&#8221; objects, which can be used to implement the factory pattern, and put in miscellaneous methods, implicit conversion methods and so on. Extremely powerful yet elegant.</p>
<p><span style="font-size:20px;font-weight:bold;">4) Operator overloading (well, sort of).</span></p>
<p>OK, it&#8217;s not exactly operator overloading &#8211; Scala allows many non-alpha-numeric characters in the method name, so operators are essentially methods. duh! if you think about it&#8230;why should + be treated any different from &#8220;add()&#8221;? Being able to use special characters in method names makes code easy to understand. However, I&#8217;m a bit disappointed that question mark (?) cannot be used in method names&#8230;One of the things I liked about LISP is you can define a function (odd? (x) (&#8230;)) and readers immediately know this function returns a boolean. I don&#8217;t have to ponder whether I should name it isOdd() or hasChildren(). Anyway&#8230;</p>
<h2>5) Traits</h2>
<p>In most cases, multiple inheritance is manageable. Seems Java threw the baby out with the bath water &#8211; rejecting multiple inheritance completely. It&#8217;s ironic that the AOP guys cracks open Java classes in the byte code level to do the &#8220;mixins&#8221;&#8230;With Scala, this seems to be natural.</p>
<h2>6) Built-in parser-combinator library</h2>
<p>It&#8217;s easy to do some non-mission critical parsing using the Scala standard library. The library itself is implemented as an internal DSL such that writing parser rules feels like writing EBNF directly.</p>
<p>Here&#8217;s what&#8217;s not so hot for me so far:</p>
<h1>1) The generics still is obtrusive sometimes.</h1>
<p>That said, however, it&#8217;s vastly superior than Java&#8217;s generics system with far better type inferencing. But sometimes, you still have to write down a lot of types especially on a parameterized method. What&#8217;s worse is because Scala is more strict than Java wrt types, you cannot ignore generic types the way you can in Java code. Moreover, because Scala runs on JVM, and because of type-erasure, you still can&#8217;t write code such as val t = new T()&#8230;although we can&#8217;t blame this on Scala.</p>
<h2>2) The collection library.</h2>
<p>For each collection data structure, Scala has the mutable implementation, immutable implementation, and the native Java Collection Library. If you&#8217;re writing code that calls Java library, very often you have to wrap JCL lists/maps/sets into the Scala ones, because you want to use the nice functional features Scala provides. I&#8217;m not smart enough to know a better solution to this, I&#8217;m just merely pointing out a sore spot. Clojure has a very clever and elegant way of integrating JCL data structures into Clojure code, but since Clojure and Scala are vastly different, I don&#8217;t know how relevant this is.</p>
<h2>3) Start up time</h2>
<p>One of Scala&#8217;s goal is to be able to both scale up and scale down. Scala programs can be run as scripts by the interpreter, but it can&#8217;t compete with Python or Ruby in terms of development turn-around time in terms of scripting. Again, this is because of the dreadful JVM startup process.</p>
<h2>4) Lack of good tooling</h2>
<p>The best Scala development environment I found so far is the Scala plugin for IntelliJ. It&#8217;s still not great for debugging, but for coding and integration with Maven and such, it&#8217;s great. The Eclipse plugin lags significantly, despite having built a brand new website and seemingly having more resource pour into it&#8230;I know I shouldn&#8217;t be overly critical of a community effort, but it&#8217;s just frustrating that it can&#8217;t even do auto import of classes&#8230;</p>
<p>Overall, I think Scala really has the potential to become a big name in the programming language landscape. It can do everything Java can and does better. It has so much features that Java doesn&#8217;t dare to add to keep backward compatibility or keep the language dead simple or politics or whatever reason&#8230;</p>
<p>Scala is not a hype, but in order to be adopted more rapidly, I think it needs to</p>
<p>1) Stablize the language and core library.</p>
<p>2) Tooling, tooling, tooling! Seriously.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/reminiscential.wordpress.com/216/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/reminiscential.wordpress.com/216/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/reminiscential.wordpress.com/216/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/reminiscential.wordpress.com/216/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/reminiscential.wordpress.com/216/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/reminiscential.wordpress.com/216/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/reminiscential.wordpress.com/216/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/reminiscential.wordpress.com/216/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/reminiscential.wordpress.com/216/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/reminiscential.wordpress.com/216/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/reminiscential.wordpress.com/216/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/reminiscential.wordpress.com/216/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/reminiscential.wordpress.com/216/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/reminiscential.wordpress.com/216/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=216&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://reminiscential.wordpress.com/2010/10/07/my-impression-on-scala-so-far/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/696a8f13a7fcf0b4265fe801f18ba7b5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kevinjqiu</media:title>
		</media:content>
	</item>
		<item>
		<title>Use function currying to reduce repetition and make code clean</title>
		<link>http://reminiscential.wordpress.com/2010/09/29/scala-use-function-currying/</link>
		<comments>http://reminiscential.wordpress.com/2010/09/29/scala-use-function-currying/#comments</comments>
		<pubDate>Wed, 29 Sep 2010 17:33:35 +0000</pubDate>
		<dc:creator>Kevin J. Qiu</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://reminiscential.wordpress.com/?p=210</guid>
		<description><![CDATA[Use function currying and Scala syntactic sugar to create your own control flow that reduces unit testing structural code repetition<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=210&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Lately, I&#8217;ve been writing a parser using the Scala parser-combinator framework to parse some saves from a game. As a responsible programmer (:P), I write unit tests for each rule. However, I found myself having to write the following code over and over again:</p>
<pre class="brush: scala;">
@Test
def testRule1() {
  parserRule.apply(new CharSequence(&quot;someInput&quot;)) match {
    case Success(result, _) =&gt; {
      assertEquals(&quot;expected&quot;, result)
      /* other asserts if the result is a collection of something else */
      }
    case NoSuccess(msg, _) =&gt; fail(msg)
  }
}
</pre>
<p>It&#8217;s worth noting that you cannot pass in a string value to a Parser. A parser expects a CharSequence CharSequenceReader object. Luckily, with Scala, you can define implicit conversion to turn a string into a CharSequence CharSequenceReader:</p>
<pre class="brush: scala;">
implicit def str2charSeqReader(v:String) = new CharSequenceReader(v)
</pre>
<p>Another goody Scala offers is that obj.apply(arg) method can be invoked by obj(arg), so the above code becomes:</p>
<pre class="brush: scala;">
/* ... */
parserRule(&quot;someInput&quot;) match {
/* ... */
}
</pre>
<p>It&#8217;s much cleaner.</p>
<p>However, the matching part is not clean still. It&#8217;s not that bad for a single test case, but it&#8217;s hardly a good practice to copy/paste it all over the test code base. We need to refactor this. The first thing comes to mind is to extract the matching part into a separate method, and let the caller provide the assertion part. Because Scala is a functional language, we can declare the method takes a function as a parameter, instead of using the delegate pattern, creating another class to encapsulate the method to be called, as you would do in Java:</p>
<pre class="brush: scala;">
def tryMatch[T](pr:ParseResult[T], f:(T)=&gt;Unit) {
  pr match {
    case Success(r, _) =&gt; f(r)
    case NoSuccess(msg, _) =&gt; fail(msg)
  }
}
</pre>
<p>Now the consumer (the test code) looks like this:</p>
<pre class="brush: scala;">
@Test
def test1() {
  tryMatch(rule1(&quot;input&quot;), (result)=&gt;{assertEquals(&quot;expected&quot;,result)})
}
</pre>
<p>It&#8217;s better, except that when you have multiple assert* methods need to be called, it quickly becomes ugly:</p>
<pre class="brush: scala;">
@Test
def test2() {
  tryMatch(listRule(&quot;1,2,3,4&quot;), (result)=&gt;{assertEquals(1,result(0));assertEquals(2,result(1));assertEquals(3,result(2));assertEquals(4,result(3))})
}
</pre>
<p>To do better, we can use <a href="http://en.wikipedia.org/wiki/Currying">function currying</a>. I read about function currying before, but not until now did it dawn on me that I can use this technique to make my code look cleaner. Basically, currying means that a function with n parameters is the same as the function being applied one parameter at a time in succession. e.g., function add(x1:Int,x2:Int,&#8230;,xn:Int) adds all its parameters. add(1,2)=[add(1)](2), where add(1) becomes a partially applied function that takes an integer and returns an integer. Then the partial function is applied to the second parameter which gives the eventual result.</p>
<p>This is all very theoretical, but the practical implication is that we can transform tryMatch() method shown above from a method with 2 parameters into a curried function. Why? Because with Scala, when you have a method that only takes a single parameter (as is the case with the partially applied function), you can replace parentheses with curly brackets! Let&#8217;s see how it works:</p>
<pre class="brush: scala;">
def tryMatch[T](pr:ParseResult[T])(f:(T)=&gt;Unit) {
  pr match {
    case Success(r, _) =&gt; f(r)
    case NoSuccess(msg, _) =&gt; fail(msg)
  }
}
</pre>
<p>Basically, we break the two parameter definitions. This creates a PartialFunction in Scala. No other code needs to be changed at all. Now we can call tryMatch like this:</p>
<pre class="brush: scala;">
@Test
def testList() {
  tryMatch(listRule(&quot;1 2 3&quot;)) {
    result =&gt; {
      assertEquals(1, result(0))
      assertEquals(2, result(1))
      assertEquals(3, result(2))
    }
  }
}
</pre>
<p>This is like creating your own control flow (like try-catch-finally). Ain&#8217;t that neat?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/reminiscential.wordpress.com/210/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/reminiscential.wordpress.com/210/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/reminiscential.wordpress.com/210/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/reminiscential.wordpress.com/210/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/reminiscential.wordpress.com/210/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/reminiscential.wordpress.com/210/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/reminiscential.wordpress.com/210/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/reminiscential.wordpress.com/210/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/reminiscential.wordpress.com/210/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/reminiscential.wordpress.com/210/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/reminiscential.wordpress.com/210/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/reminiscential.wordpress.com/210/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/reminiscential.wordpress.com/210/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/reminiscential.wordpress.com/210/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=210&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://reminiscential.wordpress.com/2010/09/29/scala-use-function-currying/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/696a8f13a7fcf0b4265fe801f18ba7b5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kevinjqiu</media:title>
		</media:content>
	</item>
		<item>
		<title>Finding Happy Numbers using Scala</title>
		<link>http://reminiscential.wordpress.com/2010/07/23/finding-happy-numbers-using-scala/</link>
		<comments>http://reminiscential.wordpress.com/2010/07/23/finding-happy-numbers-using-scala/#comments</comments>
		<pubDate>Fri, 23 Jul 2010 18:40:25 +0000</pubDate>
		<dc:creator>Kevin J. Qiu</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://reminiscential.wordpress.com/?p=205</guid>
		<description><![CDATA[The problem was posted on Programming Praxis. The algorithm itself is pretty straightforward, anyone can do it with a few if/else/fors, but to coerce myself to think functionally, I decide to practice writing it in Scala. A number is a happy number if the sum of square of its digits eventually arrive at 1. For [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=205&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The problem was posted on <a href="http://programmingpraxis.com/2010/07/23/happy-numbers/">Programming Praxis</a>. The algorithm itself is pretty straightforward, anyone can do it with a few if/else/fors, but to coerce myself to think functionally, I decide to practice writing it in <a href="http://www.scala-lang.org">Scala</a>.</p>
<p>A number is a happy number if the sum of square of its digits eventually arrive at 1. For example, 7=&gt;7<sup>2</sup>=49=&gt;4<sup>2</sup>+9<sup>2</sup>=97=&gt;9<sup>2</sup>+7<sup>2</sup>=&gt;130=1<sup>2</sup>+3<sup>2</sup>+0<sup>2</sup>=10=&gt;1<sup>2</sup>+0<sup>2</sup>=1, so 7 is a happy number. 17 is not a happy number because by applying the above process, it goes into a loop.</p>
<p>Step1: calculating the sum of squares of a number</p>
<p>To get a list of numbers from a given number, we can first convert the number into a string, and then map every character of the string to its corresponding integer value. A more mathematical way is to divide the number continually by 10 until the original number becomes 0, adding the remainder to a list each time&#8230;The first method is easier to visualize, so here it goes:<br />
<code>n.toString.toCharArray.map{digit=&gt;Integer.valueOf(""+digit)}</code></p>
<p>It&#8217;s quite wordy but I&#8217;ve yet to find a better way. I&#8217;m pretty sure there is so if you know, do inform me.<br />
Now I need to square each item in the list. So modify the above statement:<br />
<code>n.toString.toCharArray.map{digit=&gt;Math.pow(Integer.valueOf(""+digit).doubleValue,2.0)}</code><br />
One thing bothers me is that I have to explicitly call someInt.doubleValue&#8230;I thought Scala does the implicit conversion for me? Then I realized Integer.valueOf(&#8230;) gives me java.lang.Integer, not scala.lang.Int. So I have to write a implicit conversion function myself:<br />
<code><br />
implicit def integer2double(i:Integer):Double = i.doubleValue<br />
</code><br />
Now I can get rid of the hideous someInt.doubleValue.<br />
Since we&#8217;re doing implicit conversion already, why not just implicitly convert a numeric character to a double so that it can be accepted by Math.pow?<br />
<code><br />
implicit def char2double(ch:Char):Double = Integer.valueOf("" + ch).doubleValue<br />
</code><br />
Now the code can be shortened to<br />
<code><br />
n.toString.toCharArray.map { digit =&gt; Math.pow(digit, 2) }<br />
</code><br />
Isn&#8217;t that sweet? Implicit conversion is cool but it&#8217;s easy to get carried away and do everything implicit, which makes the code hard to maintain, so there gotta be a balance somewhere. In the scope of this small exercise, I guess it&#8217;s OK to use it.</p>
<p>Now that we have the squares of individual digits in a list, we can calculate the sum by reducing or folding it:<br />
<code><br />
((n.toString.toCharArray.map { digit =&gt; Math.pow(digit, 2) }).foldLeft(0.0) { _ + _ }).toInt<br />
</code><br />
{_ + _} seems a lot like line noise. The underscore converts the statement into a closure. It&#8217;s a shortcut for (a,b)=&gt;a+b. It&#8217;s succinct yet should be used sparingly.</p>
<p>Step2:return</p>
<p>lol, yeah, no extra fluff is needed. We can capture the constraints in one return statement, but before that, I need to decide on what states I need to carry on from each recursive step. (You know I&#8217;m going to use recursion, don&#8217;t you? <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> )</p>
<p>There are a couple of states involved:<br />
1) the limit. It&#8217;s the number of steps we allow before the final &#8220;1&#8243; is reached. It took number seven 5 steps to reach 1. This variable is the cut-off: if the given number can&#8217;t reach 1 before the limit, it&#8217;s considered unhappy (return false)<br />
2) the current number of steps<br />
3) the set of numbers already appeared. In the case of seven, the set is {49 97 130 10}. This set is used to determine if the calculations fall into a loop. If the current calculated number appears in this set, the original number is unhappy.</p>
<p>So here&#8217;s our method:<br />
<code><br />
def isHappyNumber(n:Int, limit:Int, numOfTries:Int, alreadySeen:Set[Int]):Boolean = {<br />
val sos = ((n.toString.toCharArray.map { digit =&gt; Math.pow(digit, 2) }).foldLeft(0.0) { _ + _ }).toInt<br />
return sos == 1 ? true : (!alreadySeen.contains(sos) &amp;&amp; numOfTries+1 &lt;= limit &amp;&amp; isHappyNumber(sos, limit, numOfTries+1, alreadySeen+sos))<br />
}<br />
</code></p>
<p>The second line basically says: when sos (sum of squares) is 1, return true, otherwise, is the number already in the set of numbers seen during the calculation?, if not, does the number of calculation exceed the limit? if not, repeat the calculation, with sos being the &#8220;original&#8221; number, increase the counter and put sos in the alreadySeen set.</p>
<p>Note that this is a <a href="http://en.wikipedia.org/wiki/Tail_recursion">tail recursive</a> function, we can add @tailrec annotation to the method to let the compiler optimize it &#8211; turn the recursion into a loop so that it won&#8217;t grow in stack.</p>
<p>Now that we&#8217;ve had the body of the function, we can write an overload method that provides initial values:<br />
<code><br />
def isHappyNumber(n:Int):Boolean = isHappyNumber(n, 10, 0, Set[Int]())<br />
</code></p>
<p>To find all happy numbers between 1 and 100:<br />
<code><br />
println (1 to 100 filter { isHappyNumber(_) })<br />
</code></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/reminiscential.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/reminiscential.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/reminiscential.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/reminiscential.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/reminiscential.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/reminiscential.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/reminiscential.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/reminiscential.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/reminiscential.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/reminiscential.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/reminiscential.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/reminiscential.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/reminiscential.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/reminiscential.wordpress.com/205/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=reminiscential.wordpress.com&amp;blog=4716047&amp;post=205&amp;subd=reminiscential&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://reminiscential.wordpress.com/2010/07/23/finding-happy-numbers-using-scala/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/696a8f13a7fcf0b4265fe801f18ba7b5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kevinjqiu</media:title>
		</media:content>
	</item>
	</channel>
</rss>
