A Prototype Factorial
Posted: May 28th, 2007 | Author: admin | Filed under: Computer Science, Programming Languages | No Comments »So I’ve been a fan of prototype based programming since I first came across SELF a few years ago. I was talking to duncan over the weekend about various OO/PL type things and we realized that neither of us had seen factorial, the standard functional programming demo, implemented in a prototype langauge. This being the case, I set out to rectify it.
Here is an implementation in Javascript (tested in firefox)
Number.prototype.factorial = function ()
{
if (this == 1)
return 1;
return this * (new Number (this -1)).factorial ();
};
//Test
myNum = new Number (10);
alert (\"Factorial of \" +myNum +\": \" +myNum.factorial ());
So you can see it’s not that bad, but its not as good as it could be.
Now the following code DOESN’T WORK. This is how I wish I could program it.
NaturalNumber.prototype.factorial = function () {return this * (this -1).factorial()};
0.factorial = function () { return 1; }
Now this code leverages the power of a prototype based language. This code doesn’t work since JavaScripts doens’t treat literal #’s (1, 42, 1337, etc) as instances of the Number object, and doesn’t define a collection of natural #’s.
It defines a factorial function for every Natural # (integers >= 0). We have one special case 0, 0! = 1.