﻿<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom"><title type="text">Nerdworks Blogorama - Nerdspeak</title><subtitle type="text">The nerd shall inherit the earth.</subtitle><updated>2010-06-15T09:10:01Z</updated><author><name>Ranju. V</name><uri>http://blogorama.nerdworks.in/</uri><email>avranju@gmail.com</email></author><icon>http://blogorama.nerdworks.in/images/nw_logo.png</icon><id>http://blogorama.nerdworks.in/</id><link href="http://blogorama.nerdworks.in/" rel="alternate" type="text/html" /><link href="http://blogorama.nerdworks.in/atom.ashx" rel="self" type="application/atom+xml" /><entry><title>Writing a sensor driver for the Wiimote on Windows 7</title><link href="http://blogorama.nerdworks.in/entry-WritingasensordriverfortheWiim.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=45</id><updated>2010-02-05T16:57:28Z</updated><published>2010-02-05T16:57:28Z</published><content type="html">&lt;p style="text-align: justify"&gt;
    Ever since I saw &lt;a href="http://johnnylee.net/" target="_blank"&gt;Johnny Chung Lee&lt;/a&gt;'s
    &lt;a href="http://johnnylee.net/projects/wii/" target="_blank"&gt;demos&lt;/a&gt; of the innovative ways
    in which the &lt;a href="http://en.wikipedia.org/wiki/Wii_Remote" target="_blank"&gt;Nintendo Wiimote&lt;/a&gt;
    can be used as an input device for the PC, I've been hooked!  The Wiimote is a surprisingly
    self-contained piece of hardware that is able to operate independently apart from the Wii console.
    Among other things, the Wiimote features a 3-axis accelerometer which is the primary enabler
    for letting you do things like wave a virtual tennis racquet or roll a bowling ball down the alley.
    &lt;/p&gt;
    
    &lt;p style="text-align: justify"&gt;
    When Microsoft released &lt;a href="http://en.wikipedia.org/wiki/Windows_7" target="_blank"&gt;Windows 7&lt;/a&gt;,
    one of the new things that they added to the system was a brand new platform for managing a certain
    class of hardware devices known as "sensors".  Sensors are basically devices that, well, sense things!
    A &lt;a href="http://en.wikipedia.org/wiki/Global_Positioning_System" target=""&gt;GPS&lt;/a&gt; device for example
    is a sensor that can provide geographical location information.  Another example is an ambient light sensor
    that lets the system know how bright the ambient light is.  Now, these kinds of devices could be written
    and used even before Windows 7, just that now we have standard ways of exposing and consuming sensor
    data so that device vendors and application developers are able to communicate with each other in
    non-proprietary ways.
    &lt;/p&gt;

    &lt;p style="text-align: justify"&gt;
    So, putting the two together, I figured it'd be kind of neat to come up with a sensor driver that
    exposed the accelerometer data from the Wiimote to the sensor platform.  After some bit of head-scratching
    I managed to put something together.  I've written up an article about it and posted it over at
    &lt;a href="http://codeproject.com" target="_blank"&gt;CodeProject.com&lt;/a&gt;.  If you're interested, you can head
    over there and read all about it!  Here's the link:
    &lt;/p&gt;
    
    &lt;ul&gt;
    &lt;li&gt;&lt;a href="http://www.codeproject.com/KB/system/wiisensor.aspx" target="_blank"&gt;Writing a sensor driver for the Wiimote on Windows 7&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;</content></entry><entry><title>Enabling JSONP calls on ASP.NET MVC</title><link href="http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=44</id><updated>2010-03-09T08:50:36Z</updated><published>2009-10-19T14:15:09Z</published><content type="html">&lt;p style="text-align:justify"&gt;
    &lt;a href="http://en.wikipedia.org/wiki/Json#JSONP" target="_blank"&gt;JSONP&lt;/a&gt; is the technique of
    making cross-domain HTTP requests via JavaScript circumventing browser security restictions on
    requests that return data in the JSON format.  By cross-domain, we refer to the practice
    of making HTTP requests on URLs that refer to resources residing on a domain other than the one from where
    the page being viewed/executed was loaded from.  You'll find a good description
    of what JSONP is all about &lt;a href="http://www.insideria.com/2009/03/what-in-the-heck-is-jsonp-and.html" target="_blank"&gt;here&lt;/a&gt;.
    Briefly, the technique exploits a browser back-door where the &lt;code&gt;SRC&lt;/code&gt; attribute on a &lt;code&gt;SCRIPT&lt;/code&gt; tag
    is allowed to be a "foreign" URL and the browser will download the code and evaluate it.
    But then again, this is perhaps not so much a &lt;em&gt;back-door&lt;/em&gt; as a &lt;em&gt;feature&lt;/em&gt; that allows
    you to build mash-ups by composing code that draws on functionality hosted on different servers.  If this were not
    allowed then something like the &lt;a href="http://en.wikipedia.org/wiki/Content_delivery_network" target="_blank""&gt;Content Delivery Networks (CDN)&lt;/a&gt;
    would just not work.  In fact this blog that you're reading right now loads the &lt;a href="http://jquery.com/" target="_blank"&gt;jQuery&lt;/a&gt;
    JavaScript library via the &lt;a href="http://code.google.com/intl/hr/apis/ajaxlibs/" target="_blank"&gt;Google CDN&lt;/a&gt;.
    &lt;/p&gt;
    
    &lt;p style="text-align:justify"&gt;
    Here's an example of this in practice - I've loaded up the 5 most
    "&lt;a href="http://www.flickr.com/services/api/flickr.interestingness.getList.html" target="_blank"&gt;interesting&lt;/a&gt;"
    photos uploaded on &lt;a href="http://www.flickr.com/" target="_blank"&gt;Flickr&lt;/a&gt; in the last day or so below:
    &lt;/p&gt;
    
    &lt;script type="text/javascript" language="javascript"&gt;

        //
        // Flickr REST url
        //
        var url = "http://api.flickr.com/services/rest/?";

        //
        // My Flickr API key
        //
        var api_key = "bf3b5784792dcda75692837db1b6b0e5";

        //
        // build a flicker url from a photo object
        //
        function buildPhotoUrl(photo) {
            return "http://farm" + photo.farm + ".static.flickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + "_t.jpg";
        }

        //
        // get interesting photos
        //
        function getInterestingPhotos() {
            //
            // build the URL
            //
            var call = url + "method=flickr.interestingness.getList&amp;api_key=" + api_key + "&amp;per_page=5&amp;page=1&amp;format=json&amp;jsoncallback=?";

            //
            // make the ajax call
            //
            $.getJSON(call, function(rsp) {
                if (rsp.stat != "ok") {
                    //
                    // something went wrong!
                    //
                    $("#interesting_photos").append("&lt;label style=\"color:red; font-style:italic\"&gt;Whoops!  It didn't work!" +
                        "  This is embarrassing!  Here's what Flickr had to say about this - " +
                        rsp.message + "&lt;/label&gt;");
                }
                else {
                    //
                    // build the html
                    //
                    var html = "";
                    $.each(rsp.photos.photo, function() {
                        var photo = this;
                        html += "&lt;span&gt;&lt;img src=\"" + buildPhotoUrl(photo) + "\" title=\"" +
                                photo.title + "\" alt=\"" + photo.title + "\" /&gt;&lt;/span&gt;&amp;nbsp;";
                    });

                    //
                    // append this to the div
                    //
                    $("#interesting_photos").append(html);
                }
            });
        }

        //
        // get the photos
        //
        $(getInterestingPhotos);
    
    &lt;/script&gt;
    &lt;blockquote&gt;&lt;div id="interesting_photos"&gt;&lt;/div&gt;&lt;/blockquote&gt;
    
    &lt;p style="text-align:justify"&gt;
    And here's the code that accomplishes this with a little &lt;a href="http://jquery.com/" target="_blank"&gt;jQuery&lt;/a&gt; magic:
    &lt;/p&gt;
    
    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;//
