Feb 22

Factorial in multiple languages

Languages that I like to dabble in:

Clojure

(defn fact [n]
  (apply * (range 2 (inc n))))

Scala

def fact(x: BigInt): BigInt = if (x == 0) 1 else x * fact(x - 1)

JavaScript

function fact(n) {
   return (n == 0) ? 1 : n * fact(n - 1);
}

Groovy

def fact(n) {
    (2..n).inject(1) { fact, i | fact * i }
}

Python / Jython

def fact(x): return (1 if x==0 else x * fact(x-1))

Ruby

def fact(n)
  (1 .. n).inject{|a, b| a*b}
end

Feb 22

What is the big deal about Twitter?

I’ve looked at Twitter in the past and just never got what the big deal was. I would try to read other people’s streams and it just seemed like a lot of noise.

Well, after seeing more and more people whose blogs I read start Twittering, I finally created my Twitter account. I figure that trying it out is the only way I’m ever going to get it. I doubt I’ll do much tweeting, but I’ll try following some others for now.

Feb 22

How to create objects in JavaScript

This post goes over the various methods of creating objects in JavaScript.

Objects in JavaScript are actually like associative arrays with a special dot notation making the syntax look more Java like. It is possible to use array notation to access members of an object.

anObject.aProperty = "Hello";
anObject.aFunction();
anObject["aProperty"] = "Hello";
anObject["aFunction"]();

Array notation is useful when the property or function name is derived programmatically at runtime.

The following sections detail different ways to create objects in JavaScript.

1. Start with Object

Object is the base class of all objects in JavaScript. Perhaps the quickest way to create an object in JavaScript is to create a new Object and add to it.

var person = new Object();
person.nameFirst = "John";
person.nameLast = "Doe";

person.speak = function() {
   alert("Hello, my name is " + this.nameFirst + " " + this.nameLast + ".");
}

person.speak();

In this example, a new Object is created with the variable person pointing to it. Next, properties nameFirst and nameLast are added. Finally, a speak function is added to the person object.

Note the use of this in the above (and following) examples to reference members of the current object. Runtime binding ties this to the current object.

2. Using JavaScript Object Notation

JSON is another way to accomplish the definition of the person object. The JSON method looks a little cleaner than our first approach of starting with Object and it visually groups the definition of the object’s properties and functions between curly braces.

var person = {
   nameFirst : "John",
   nameLast : "Doe",
   speak : function() {
      alert("Hello, my name is " + this.nameFirst + " " + this.nameLast + ".");
   }
};

person.speak();

JSON is often used to marshal data between objects in another language and JavaScript. Libraries are available in many languages that can serialize objects to and deserialize objects from JSON. Since the resulting JSON string is native JavaScript, it is very easy on the JavaScript side of the transaction to get objects this way.

3. Define a Class

With the previous two methods of object creation, we are defining object instances. The whole process has to be repeated for each additional object instance needed. Defining a class saves a lot of repetitive typing if multiple instances of a given class are needed.

function personClass() {
   this.speak = function() {
      alert("Hello, my name is " + this.nameFirst + " " + this.nameLast + ".");
   }
}

var person = new personClass()
person.nameFirst = "John";
person.nameLast = "Doe";
person.speak();

To define a class in JavaScript, start with a function definition. Functions are themselves objects in JavaScript. This function serves as the constructor for the class. After defining the class, use the new keyword to create object instances of that class.

In this example, each object instance is created with a speak function. The properties have been added after the class was created. The properties could have been put in the class definition and assigned via the constructor function like so:

function personClass(first, last) {
   this.nameFirst = first;
   this.nameLast = last;

   this.speak = function() {
      alert("Hello, my name is " + this.nameFirst + " " + this.nameLast + ".");
   }
}

var person = new personClass("John", "Doe");
person.speak();

4. Inheritance via Prototypes

The main problem with the first three methods of object creation is that each object instance has it’s own copy of the properties and function objects defined. This becomes memory wasteful as more objects get created.

There is a better way in JavaScript. A way in which we define all common properties and functions in one place and have every object of the same type reference them. This is done through an object’s prototype property. Every JavaScript object has a prototype property.

JavaScript implements inheritance with a prototype model instead of the classic method used in languages like Java or C++. The prototype property references another object that acts as the parent object during property and function lookups. So when a function is called on a JavaScript object, JavaScript will first look in that object for the definition of the function. If the function is not found, JavaScript proceeds to look in the prototype object for the definition. If the function is still not found, the prototype’s prototype is searched. This prototype chaining continues until either the object is found or the base of the prototype chain is reached. The value undefined is returned if the property or function being searched for is not found.

