My latest Scala-inspired Javascript library: pf.js
February 4th, 2010What is a function? While many use the words ‘method’ and ‘function’ interchangeably, more mathematically-inclined programmers make a distinction between functions and methods based on between you are guaranteed a return value. Scala is one programming language that makes a distinction between functions and methods (though it’s actually pretty easy to jump between the two). Great, just like plenty of other languages, nothing special here. Javascript functions are funny beasts. On one hand, they seem to be simple subroutines which can be passed arguments and can enclose variables – pretty standard methods in other words. However, regardless of whether you include return statements in a function, something is actually returned, undefined being returned if you hadn’t specified a return value. Hmm, so they’re kind of like mathematical methods except there’s no way to know without looking at a function’s source code whether the author failed to return a value for the input you gave it or actually did return something, the undefined object.
However, Scala also provides a middle ground with PartialFunctions. PartialFunctions are cool because they are only defined for specific inputs and you can check this. In addition, because they are defined for specific inputs, you can combine several PartialFunctions to create a new PartialFunction which is defined for the union of all the original PartialFunctions’ inputs. Wouldn’t it be cool if Javascript did that too? Well, now it can with pf.js. Enjoy.
December 7th, 2010 at 8:19 am
“more mathematically-inclined programmers make a distinction between functions and methods based on between you are guaranteed a return value”
Only those who confuse methods with procedures or subroutines and don’t grasp the basic attribute of methods: “In object-oriented programming, a method is a subroutine that is exclusively associated either with a class (in which case it is called a class method or a static method) or with an object (in which case it is an instance method).” [Wikipedia]
“However, regardless of whether you include return statements in a function, something is actually returned, undefined being returned if you hadn’t specified a return value.”
Perl does the same; Scala returns the value of the last statement, which often is ():Unit. There’s nothing at all “funny” about Javascript’s functions vis-a-vis any other expression-oriented language.
“PartialFunctions are cool”
All PartialFunction does is provide an interface (trait) for argument checking of functions with one argument.
December 7th, 2010 at 10:32 am
I stand corrected.