// Flickr REST url
//
var url = "http://api.flickr.com/services/rest/?";

//
// My Flickr API key
//
var api_key = "&amp;lt;&amp;lt;your flickr api key here&amp;gt;&amp;gt;";

//
// build a flicker url from a photo object
//
function buildPhotoUrl(photo) {
    return "http://farm" + photo.farm +
           ".static.flickr.com/" + photo.server + "/" +
           photo.id + "_" + photo.secret + "_t.jpg";
}

//
// get interesting photos
//
function getInterestingPhotos() {
    //
    // build the URL
    //
    var call = url + "method=flickr.interestingness.getList&amp;api_key=" +
               api_key + "&amp;per_page=5&amp;page=1&amp;format=json&amp;jsoncallback=?";

    //
    // make the ajax call
    //
    $.getJSON(call, function(rsp) {
        if (rsp.stat != "ok") {
            //
            // something went wrong!
            //
            $("#interesting_photos").append(
                "&amp;lt;label style=\"color:red\"&amp;gt;Whoops!  It didn't work!" +
                "  This is embarrassing!  Here's what Flickr had to " +
                " say about this - " + rsp.message + "&amp;lt;/label&amp;gt;");
        }
        else {
            //
            // build the html
            //
            var html = "";
            $.each(rsp.photos.photo, function() {
                var photo = this;
                html += "&amp;lt;span&amp;gt;&amp;lt;img src=\"" + buildPhotoUrl(photo) +
                        "\" title=\"" + photo.title + "\" alt=\"" + photo.title +
                        "\" /&amp;gt;&amp;lt;/span&amp;gt;&amp;nbsp;";
            });

            //
            // append this to the div
            //
            $("#interesting_photos").append(html);
        }
    });
}

//
// get the photos
//
$(getInterestingPhotos);&lt;/pre&gt;
    &lt;/blockquote&gt;
    
    &lt;p style="text-align:justify"&gt;
    The basic idea is to dynamically add a &lt;code&gt;SCRIPT&lt;/code&gt; tag to the DOM where the
    &lt;code&gt;SRC&lt;/code&gt; attribute is pointing to the external URL where the data that we want
    resides.  Upon encountering a new &lt;code&gt;SCRIPT&lt;/code&gt; node, the browser immediately
    starts loading the code and evaluating it (and also freezes pretty much everything else
    in the browser while it is doing this!).  If we can have the external resource render a
    call to a function that we define (or to a well-known function name) in the script that
    it produces then we can effectively have a callback routine invoked when the data is
    received from the foreign domain.  The function to be called when the script dynamically
    loads is usually passed in as a query string parameter in the &lt;code&gt;GET&lt;/code&gt; request or can be a
    function name that is mandated by the 3rd party site.  Flickr for example defaults to
    rendering a call to a function called &lt;code&gt;jsonFlickrApi&lt;/code&gt; but allows you to
    override this by passing a different name via the &lt;code&gt;jsoncallback&lt;/code&gt;
    query string parameter.
    &lt;/p&gt;
    
    &lt;p style="text-align:justify"&gt;
    &lt;strong&gt;jQuery&lt;/strong&gt; has direct support for JSONP in that if you include a &lt;code&gt;callback=?&lt;/code&gt; parameter
    in the AJAX URL for the &lt;a href="http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback"&gt;&lt;code&gt;getJSON&lt;/code&gt;&lt;/a&gt;
    call then it will replace the &lt;code&gt;?&lt;/code&gt; with a dynamically generated global JavaScript function name
    that it also defines.  The word &lt;code&gt;callback&lt;/code&gt; can be replaced with anything else as we did above
    by using &lt;code&gt;jsoncallback&lt;/code&gt;.  All the grunt work of dynamically adding &lt;code&gt;SCRIPT&lt;/code&gt; tags to the
    DOM is done by jQuery.
    &lt;/p&gt;
    
    &lt;p style="text-align:justify"&gt;
    Now, imagine that you designed your own little REST based service using ASP.NET MVC and have
    opted to provide JSON as one of the data output formats and wish to support JSONP requests.  This
    basically means that you simply need to wrap your JSON output in a call to a user-supplied or a
    standard JavaScript function.  So instead of rendering something like this out to the client:
    &lt;/p&gt;
    
    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;{
    photos : [
        photo : {
            id : 232992,
            secret : "bAC980980c09c08a0ef"
        }
    ],
    page : 1,
    total : 500,
    photosPerPage : 10
}&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p style="text-align:justify"&gt;You want to render something like this:&lt;/p&gt;

    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;callback({
    photos : [
        photo : {
            id : 232992,
            secret : "bAC980980c09c08a0ef"
        }
    ],
    page : 1,
    total : 500,
    photosPerPage : 10
});&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p style="text-align:justify"&gt;
    Where &lt;code&gt;callback&lt;/code&gt; is the name of the JavaScript function defined by the client
    that needs to be invoked when the script is evaluated by the browser.  If you wanted your
    ASP.NET MVC controllers to support this, how would you do it?  The first approach I took
    was to simply define a custom &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.actionresult.aspx"&gt;&lt;code&gt;ActionResult&lt;/code&gt;&lt;/a&gt;
    class that would produce the correct script.  Here's what this looks like:
    &lt;/p&gt;

    
    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;/// &amp;lt;summary&amp;gt;
/// Renders result as JSON and also wraps the JSON in a call
/// to the callback function specified in "JsonpResult.Callback".
/// &amp;lt;/summary&amp;gt;
public class JsonpResult : JsonResult
{
    /// &amp;lt;summary&amp;gt;
    /// Gets or sets the javascript callback function that is
    /// to be invoked in the resulting script output.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;value&amp;gt;The callback function name.&amp;lt;/value&amp;gt;
    public string Callback { get; set; }

    /// &amp;lt;summary&amp;gt;
    /// Enables processing of the result of an action method by a
    /// custom type that inherits from &amp;lt;see cref="T:System.Web.Mvc.ActionResult"/&amp;gt;.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="context"&amp;gt;The context within which the
    /// result is executed.&amp;lt;/param&amp;gt;
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");

        HttpResponseBase response = context.HttpContext.Response;
        if (!String.IsNullOrEmpty(ContentType))
            response.ContentType = ContentType;
        else
            response.ContentType = "application/json";

        if (ContentEncoding != null)
            response.ContentEncoding = ContentEncoding;

        if (Callback == null || Callback.Length == 0)
            Callback = context.HttpContext.Request.QueryString["callback"];