At the base of every prototype chain is JavaScript’s Object. This is how all objects get common functions like toString().

function personClass(first, last) {
   this.nameFirst = first;
   this.nameLast = last;
}

personClass.prototype.speak = function() {
   alert("Hello, my name is " + this.nameFirst + " " + this.nameLast + ".");
}

var person = new personClass("John", "Doe");
person.speak();

In this example, every object instance of personClass gets it’s own copy of the variable data nameFirst and nameLast and shares a common speak function.

The next example shows setting an objects prototype object explicitly.

/* Common base class */
function Dog() { }

Dog.prototype.barkSound = "woof! woof!";

Dog.prototype.bark = function() {
   alert(this.barkSound);
}

/* BigDog inherits from Dog */
function BigDog() { }
BigDog.prototype = new Dog();
BigDog.prototype.barkSound = "WOOF! WOOF!";

/* LittleDog also inherits from Dog */
function LittleDog() { }
LittleDog.prototype = new Dog();
LittleDog.prototype.barkSound = "yap! yap!";

/* Listening to the different types of dogs barking */
var mutt = new Dog();
mutt.bark();

var germanShephard = new BigDog();
germanShephard.bark();

var chihuahua = new LittleDog();
chihuahua.bark();

JavaScript objects can be modified dynamically at runtime. This includes prototype objects. Dynamically modifying a prototype object effectively modifies every instance associated to the prototype. It is also possible to modify the prototypes of built-in Javascript objects.

The choice of which object creation method to use depends largely on the situation. Using prototypes is overall the most flexible. JSON will probably be used for marshalling data between a client and server. The simpler methods are probably sufficient for quick transient objects.

This post just scratches the surface of what is possible with JavaScript. The dynamic nature of the language makes for some very flexible runtime constructs with objects.

Mar 11

Inform 7 IDE and xUnit testing

Today at work we were discussing unit testing and code coverage tools on .Net. I’ve worked with these tools before on both Java and .Net platforms. But the rehashing today made me draw some analogies to what I’m referring to as the Inform 7 IDE.

Inform is a design system for interactive fiction based on natural language. I started evaluating Inform this previous weekend as a possible platform to introduce my almost nine year old daughter to some form of programming on the computer. Here is what a simple Inform 7 program looks like (this example is from the Wikipedia entry for Inform):

“Hello World” by “I.F. Author”

The story headline is “An Interactive Example”.

The Living Room is a room. “A comfortably furnished living room.” The Kitchen is north of the Living Room. The Front Door is south of the Living Room. The Front Door is a closed locked door.

The insurance salesman is a man in the Living Room. The description is “An insurance salesman in a tacky polyester suit. He seems eager to speak to you.” Understand “man” as the insurance salesman.

A briefcase is carried by the insurance salesman. The description is “A slightly worn, black briefcase.” Understand “case” as the briefcase.

The insurance paperwork is in the briefcase. The description is “Page after page of small legalese.” Understand “papers” or “documents” or “forms” as the paperwork.

Instead of listening to the insurance salesman:
say “The salesman bores you with a discussion of life insurance policies. From his briefcase he pulls some paperwork which he hands to you.”;
now the player carries the insurance paperwork.

The Inform IDE keeps a history of the runs of the program. The current and previous runs are graphically depicted in a Skein panel. The skein graphically depicts the various runs through the program as threads that hang from knots with the start knot being the root. Any knot with multiple threads coming out of it represents different runs of the program. The current run is shown in a different color than previous runs.

Inform 7 Skein - click to enlarge

For the current run the Inform 7 IDE also has a Transcript panel that shows the program output and user interaction. This panel shows in two columns. The left column represents the actual output. The right column represents the expected or blessed output. If you ever rerun a thread and the actual output does not match the blessed output, those differences will be highlighted in both the Skein and Transcript panels.
Inform 7 Transcript - click to enlarge

Refer to the Skein tutorial in the Inform Manual for a more complete description of how the Skein and Transcript work.

To complete the analogy to unit testing in Java or .Net, the unit test is represented by the blessed transcript items. The test suite would be the collection of blessed transcript items across all skein threads.

I’m probably over simplifying the analogy and I’m just getting into Inform, so I really do not know the full extent of how the Skein and Transcript can be used. But on the surface, I think this comparison is kind of cool.