        if (Data != null)
        {
            // The JavaScriptSerializer type was marked as obsolete
            // prior to .NET Framework 3.5 SP1 
#pragma warning disable 0618
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string ser = serializer.Serialize(Data);
            response.Write(Callback + "(" + ser + ");");
#pragma warning restore 0618
        }
    }
}&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p style="text-align: justify"&gt;
    Now you can simply return a &lt;code&gt;JsonpResult&lt;/code&gt; (note the &lt;u&gt;p&lt;/u&gt; before the "R" in "Result")
    from your action methods instead of &lt;code&gt;JsonResult&lt;/code&gt; and everything should just work.  Client's would
    indicate that this is a JSONP request by appending a query string parameter called &lt;code&gt;callback&lt;/code&gt;
    to the request with the name of a JavaScript function that is to be called.  I wasn't however,
    entirely happy with this situation as this would mean that I'd have to go and change the return
    type of &lt;em&gt;all&lt;/em&gt; my action methods to return a &lt;code&gt;JsonpResult&lt;/code&gt; instead of
    a &lt;code&gt;JsonResult&lt;/code&gt;.  And also update the code that instantiated &lt;code&gt;JsonResult&lt;/code&gt;.
    I wanted a less disruptive solution if you will.
    &lt;/p&gt;

    &lt;p style="text-align: justify"&gt;
    It is precisely for scenarios such as this that the ASP.NET MVC framework includes extension
    points in the form of &lt;a href="http://msdn.microsoft.com/en-us/library/dd410209.aspx" target="_blank"&gt;action filters&lt;/a&gt;.
    Action filters are basically hooks that you can define to intercept and enhance request processing
    in various ways.  ASP.NET MVC allows you to define filters that get called &lt;em&gt;before&lt;/em&gt; and/or &lt;em&gt;after&lt;/em&gt; the action
    method is invoked and also &lt;em&gt;before&lt;/em&gt; and/or &lt;em&gt;after&lt;/em&gt; the &lt;code&gt;ExecuteResult&lt;/code&gt; method on the &lt;code&gt;ActionResult&lt;/code&gt;
    is invoked.  Action filters are defined as .NET custom attribute classes that inherit from
    &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.actionfilterattribute.aspx" target="_blank"&gt;ActionFilterAttribute&lt;/a&gt;.
    &lt;code&gt;ActionFilterAttribute&lt;/code&gt; defines 4 virtual methods that you can override to hook into the
    request processing pipeline at the right juncture.  The &lt;code&gt;OnActionExecuted&lt;/code&gt; method for instance
    is invoked immediately &lt;em&gt;after&lt;/em&gt; the action method has been invoked and gives you a chance to further
    process the returned result.  This would perfectly suit our purpose here where we wish to conditionally
    supplant the &lt;code&gt;JsonResult&lt;/code&gt; object being returned from the action method with a &lt;code&gt;JsonpResult&lt;/code&gt;
    instead.  Here's what I came up with:
    &lt;/p&gt;

    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;public class JsonpFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if(filterContext == null)
            throw new ArgumentNullException("filterContext");

        //
        // see if this request included a "callback" querystring parameter
        //
        string callback = filterContext.HttpContext.Request.QueryString["callback"];
        if (callback != null &amp;&amp; callback.Length &amp;gt; 0)
        {
            //
            // ensure that the result is a "JsonResult"
            //
            JsonResult result = filterContext.Result as JsonResult;
            if (result == null)
            {
                throw new InvalidOperationException("JsonpFilterAttribute must be applied only " +
                    "on controllers and actions that return a JsonResult object.");
            }

            filterContext.Result = new JsonpResult
            {
                ContentEncoding = result.ContentEncoding,
                ContentType = result.ContentType,
                Data = result.Data,
                Callback = callback
            };
        }
    }
}&lt;/pre&gt;
    &lt;/blockquote&gt;
    
    &lt;p style="text-align: justify"&gt;
    As is perhaps self-evident, we simply check if the query string included a parameter called
    &lt;code&gt;callback&lt;/code&gt; and if it did, then we supplant the &lt;code&gt;Result&lt;/code&gt; object in
    &lt;code&gt;filterContext&lt;/code&gt; with a new &lt;code&gt;JsonpResult&lt;/code&gt; instance.  This approach allows us to
    enable JSONP processing on a controller or an action method by simply tagging on the
    &lt;code&gt;JsonpFilter&lt;/code&gt; attribute.  If I wanted all of my methods in the controller to
    support JSONP then, I can do this:
    &lt;/p&gt;
    
    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;[JsonpFilter]
public class DoofusController : Controller
{
    //
    // all your action methods here
    //
}&lt;/pre&gt;
    &lt;/blockquote&gt;
    
    &lt;p style="text-align: justify"&gt;
    Or if I wanted it to work with only a specific action method then I'd do this:
    &lt;/p&gt;
    
    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;public class DoofusController : Controller
{
    [JsonpFilter]
    public JsonResult DoTheThing(string data, string moreData)
    {
        return new JsonResult
        {
            Data = FetchSomeData(data, moreData)
        };
    }
}&lt;/pre&gt;
    &lt;/blockquote&gt;
    
    &lt;p style="text-align: justify"&gt;ASP.NET MVC is kind of cool eh?! :-P&lt;/p&gt;</content></entry><entry><title>The Conman</title><link href="http://blogorama.nerdworks.in/entry-TheConman.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=43</id><updated>2010-06-15T09:10:01Z</updated><published>2009-09-01T13:15:35Z</published><content type="html">&lt;p style="text-align: justify"&gt;The conman was seated at his usual vantage point, a place that afforded a clear view of the populace exiting the railway station. As he stubbed out his morning cigarette, he was sure he'd spotted his first quarry.&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"Aren't you from Sivan Master's household?" the conman accosted him as he was crossing the subway under M--- Road across the Central railway station.&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"Sivan who?"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"Err... Are you from Kerala?"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"Yes, Palakkad."&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"Where in Palakkad?"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"It's a village, about 12 kms from the town."&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"Ah! I am not mistaken then! Do you know postmaster Balan?"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"No"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"Well, I am his son. I knew I had seen you somewhere before! You're on your way back from home I gather?"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"Yes". The conman appeared to ponder this awhile.&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"What is your ancestral name?"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"I am from the &lt;I&gt;Mele Paadam&lt;/I&gt; house." &lt;/P&gt;
&lt;p style="text-align: justify"&gt;That seemed to clear the matter at once. With the widest grin he'd ever seen, the conman remarked, "Indeed! I know your family very well. You should ask your parents about Balan postmaster's son Vasu. You perhaps don't remember, but I have been to your house many times."&lt;/P&gt;
&lt;p style="text-align: justify"&gt;He just smiled pleasantly and continued making his way through the morning rush of work and school bound humanity.&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"You won't believe the trip I had yesterday night!" Vasu persisted, "The train we were in was stopped by dacoits!" This halted the quarry in his tracks.&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"Dacoits?!"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"Oh yes! Rumor has it that it was Veerappan! Haven't you read the papers?" he paused, "It perhaps hasn't made it to the press yet. But I am sure you'll read all about it in the evening edition! Suffice it to say that I am extremely lucky to be alive!"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;He looked at Vasu with concern and remarked, "That's quite awful!"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"Yes! Yes! My wife wasn't quite so lucky though. She has been admitted to the general hospital which is where I am headed right now. Oh! I don't know what I'll do!" Vasu was visibly distraught.  They were out of the subway by now.&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"They took everything you see." Vasu continued, "We escaped only with the clothes on our back!"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"Tragic! Quite tragic!"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"Yes! Yes! Quite! And I am so new to this city. I am so glad I saw you - you're a God send!"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;He faced Vasu and said abruptly, "Well, Vasu it was nice meeting you. Hope your wife recovers soon. Goodbye!"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"Yes, thank you! Goodbye then!" Vasu replied and turned away walking towards the hospital.&lt;/P&gt;
&lt;p style="text-align: justify"&gt;The quarry had waved an auto rickshaw and got into it before he heard the familiar voice call out to him again.&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"I feel so embarrassed saying this to somebody I've just met, but it is a desperate situation you see. Like I said, they took everything; even the money in my wallet! May they be struck by lightning!" Vasu cursed, "I am completely broke right now. Would you be able to spare some money? I will personally return it to the &lt;I&gt;Mele Paadam&lt;/I&gt; house once I get back. It will be a big help."&lt;/P&gt;
&lt;p style="text-align: justify"&gt;Seeing him hesitate, Vasu was quick to remark, "No, that's quite alright. I completely understand. Please forget that I ever asked. I apologize. Please give my regards to your parents." And made as if he would leave.&lt;/P&gt;
&lt;p style="text-align: justify"&gt;He stopped Vasu and said with feeling, "No Vasu, that's not it. It's just that... I don't have change you see. All I have is a Rs. 1000/- note. If you can spare Rs.100/- for this auto I'd happily hand it over to you. I am sure you need it more right now than I do."&lt;/P&gt;
&lt;p style="text-align: justify"&gt;There was an expression of genuine surprise on Vasu's face. He quickly recovered and said, "Thank you so much Sir! I was right, you truly are a God send! I do in fact happen to have this one Rs.100/- note. They forgot my secret pant pocket you see!"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;They quickly exchanged the money and Vasu said as he handed his hundred rupee note, "I promise to return this money as soon as I get back home. I shall never forget this favor! Again, thank you Sir, may God shower His blessings upon you."&lt;/P&gt;
&lt;p style="text-align: justify"&gt;"Oh! That's quite alright. Please go attend to your wife now. Goodbye!"&lt;/P&gt;
&lt;p style="text-align: justify"&gt;As the rickshaw sped away from the station, he thought, "Now, if only the rest of the fake notes were as easily spent!"&lt;/P&gt;