I don’t know yet if Inform will be the right thing to introduce my daughter to some form of programming on the computer. It does require less contextual information to get started than say Java, Python, Ruby, or Groovy. I also think she would get some enjoyment out of the interactive fiction part of it.

I’m also interested in Scala, but it suffers like the previous languages mentioned plus I’m not even sure I’m ready for the lambda calculus, existential types and closures. ;-)

Feb 07

Silverlight developer demo

Last night, I attended a developer demo of Microsoft’s Silverlight hosted at the monthly meeting of the North Dallas .Net Users Group. The presenter was Chris Koenig. Chris is Microsoft’s Developer Evangelist for this region. For the presentation, Chris showed some full blown Silverlight application demos and gave an overview of Silverlight before proceeding with a simpler demo where he dove into the code behind it all. Overall Silverlight and the demo looked fairly impressive.

Here are some of my takeaway notes from the meeting:

  • Microsoft is not calling Silverlight an Adobe Flash killer. However, it is obvious that like JavaFX it is intended to compete in this space. I suspect Microsoft doesn’t want Silverlight to be compared too harshly against Flash at it’s current product maturity level. The 2.0 version will be able to compare more directly to Flash. DevX.com has a comparison article of the three technologies where a stopwatch gadget is created in each. One of the neatest demos that Chris showed had a cityscape with a bouncing ball moving in front of the buildings from side to side. Half of the cityscape was done in Silverlight and the other half was done in Flash. This demo showcased the interoperability between the two as the bouncing ball appeared to seamlessly flow across the entire cityscape.
  • The streaming video capabilities of HD 720p support the current standards for HD-DVD and BluRay.
  • Microsoft offers a companion service for Silverlight streaming on Windows Live.
  • Silverlight is cross platform: Windows and OS/X.
  • Silverlight is cross browser with plugin support for Internet Explorer, Firefox, and Safari.
  • Silverlight is not available for Linux. However, some Silverlight content can be run on Linux using Moonlight. Moonlight is an open source implementation of the Silverlight runtime that is being developed by the Mono project.
  • Microsoft has put a lot of attention into tool support for Silverlight in Visual Studio 2008 and a new designer focused tool suite called Expression Blend.
  • Current language support is only Javascript. 2.0 will add the other .Net languages like C#, VB, Iron Ruby, etc.
  • In addition to additional language support, version 2.0 will bring more support for layouts, common business and data manipulation controls, and networking.

With the introductions of Silverlight and JavaFX, Adobe finally has some worthy competition in this space. I look forward to watching it play out.

Feb 05

Essential Mac Applications

Mac Tricks And Trips has an extensive list of essential applications for the Mac. I haven’t had my Mac long enough to accumulate this many applications. Some of the ones in the list that I have installed:

Looks like I have a lot more to try.

[Updated] Other applications that I have installed that are not on the  Mac Tricks And Trips list:

Apr 29

Simply del.icio.us

I’ve been using del.icio.us for bookmarking for a little over six months now. Since that time, I haven’t bookmarked anything new in any of the numerous browsers that I use throughout the day. No more scattered collections of bookmarks. I love it! Now I just need to work on the organization of my bookmarks.

I see a new feature over at del.icio.us called Your network. It allows del.icio.us users to track bookmarks that others are adding. I just started trying it out. Seems cool.

I’ve really liked the inbox feature for some time now. Your inbox is where you can track bookmarks being added with tags that you specify.

Checkout my bookmarks and add me to your network if you want.

Apr 26

Mapping Linux

A friend of mine recently pointed me to an interesting map of current Linux distributions. This got me thinking about my quest for Linux nirvana and all the distributions that I have tried over the years.

What I find important in a distribution has changed throughout the years. Initially Linux was just a hobby OS installed on spare hardware or a secondary partition. Then it started filling special needs. Like a dedicated combo router and firewall. Now I use it as one of my primary desktop OSes. I especially like Linux for most development stuff.

Criteria that is important to me now is getting a distribution to a completely useable state in a short amount of time. By completely useable I mean that I don’t have to install alot of extra stuff after the initial installation. I like having some support for things like Java, Flash and other browser plugins right out of the box. I have also come to prefer KDE.