&lt;blockquote&gt;&lt;p style="text-align: justify"&gt;&lt;strong&gt;PS:&lt;/strong&gt; &lt;em&gt;My colleague cum boss cum general pain in the wrong part of the anatomy (otherwise known as Aravind) is
writing a series of really short stories over at his blog &lt;a href="http://movinghorizons.blogdrive.com/" target="_blank"&gt;Moving Horizons&lt;/a&gt; and doing a 
pretty good job of it - so much so that the writing bug seems to have bit me too now!  This little short here is my first shot at the genre (or any genre in 
writing any kind of ficitonal prose actually).  Feel free to critique, slobber mindlessly at its sheer blinding genius etc.&lt;/em&gt;&lt;/p&gt;&lt;/blockquote&gt;</content></entry><entry><title>Memoization - Optimize your function calls</title><link href="http://blogorama.nerdworks.in/entry-MemoizationOptimizeyourfunctio.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=42</id><updated>2009-07-31T12:04:34Z</updated><published>2009-07-31T12:04:34Z</published><content type="html">&lt;p style="text-align:justify"&gt;
    &lt;a href="http://en.wikipedia.org/wiki/Memoization" target="_blank"&gt;Memoization&lt;/a&gt; is an optimization technique where the
    idea is to create functions that cache computed values for various input sets so that subsequent invocations
    can return the value from the cache instead of re-computing the results. It is a simple space for time trade-off
    where processing time is reduced at the expense of increased memory use.  I figured I'd implement an &lt;em&gt;automatic
    memoization&lt;/em&gt; mechanism in JavaScript that will work well under certain well defined constraints.  Here's what I came
    up with:
    &lt;/p&gt;
    
    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;function memoize( fn ) {
    //
    // check if this function has already been memoized
    //
    if( typeof( fn.__fn ) == "undefined" ) {
        //
        // the cache where the results are to be stored
        //
        fn.__cache = {};
        
        //
        // memoized version of the function
        //
        fn.__fn = function() {
            //
            // build the key that represents the given input set;
            // note that this thing works only so long as the operation
            // "toString" returns a meaningful result on all of the
            // parameters
            //
            var key = "";
            for( var i = 0 ; i &lt; arguments.length ; ++i )
                key += arguments[i].toString() + "-";
            
            //
            // if the result for the current parameter set already exists
            // in the cache then return that; otherwise call the original
            // routine and store the result
            //
            if( typeof( fn.__cache[key] ) == "undefined" )
                fn.__cache[key] = fn.apply( null, arguments );
            return fn.__cache[key];
        }
    }
    
    return fn.__fn;
}&lt;/pre&gt;
    &lt;/blockquote&gt;
    
    &lt;p style="text-align:justify"&gt;Imagine that you are tasked with the job of writing a Javascript function that
    returns the factorial given a number.  If you wished to write a &lt;em&gt;memoized&lt;/em&gt; version of the function here's
    what you'd do:&lt;/p&gt;

    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;var fac = memoize( function( n ) {
    if( n &lt;= 0 )
        return 1;
    return ( n * fac( n - 1 ) );
} );&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p style="text-align:justify"&gt;
    If you invoked &lt;code&gt;fac&lt;/code&gt; passing &lt;code&gt;5&lt;/code&gt; for instance, and traced the control flow, here's the sequence
    of calls you'd see:
    &lt;/p&gt;

    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;. __fn(5)
.. fac(5)
... __fn(4)
.... fac(4)
..... __fn(3)
...... fac(3)
....... __fn(2)
........ fac(2)
......... __fn(1)
.......... fac(1)
........... __fn(0)
............ fac(0)&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p style="text-align:justify"&gt;
    The number of dots to the left of the function names indicates the stack depth and here it tends
    to increase because &lt;code&gt;fac&lt;/code&gt; is a recursive function and keeps calling itself till the termination criteria is met.
    This seems like a drawback since where you'd have had a sequence of calls to just &lt;code&gt;fac&lt;/code&gt; now we see it
    interspersed with calls to &lt;code&gt;__fn&lt;/code&gt; also, effectively doubling the number of function calls that needs to
    be made.  The benefit however, is realized when we observe what happens when &lt;code&gt;fac&lt;/code&gt; is invoked again, a
    second time, passing &lt;code&gt;5&lt;/code&gt;.
    &lt;/p&gt;
    
    &lt;blockquote&gt;&lt;pre class="prettyprint"&gt;. __fn(5)&lt;/pre&gt;&lt;/blockquote&gt;
    
    &lt;p style="text-align:justify"&gt;
    As you can see, this time around, there was only a single function call.  No further computation was needed as the
    required result was already available in the cache and only a simple look-up operation was performed.  Observe what
    happens when we pass &lt;code&gt;3&lt;/code&gt; next.
    &lt;/p&gt;
    
    &lt;blockquote&gt;&lt;pre class="prettyprint"&gt;. __fn(3)&lt;/pre&gt;&lt;/blockquote&gt;
    
    &lt;p style="text-align:justify"&gt;
    This was resolved via cache look-up also because the first call with &lt;code&gt;5&lt;/code&gt; had recursively invoked &lt;code&gt;fac&lt;/code&gt;
    with &lt;code&gt;3&lt;/code&gt; as well.  On a similar note, passing &lt;code&gt;7&lt;/code&gt; produces the following call sequence:
    &lt;/p&gt;
    
    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;. __fn(7)
.. fac(7)
... __fn(6)
.... fac(6)
..... __fn(5)&lt;/pre&gt;
    &lt;/blockquote&gt;
    
    &lt;p style="text-align:justify"&gt;
    Automatic memoization ensures that the original routine is called only the bare minimum number of times - in this case, for
    the values &lt;code&gt;7&lt;/code&gt; and &lt;code&gt;6&lt;/code&gt;.  The implementation of &lt;code&gt;memoize&lt;/code&gt; given above is useful only so long
    as the following are held true:
    &lt;/p&gt;
    
    &lt;ol type="1"&gt;
        &lt;li&gt;Each parameter passed to the actual function has a &lt;code&gt;toString&lt;/code&gt; method that returns a meaningful value; if
        you passed a custom object for instance, you're going to have to define a &lt;code&gt;toString&lt;/code&gt; method on it.&lt;/li&gt;
        
        &lt;li&gt;The CPU overhead of constructing a unique key for a given parameter set and doing hashtable lookups should
        be lower (preferably &lt;em&gt;significantly&lt;/em&gt;) than simply performing the actual work.&lt;/li&gt;
        
        &lt;li&gt;For obvious reasons, the function should have at least 1 parameter!&lt;/li&gt;
    &lt;/ol&gt;
    
    &lt;p style="text-align:justify"&gt;
    If you've been following this blog, you know that I am trying to learn the &lt;a href="http://en.wikipedia.org/wiki/Common_Lisp"&gt;
    &lt;em&gt;Common Lisp&lt;/em&gt;&lt;/a&gt; programming language. I figured, I'll try and implement &lt;code&gt;memoize&lt;/code&gt; in &lt;em&gt;Common
    Lisp&lt;/em&gt; as well, to see if I'd learned enough of it to be able to do this.  After looking up the
    &lt;a href="http://www.lispworks.com/documentation/HyperSpec/Front/"&gt;Common Lisp Hyperspec&lt;/a&gt; a few times, I was in fact
    able to come up with an implementation that does essentially the same thing as what the JavaScript version above does.
    Here goes:
    &lt;/p&gt;

    &lt;blockquote&gt;
    &lt;pre class="prettyprint lang-cl"&gt;(defun make-key (lst)
  (format nil "~{~A-~}" lst))

(defun memoize (fn)
  (let ((cache (make-hash-table :test 'equal)))
    #'(lambda (&amp;rest p)
	(let ((key (make-key p)))
	  (if (not (gethash key cache))
	    (setf (gethash key cache) (apply fn p)))
	  (gethash key cache)))))

(setf fac (memoize #'(lambda (n)
                        (if (&lt;= n 0) 1
                            (* n (funcall fac (- n 1)))))))
&lt;/pre&gt;
    &lt;/blockquote&gt;</content></entry><entry><title>Random Lisp thoughts</title><link href="http://blogorama.nerdworks.in/entry-RandomLISPthoughts.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=41</id><updated>2009-07-26T10:03:12Z</updated><published>2009-07-23T09:04:37Z</published><content type="html">&lt;p style="text-align:justify"&gt;
    I have covered about 4 chapters from the book &lt;a href="http://gigamonkeys.com/book/"&gt;Practical Common Lisp&lt;/a&gt;
    and what I have learnt so far is quite fascinating to say the least.  Here're some random observations that
    I happened to make about Commmon Lisp.  Please note that whenever I use the term &lt;em&gt;Lisp&lt;/em&gt; below I refer
    to the &lt;em&gt;Common Lisp&lt;/em&gt; dialect of the language.
    &lt;/p&gt;

    &lt;ul&gt;
        &lt;li&gt;
            &lt;p style="text-align:justify"&gt;Contrary to what one might conclude upon encountering a typical Lisp program, the basic
            Lisp syntax is actually quite minimalistic.  It is so minimalistic in fact that I can probably explain all of
            Lisp syntax in about one line (OK, not &lt;em&gt;all&lt;/em&gt; of it, but maybe a significant chunk of it - the point is, the
            basic structure of Lisp code is fairly straightforward)!  Here goes:&lt;/p&gt;
            
            &lt;blockquote&gt;&lt;em&gt;Any Lisp code is a line of space delimited list of "things" and nested lists enclosed in parentheses.&lt;/em&gt;&lt;/blockquote&gt;
            
            &lt;p style="text-align:justify"&gt;By "things", I mean pretty much everything that can go into Lisp code.  Here's some lisp code:&lt;/p&gt;
            
            &lt;blockquote&gt;&lt;pre class="prettyprint lang-cl"&gt;(believe it or not but this is some lisp code!)&lt;/pre&gt;&lt;/blockquote&gt;
            
            &lt;p style="text-align:justify"&gt;And here's another example with nested lists:&lt;/p&gt;
            
            &lt;blockquote&gt;&lt;pre class="prettyprint lang-cl"&gt;(lisp code (with nested lists))&lt;/pre&gt;&lt;/blockquote&gt;
            
            &lt;p style="text-align:justify"&gt;If you tried entering this stuff at an
            &lt;a href="http://en.wikipedia.org/wiki/Read-eval-print_loop"&gt;interactive&lt;/a&gt; Lisp shell prompt however,
            you are bound to have been slapped with some errors and that's because even though this conforms to Lisp
            code structure it really doesn't mean anything.  Its like trying to feed some random bit of
            &lt;a href="http://en.wikipedia.org/wiki/XML"&gt;XML&lt;/a&gt; to an &lt;a href="http://en.wikipedia.org/wiki/Extensible_Stylesheet_Language"&gt;XSL&lt;/a&gt;
            parser, or trying to pass an XSL file to the &lt;a href="http://en.wikipedia.org/wiki/Apache_Ant"&gt;ANT&lt;/a&gt; program.
            In each of these cases, though we are passing well-formed XML they don't exactly have the
            tags that the respective programs are looking for.&lt;/p&gt;
            
            &lt;p style="text-align:justify"&gt;What we have accomplished with our definition above therefore is to
            specify what Lisp expressions are to look like.  Imagine specifying the entire
            XML &lt;a href="http://www.w3.org/TR/REC-xml/"&gt;specification&lt;/a&gt; in one line (which of course is quite impossible
            because the actual spec runs to about 50 pages)!  For a fully featured multi-paradigm programming language I
            think this is quite an incredible feat!&lt;/p&gt;

            &lt;p style="text-align:justify"&gt;The technical Lisp term for what we have defined above is an &lt;em&gt;s-expression&lt;/em&gt;.
            Any piece of valid Lisp code is always a valid s-expression but as you might have discovered if you tried getting
            a Lisp interpreter to parse the examples given above, not all valid s-expressions
            are valid Lisp code.  And that is where the typical Lisp noob (such as yours truly) spends time learning the language.  But as is perhaps
            self evident, the terseness of the basic syntax for Lisp code goes a long way in accelerating the learning
            process and all the apparently confounding parentheses actually end up being a rather natural way of doing things.&lt;/p&gt;
        &lt;/li&gt;
        &lt;li&gt;
            &lt;p style="text-align:justify"&gt;The basic Lisp form is so simple that I was able to whip up a little Lisp parser
            in JavaScript in about half an hour!  Here's the complete parser:&lt;/p&gt;
            
            &lt;blockquote&gt;
            &lt;pre class="prettyprint"&gt;//
// Each node in the parse tree can be a list or a symbol.
//
var NodeType = {
    List: 0,
    Symbol: 1
};

//
// Each node is defined by its type and content which in
// turn can be another node (list) or a symbol name.
//
function Node(type, content) {
    this.type = type;
    this.content = content;
}

//
// Helper function that generates a "Node" object given
// a symbol name.
//
function symbol(sym) {
    return new Node(NodeType.Symbol, sym);
}

//
// Helper function that generates a "Node" object given
// a list object.
//
function list(lst) {
    return new Node(NodeType.List, lst);
}

//
// Helper function that trims a string for leading/trailing white space.
//
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
}

//
// The Lisp lexer that can tokenize a string of Lisp code.
//
function Lexer(code) {
    this.code = code;
    var current = 0;
    var delims = "( )";

    this.nextToken = function() {
        var token = null;
        //
        // skip all white-space only tokens
        //
        while (((token = internalNextToken.apply(this)) != null) &amp;&amp; (token.trim().length == 0));
        return token;
    }

    function internalNextToken() {
        //
        // if we have reached end of code then return null
        //
        if (current &gt;= this.code.length)
            return null;

        //
        // accumulate characters into token till one of
        // the delimiters are encountered
        //
        var token = "";
        for (; current &lt; this.code.length; ++(current)) {
            var ch = this.code.charAt(current);
            if (isDelim(ch)) {
                if (token.length == 0) {
                    token += ch;
                    ++current;
                }

                break;
            }

            token += ch;
        }

        return token;
    }

    function isDelim(ch) {
        return (delims.indexOf(ch) != -1);
    }
}

//
// The Lisp parser class that generates a parse tree composed of
// "Node" object given a lexer object.
//
function Parser(lexer) {
    this.lexer = lexer;

    this.parseList = function() {
        var token;
        var lst = [];
        while (((token = this.lexer.nextToken()) != null) &amp;&amp; (token != ")")) {
            switch (token) {
                case "(":
                    lst.push(this.parseList());
                    break;
                default:
                    lst.push(symbol(token));
                    break;
            }
        }

        return list(lst);
    };

    this.parse = function() {
        //
        // the first token MUST be a "("
        //
        if (this.lexer.nextToken() != "(")
            return null;
        return this.parseList();
    };
}