Have I found the perfect distribution? Probably not, but here is a list of the ones that I have used or evaluated that are still active.

  • Red Hat – The last Red Hat I tried was in the pre-Fedora days. It was once my primary distribution and I used it as a dedicated router for a couple of years. I finally dropped it for Suse when I got a new PC that had hardware that required a newer kernel than Red Hat supported at the time.
  • SuSe – I really liked SuSe for a couple of years. I purchased two or three copies of the Professional package as new versions became available. YaST was a nice touch. I finally moved on after getting the feeling that it had become too bloated for my needs.
  • Slackware – Slackware eventually replaced SuSe as my preferred distribution. I used it as my primary distribution for a couple of years. Slackware is awesome and I still have a fondness for it. But I guess my criteria has changed over the years and it seems to lag behind some of the other popular distributions when it comes to things like kernel versions and package management.
  • Vector – Vector was based on Slackware with some nice extensions in installation and package management. It seemed really nice, but in the end probably too much like Slackware at a time when I decided to try something different. I think I’ve had some installation issues with the latest versions and my newest hardware — perhaps it is time for me to try Vector again.
  • Arch – Nice distribution with a cool package manager in Pacman.
  • Yoper – I’ve only taken a quick look at Yoper. It is a 686 optimized distribution.
  • SLAX – SLAX is a cool Live CD distribution based on Slackware. It was a life saver on a trip to Disney World a couple of years back. It booted nicely on a laptop I had brought along and provided hours of in-flight gaming entertainment for my daughter.
  • Mandriva – I tried this distribution back when it was still Mandrake. It had some nice features, but just never met my fancy for some reason.
  • PCLinuxOS – I was impressed with some of the soundcard detection PCLinuxOS did on a PC that seemed to give other distributions problems. Still though, too much Mandrake for my tastes.
  • Gentoo – The ideas seem cool and I’ve tried it once or twice. But I guess I’m just too impatient to invest as much time as seems to be required to get the OS to the state I want. Nonetheless, emerge and portage are really cool.
  • VLOS – VLOS is basically a nice packaging of a Gentoo stage 3 build. Nicely done but still more time that I want to invest these days.
  • Debian – Debian is the base of my current favorite distributions. I find Debian itsself to be too draconian in what it allows in the distribution proper for my tastes. All the Debian based distributions have excellent package management in Apt and Synaptic makes a nice GUI frontend to Apt.
  • Ubuntu – Very nice, Debian based with more uptodate stuff. Used it as my primary distribution for about one year. This was my first time to stick with Gnome for that long. In the end, it was probably Gnome that made me switch to something else.
  • Kubuntu – Ubuntu with KDE as the window manager. When I tried Kubuntu, it seemed to lag behind Ubuntu and didn’t seem to be getting the same kind of attention. Perhaps things have changed.
  • Knoppix – Knoppix has got to be the best Live CD that I have used so far. It has helped me recover data from dead MS Windows installations more times than I care to remember.
  • Mepis – My current favorite distribution is Mepis. Based on Debian with non-free stuff Debian will not include. I’ve had nothing but good experiences with it so far. It includes many things that other distributions require you to install after the initial installation. Things promise to get even better now that Mepis is switching to Ubuntu as a base. With KDE as the primary window manager, Mepis appears to be a better Kubuntu than Kubuntu.
  • FreeBSD – While not a Linux distribution, I’ve tried it numerous times and always enjoyed the experience. The ports package management system was the inspiration for Gentoo’s portage.

That said, I still have some spare partitions reserved for trying new or updated distributions. Read the rest of this entry »

Apr 23

Happy Birthday Gillian!

This is all happening way too fast! It seems just like yesterday that your Mom and I brought you home from the hospital.

Apr 22

It started with a question

It started simple enough. One weekend morning my then six year old daughter and I were making pancakes. She always helps with mixing the ingredients. She must have been thinking about growing up and what you do as a grownup when she asked, “Dad, what did you want to be when you were my age?” I thought for a second or two and told her that when I was her age I probably wanted to be an astronaut or fireman. She mulled that over for a little bit and then the question came. I should have been better prepared! With a little bit of confusion in her voice, she asked, “Dad, what did you grow up to be?” How do you make cube dwelling developer sound exciting to a six year old? Fortunately it didn’t take too long before she moved on to the next thing and a simple description sufficed.

But she had unknowingly planted a seed in my own thinking. I couldn’t even make what I do exciting to myself, much less anyone else. Guess I had become too complacent in doing just what is required to get by in my field. I had also been thinking about several articles over at The Pragmatic Programmers about staying competitive in our industry. Some of that advice includes being involved in the community at large. Doing things like blogging about the technologies that interest you.

So here I am now. Starting this blog. My intent is to blog about the things that interest me in the development world as a hobby and as a profession. Perhaps I’ll keep focused long enough to produce something useful for my own learning and for the community at large. It may not be as exciting as being an astronaut, but then again I’m not as much into travelling for work as I used to be.