//
// Parse some lisp code.
//
var code = "(sum (gen-multiples (gen-series 1000) 3 5))";
var parser = new Parser(new Lexer(code));
var root = parser.parse();&lt;/pre&gt;
            &lt;/blockquote&gt;


            &lt;p style="text-align:justify"&gt;This code simply generates an in-memory tree representation of the
            Lisp expression without performing any validation to check for correctness.  This is akin to
            writing a non-validating DOM parser for XML - it simply hands you an object graph that you can
            programmatically traverse and do stuff with.  I wrote a little HTML page to generate parse-tree
            visualizations given Lisp expressions of arbitrary complexity using the
            &lt;a href="http://code.google.com/apis/visualization/"&gt;Google Visualization API&lt;/a&gt; and the
            &lt;a href="http://code.google.com/apis/visualization/documentation/gallery/orgchart.html"&gt;Organizational Chart&lt;/a&gt;
            visualization in particular.  Given the following Lisp expression
            for instance:&lt;/p&gt;
            
            &lt;blockquote&gt;&lt;pre class="prettyprint lang-cl"&gt;(sum (gen-multiples (gen-series 1000) 3 5))&lt;/pre&gt;&lt;/blockquote&gt;
            
            &lt;p style="text-align:justify"&gt;Here's the tree representation:&lt;/p&gt;
            
            &lt;blockquote&gt;
                &lt;img style="border: 1px solid black"
                     src="images/p1.png"
                     alt="Parse tree for Lisp expression (sum (gen-multiples (gen-series 1000) 3 5))" /&gt;
            &lt;/blockquote&gt;
            
            &lt;p style="text-align:justify"&gt;And for the following slightly more complex Lisp expression:&lt;/p&gt;
            
            &lt;blockquote&gt;&lt;pre class="prettyprint lang-cl"&gt;(sqrt (1+ (* (- (/ 28 2) 10) 2)))&lt;/pre&gt;&lt;/blockquote&gt;
            
            &lt;p style="text-align:justify"&gt;Here's the tree representation:&lt;/p&gt;
            
            &lt;blockquote&gt;
                &lt;img style="border: 1px solid black"
                     src="images/p2.png"
                     alt="Parse tree for Lisp expression (sqrt (1+ (* (- (/ 28 2) 10) 2)))" /&gt;
            &lt;/blockquote&gt;
            
            &lt;p style="text-align:justify"&gt;You can try building Lisp expression trees of your own at the following
            location:&lt;/p&gt;
            
            &lt;blockquote&gt;
                &lt;a href="http://blogorama.nerdworks.in/arbit/webstuff/lisp-graph.html"
                   target="_blank"&gt;Build your own Lisp expression trees&lt;/a&gt;
            &lt;/blockquote&gt;
        &lt;/li&gt;
        &lt;li&gt;
            &lt;p style="text-align:justify"&gt;Lisp s-expressions (i.e. valid Lisp form s-expressions) are of 3 types:&lt;/p&gt;
            &lt;ol type="1"&gt;
                &lt;li&gt;Function calls&lt;/li&gt;
                &lt;li&gt;Macro invocations&lt;/li&gt;
                &lt;li&gt;Special forms&lt;/li&gt;
            &lt;/ol&gt;
            &lt;p style="text-align:justify"&gt;Function calls, are, well, function calls!  In keeping with the minimalistic
            syntax philosophy, almost everything in Lisp is a function call (except of course, &lt;em&gt;macros&lt;/em&gt; and &lt;em&gt;special forms&lt;/em&gt;).
            Take for instance, arithmetic operators.  In most languages, the compiler is able to natively recognize
            operators such as [&lt;code&gt;+ - / *&lt;/code&gt;] and assign special meanings depending on the context where they are
            used and for that reason must, among other things, differentiate between unary, binary and ternary operators.
            In Lisp however, these are all function calls!&lt;/p&gt;
            
            &lt;p style="text-align:justify"&gt;The general form of a function call is like so:&lt;/p&gt;
            
            &lt;blockquote&gt;&lt;pre class="prettyprint lang-cl"&gt;(function-name [arg1 arg2 ... argN])&lt;/pre&gt;&lt;/blockquote&gt;
            
            &lt;p style="text-align:justify"&gt;As is perhaps obvious, a function call is expressed simply as a list
            where the first element is considered to be the function name and everything else its arguments.  As always,
            the arguments can be Lisp s-expressions themselves.  If you wanted to add 2 numbers
            for instance, here's what you'd do:&lt;/p&gt;
            
            &lt;blockquote&gt;&lt;pre class="prettyprint lang-cl"&gt;(+ 1 2)&lt;/pre&gt;&lt;/blockquote&gt;
            
            &lt;p style="text-align:justify"&gt;Here, &lt;code&gt;+&lt;/code&gt; is the name of the function being invoked and
            &lt;code&gt;1&lt;/code&gt; and &lt;code&gt;2&lt;/code&gt; are its arguments.  The function &lt;code&gt;+&lt;/code&gt; can accept a variable
            number of arguments (like the C &lt;code&gt;printf&lt;/code&gt; function), which means that in order to add 4
            numbers for instance, you can simply do this:&lt;/p&gt;
            
            &lt;blockquote&gt;&lt;pre class="prettyprint lang-cl"&gt;(+ 1 2 3 4)&lt;/pre&gt;&lt;/blockquote&gt;
            
            &lt;p style="text-align:justify"&gt;You can build compound lists by nesting s-expressions like so:&lt;/p&gt;
            
            &lt;blockquote&gt;&lt;pre class="prettyprint lang-cl"&gt;(+ 1 2 (+ 3 4))&lt;/pre&gt;&lt;/blockquote&gt;
            
            &lt;p style="text-align:justify"&gt;Lisp will always evaluate the function arguments first from left to
            right (evaluating nested s-expressions if any) and only then invoke the function with the result of
            evaluating the argument forms.  In the example above therefore, it will evaluate &lt;code&gt;1&lt;/code&gt; and
            &lt;code&gt;2&lt;/code&gt; first - which evaluate to themselves, i.e. &lt;code&gt;1&lt;/code&gt; and &lt;code&gt;2&lt;/code&gt; - followed
            by &lt;code&gt;(+ 3 4)&lt;/code&gt; - which evaluates to &lt;code&gt;7&lt;/code&gt;.  The resulting 3 numbers (&lt;code&gt;1&lt;/code&gt;,
            &lt;code&gt;2&lt;/code&gt; and &lt;code&gt;7&lt;/code&gt;) are then passed to &lt;code&gt;+&lt;/code&gt; which evaluates the composite
            expression to the value &lt;code&gt;10&lt;/code&gt;.&lt;/p&gt;
        &lt;/li&gt;
    &lt;/ul&gt;
    
    &lt;p style="text-align:justify"&gt;There's a lot more that one can say about functions.  I'll cover some of it in a
    subsequent post and also talk a bit about &lt;em&gt;macros&lt;/em&gt; (which while a rather unique feature of Lisp is also
    at the same time quite powerful) and &lt;em&gt;special forms&lt;/em&gt;.&lt;/p&gt;</content></entry><entry><title>Learning Common Lisp</title><link href="http://blogorama.nerdworks.in/entry-LearningLISP.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=40</id><updated>2009-07-26T10:15:37Z</updated><published>2009-07-18T14:38:15Z</published><content type="html">&lt;p style="text-align:justify"&gt;
    As is frequently the case with such things (at least with me) I have decided, for
    no compelling reason whatsoever, that I will learn to program in the
    &lt;a href="http://en.wikipedia.org/wiki/Common_Lisp" target="_blank"&gt;Common Lisp&lt;/a&gt; programming
    language.  It might perhaps have something to do with the fact that I stumbled upon the
    following impassioned pleas for that language and the functional style of programming,
    all of which are in my opinion well worth your while should you choose to spend the next hour
    or so of your life reading them, even if you have no plans of learning Lisp:
    &lt;/p&gt;

    &lt;blockquote&gt;
    &lt;dl&gt;
        &lt;dt&gt;&lt;a href="http://www.defmacro.org/ramblings/fp.html"  target="_blank"&gt;Functional Programming For The Rest of Us&lt;/a&gt;&lt;/dt&gt;
        &lt;dd&gt; - an introduction to functional programming designed to appeal to us
            &lt;a href="http://en.wikipedia.org/wiki/Imperative_programming" target="_blank"&gt;imperative&lt;/a&gt; grunt programmers.&lt;br /&gt;&lt;br /&gt;
        &lt;/dd&gt;

        &lt;dt&gt;&lt;a href="http://www.defmacro.org/ramblings/lisp.html" target="_blank"&gt;The Nature of Lisp&lt;/a&gt;&lt;/dt&gt;
        &lt;dd&gt; - an admirable attempt at showing to the Lisp noob what its all really about.&lt;br /&gt;&lt;br /&gt;&lt;/dd&gt;
        
        &lt;dt&gt;&lt;a href="http://www.paulgraham.com/avg.html" target="_blank"&gt;Beating The Averages&lt;/a&gt;&lt;/dt&gt;
        &lt;dd&gt; - if you thought Lisp was only for "intellectual" academicians, then you've got to hear from this
        &lt;a href="http://en.wikipedia.org/wiki/Paul_Graham"&gt;guy&lt;/a&gt; who made, like 50 million bucks
        by selling a piece of software to Yahoo - and guess what he wrote it in?&lt;br /&gt;&lt;br /&gt;
        &lt;/dd&gt;
        
        &lt;dt&gt;&lt;a href="http://www.paulgraham.com/iflisp.html" target="_blank"&gt;If Lisp is So Great&lt;/a&gt;&lt;/dt&gt;
        &lt;dd&gt; - tries to answer this question: &lt;em&gt;if Lisp is so great, why don't more people use it?&lt;/em&gt;&lt;/dd&gt;
    &lt;/dl&gt;
    &lt;/blockquote&gt;
    
    &lt;p style="text-align:justify"&gt;
    This being my blog and everything, I plan to use it to post what I hope will be a series of
    entries chronicling my experiments with Common Lisp.  There is frequent reference in popular Lisp
    literature to this so called moment of enlightenment that you apparently experience at some
    point as you work your way through the language.  If this occurs with me, well, you'll know
    about it!
    &lt;/p&gt;
    
    &lt;p style="text-align:justify"&gt;
    Here's what I am using to learn the thing:
    &lt;/p&gt;
    
    &lt;ul&gt;
        &lt;li&gt;&lt;a href="http://gigamonkeys.com/book/"&gt;Practical Common Lisp&lt;/a&gt; by Peter Seibel - a great free
        book that teaches you ANSI Common Lisp&lt;/li&gt;
        &lt;li&gt;&lt;a href="http://clisp.cons.org/"&gt;CLISP&lt;/a&gt; - a free open source implementation of the ANSI
        Common Lisp language (running on &lt;a href="http://www.cygwin.com/"&gt;Cygwin&lt;/a&gt; on Windows boxes -
        just remember to select the "clisp" package when you install Cygwin)&lt;/li&gt;
    &lt;/ul&gt;
    
    &lt;p style="text-align:justify"&gt;
    Here's what this dude called &lt;a href="http://en.wikipedia.org/wiki/Eric_S._Raymond"&gt;Eric Raymond&lt;/a&gt;
    had to say about Lisp:
    &lt;/p&gt;
    
    &lt;blockquote&gt;&lt;em&gt;Lisp is worth learning for the profound enlightenment experience you will have when
    you finally get it; that experience will make you a better programmer for the rest of your days...&lt;/em&gt;
    &lt;/blockquote&gt;
    
    &lt;p style="text-align:justify"&gt;I intend to personally find out if there's any truth to this or if Eric
    was just high when he wrote it (OK, so I do have a reason for learning Common Lisp - I never said I'll never
    contradict myself you know).&lt;/p&gt;</content></entry><entry><title>JavaScript closures act like implicit function state?</title><link href="http://blogorama.nerdworks.in/entry-JavaScriptclosuresactlikeimpli.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=39</id><updated>2009-07-12T15:36:27Z</updated><published>2009-07-12T15:36:27Z</published><content type="html">&lt;p style="text-align:justify"&gt;
    Consider this JavaScript code:
    &lt;/p&gt;

    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;function acc( n ) {
    return function( i ) {
        return n += i;
    };
}

var fn = acc( 5 );
var n1 = fn( 1 );
var n2 = fn( 2 );&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p style="text-align:justify"&gt;
    The question, of course, is what the values of &lt;code&gt;n1&lt;/code&gt; and &lt;code&gt;n2&lt;/code&gt;
    will be.  It is perhaps evident that &lt;code&gt;n1&lt;/code&gt; must now equal to &lt;code&gt;6&lt;/code&gt;.
    But what about &lt;code&gt;n2&lt;/code&gt;?  Will it now contain &lt;code&gt;7&lt;/code&gt; (i.e. &lt;code&gt;2 + 5&lt;/code&gt;)
    or will successive calls to &lt;code&gt;fn&lt;/code&gt; result in the parameters being accumulated by
    addition with the value that was passed to &lt;code&gt;acc&lt;/code&gt; (&lt;code&gt;5&lt;/code&gt;)?  We find by
    experimentation that the latter turns out to be true.  &lt;code&gt;n2&lt;/code&gt; now equals &lt;code&gt;8&lt;/code&gt;,
    i.e., &lt;code&gt;5 + 1 + 2&lt;/code&gt;!
    &lt;/p&gt;

    &lt;p style="text-align:justify"&gt;
    The conclusion to draw here therefore is that JavaScript function
    &lt;a href="http://en.wikipedia.org/wiki/Closure_(computer_science)"&gt;closures&lt;/a&gt; are essentially
    implicit function state.  In the code snippet given above, if you treat &lt;code&gt;fn&lt;/code&gt; as a
    regular object (which in fact it is), then the variable &lt;code&gt;n&lt;/code&gt; which is part of the
    closure captured by the function object when it was returned from &lt;code&gt;acc&lt;/code&gt; now acts like
    member state of &lt;code&gt;fn&lt;/code&gt;.  This is why multiple calls to &lt;code&gt;fn&lt;/code&gt; causes the
    mutation to &lt;code&gt;n&lt;/code&gt; to persist across those calls.
    &lt;/p&gt;

    &lt;p style="text-align:justify"&gt;
    This is further corroborated by the fact that a subsequent call to &lt;code&gt;acc&lt;/code&gt; to create
    another function object results in that instance getting a separate copy of  the closure
    containing &lt;code&gt;n&lt;/code&gt;.  Here's an example:
    &lt;/p&gt;

&lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;function acc( n ) {
    return function( i ) {
        return n += i;
    };
}

var fn = acc( 5 );
var n1 = fn( 1 );
var n2 = fn( 2 );

var fn2 = acc( 10 );
var n3 = fn2( 1 );
var n4 = fn2( 2 );&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p style="text-align:justify"&gt;
    Here, &lt;code&gt;n3&lt;/code&gt; and &lt;code&gt;n4&lt;/code&gt; hold &lt;code&gt;11&lt;/code&gt; and &lt;code&gt;13&lt;/code&gt; respectively.
    The function &lt;code&gt;fn&lt;/code&gt; has no effect whatsoever on &lt;code&gt;fn2&lt;/code&gt; (or vice versa).  This
    in fact, is the basis for creating the C++ equivalent of &lt;em&gt;private&lt;/em&gt; member data in JavaScript.
    Imagine that you wish to create the equivalent of the .NET
    &lt;a href="http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx"&gt;StringBuilder&lt;/a&gt;
    class and want to make the buffer where the string is actually stored a private member of the
    class.  If you did this:
    &lt;/p&gt;

    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;function StringBuilder() {
    this.buffer = [];
}&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p style="text-align:justify"&gt;
    Then &lt;code&gt;buffer&lt;/code&gt; is a &lt;em&gt;public&lt;/em&gt; member and can be accessed via an instance.  To make
    it private, simply declare &lt;code&gt;buffer&lt;/code&gt; as a local variable inside &lt;code&gt;StringBuilder&lt;/code&gt;.
    Like this:
    &lt;/p&gt;

    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;function StringBuilder() {
    var buffer = [];
    
    this.getBuffer = function() {
        //
        // TODO:
        // return a copy so the original buffer is
        // left intact
        //
        return buffer;
    }
}&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p style="text-align:justify"&gt;
    Now &lt;code&gt;buffer&lt;/code&gt; is not visible to routines defined outside &lt;code&gt;StringBuilder&lt;/code&gt; via
    an instance.  But all methods defined inside &lt;code&gt;StringBuilder&lt;/code&gt; can access &lt;code&gt;buffer&lt;/code&gt;
    like any other member.  You'd have to add &lt;a href="http://en.wikipedia.org/wiki/Accessor"&gt;accessor&lt;/a&gt;
    methods if you wished to provide access to private data.  The same principle applies to member methods
    as well.  Any local functions that you defined inside &lt;code&gt;StringBuilder&lt;/code&gt; remain accessible
    only from other functions defined inside that class.
    &lt;/p&gt;

    &lt;p style="text-align:justify"&gt;Cool eh?!&lt;/p&gt;</content></entry><entry><title>Calling a JavaScript function with variable arguments</title><link href="http://blogorama.nerdworks.in/entry-CallingaJavaScriptfunctionwith.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=38</id><updated>2009-07-04T15:21:37Z</updated><published>2009-07-04T15:15:50Z</published><content type="html">&lt;p style="text-align:justify"&gt;
    I am working on this little &lt;a href="http://en.wikipedia.org/wiki/Windows_Script_Host"&gt;Windows Scripting Host&lt;/a&gt;
    script using JavaScript where I basically need to load up a Word document and do a bunch of text transformation
    tasks on each line and dump the output to the console (which I plan to redirect to a file).  I decided to employ
    the &lt;a href="http://en.wikipedia.org/wiki/Builder_pattern"&gt;builder&lt;/a&gt; pattern a bit and set something up like
    this first:
    &lt;/p&gt;
    
    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;//
// transform events collection
//
var transformTable = {
    parseFileBegin : [],
    parseLineBegin : [],
    parseLineEnd : [],
    parseFileEnd : []
};&lt;/pre&gt;
    &lt;/blockquote&gt;
    
    &lt;p style="text-align:justify"&gt;
    The idea is to populate the arrays &lt;code&gt;parseFileBegin&lt;/code&gt; and &lt;code&gt;parseFileEnd&lt;/code&gt; with
    a set of function object references that would get called in sequence at the appropriate time.  To
    make calling these callbacks easier I decided to come up with a &lt;code&gt;fireEvent&lt;/code&gt; routine
    which I could then use to fire a particular set of callback functions.  I wanted also, to be able
    to call &lt;code&gt;fireEvent&lt;/code&gt; passing as many arguments as are needed for that particular callback.
    When invoking &lt;code&gt;parseFileBegin&lt;/code&gt; for instance, I wanted to pass the name of the file as
    a parameter to the callback routines and when calling &lt;code&gt;parseLineBegin&lt;/code&gt; I wanted to pass
    in a tokenized form of each line along with the line string itself.  Here're a couple of examples
    of how I wanted to call &lt;code&gt;fireEvent&lt;/code&gt;.
    &lt;/p&gt;
    
    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;fireEvent(transformTable.parseFileBegin, fileName);
fireEvent(transformTable.parseLineBegin, line, tokens);&lt;/pre&gt;
    &lt;/blockquote&gt;
    
    And here's what I came up with for &lt;code&gt;fireEvent&lt;/code&gt;:
    
    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;function forEach( arr, cb ) {
    for( var i = 0 ; i &lt; arr.length ; ++i )
        if( cb( arr[i] ) == false )
            return false;

    return true;
}

function fireEvent(eventHandlers) {
    //
    // everything after the first argument must be
    // considered as parameters to be passed to the
    // event handler routines
    //
    var args = [];
    var i = 0;
    forEach(arguments, function( arg ) {
        if( i++ == 0 )
            return;
        args.push( arg );
    });

    //
    // iterate through the handlers collection and call one by one
    //
    forEach(eventHandlers, function(handler) {
        // TODO: call the handler
    });
}&lt;/pre&gt;
    &lt;/blockquote&gt;
    
    &lt;p style="text-align:justify"&gt;
    I needed to somehow call the function referenced by &lt;code&gt;handler&lt;/code&gt; and
    pass all the values in the &lt;code&gt;args&lt;/code&gt; array as parameters to it.  One way
    might have been to dynamically build a string of JavaScript code that calls
    &lt;code&gt;handler&lt;/code&gt; and then have it executed by calling &lt;code&gt;eval&lt;/code&gt; on
    the string.  But I perferred a more direct method if one were available.  As it
    turned out, one was in fact available in the form of the &lt;code&gt;apply&lt;/code&gt; method
    on &lt;code&gt;Function&lt;/code&gt; objects.  Consider this code:
    &lt;/p&gt;

    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;var foo = function(s1, s2) {
    alert( s1 + " - " + s2 );
}&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p style="text-align:justify"&gt;
    There are a couple of ways you can invoke &lt;code&gt;foo&lt;/code&gt;.  You can call it as
    you normally would with functions or, alternatively, you can call the member method
    &lt;code&gt;apply&lt;/code&gt; that all function objects posses.  Here's an example:
    &lt;/p&gt;

    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;var foo = function(s1, s2) {
    alert( s1 + " - " + s2 );
}

foo("ding", 20);                 // call like normal function
foo.apply( null, ["ding", 20] ); // call via "apply" method&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p style="text-align:justify"&gt;
    The &lt;code&gt;apply&lt;/code&gt; method requires you to supply 2 parameters, the first one
    indicates the object in whose scope the function must be invoked - which means that
    the function will be invoked as though it were a member function of that object. The
    effect of this is that the variable "&lt;code&gt;this&lt;/code&gt;" within that function will refer
    to the object you pass as the first argument.  If you pass &lt;code&gt;null&lt;/code&gt; then it
    will execute like a global function.  Here's an example:
    &lt;/p&gt;

    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;var person = {
    name : "binga",
    age : 20
};

var print = function() {
    alert( this.name + " - " + this.age );
}

print.apply( person );&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p style="text-align:justify"&gt;
    From within the function &lt;code&gt;print&lt;/code&gt; here, the reference to "&lt;code&gt;this&lt;/code&gt;"
    turns out to refer the first parameter that you pass to &lt;code&gt;apply&lt;/code&gt;.  So what
    happens if you called &lt;code&gt;print&lt;/code&gt; like this?

    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;print.apply( null );&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p style="text-align:justify"&gt;
    As things tend to be in such cases, "&lt;code&gt;this&lt;/code&gt;" becomes "&lt;code&gt;undefined&lt;/code&gt;"
    from inside &lt;code&gt;print&lt;/code&gt;.
    &lt;/p&gt;
    
    &lt;p style="text-align:justify"&gt;
    The second parameter to &lt;code&gt;apply&lt;/code&gt; is of course, the array of parameters that
    are to be passed to the function.  So with this new information, &lt;code&gt;fireEvent&lt;/code&gt;
    looks like this:
    &lt;/p&gt;

    &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;function fireEvent(eventHandlers) {
    //
    // everything after the first argument must be
    // considered as parameters to be passed to the
    // event handler routines
    //
    var args = [];
    var i = 0;
    forEach(arguments, function( arg ) {
        if( i++ == 0 )
            return;
        args.push( arg );
    });

    //
    // iterate through the handlers collection and call one by one
    //
    forEach(eventHandlers, function(handler) {
        handler.apply(null, args);
    });
}&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p style="text-align:justify"&gt;
    Simple enough, when you know how to do it eh?!
    &lt;/p&gt;</content></entry></feed>