Friday, February 11, 2011

When is Lambda not a Lambda, Part 2: Replacing the Stubs

In the Ruby programming language, there is a construct called "lambda". In answer to the second part of the apprentice's question, it is called lambda because the developers wanted to give it an air of authenticity, by identifying the construct with the computational theory of lambda calculus.  The Ruby developers weren't the first to do this, and won't be the last, and are following in a tradition among computer scientists of borrowing popular labels from one another.

Not that I know enough about the internals to tell whether or not they are justified in their use of the term lambda. What I do know is this: that anonymity has nothing meaningful to do with the computational theory, nor anything really meaningful to add in practice. 

What makes lambda special, at least in Ruby, is not that it doesn't have a name. In fact, it does have an identity, otherwise Ruby couldn't pass references to a lambda around as function arguments. Ruby just hides whatever internal identity it maintains for a lambda from the user. Nor does it stop the user from assigning a lambda to a name. Anonymity is completely and utterly irrelevant to the purpose and utility of a lamba. 

Where anonymity really comes into play is in the concept of a block, which in Ruby is a syntactic sugar for what other languages might call an inline function.  

What makes lambda special is that the enclosing scope is bound to the lexical environment in which it is defined, and that it maintains a calling structure from which the "return" keyword will properly exit. This differentiates lambda from a method which has a scope defined by the object to which it is bound; and from a Proc, which doesn't impose a deeper return nesting... acting as it does as a reference to the otherwise anonymous { block } syntax. Oh, and lambda has the argument signature more strictly checked.

Apparently the implementation is all based off of the kernel Proc class. So Ruby's lambda isn't really much like its functional counterparts; like the "java" in "javascript", the name "lambda" is used more for affect than effect.  This is further highlighted by the name pollution, Y combinator gymnastics, and stack overflow surprises one gets into when attempting to use it recursively...  

On a side note, one has to give credit for the Ruby community for adding more functional language constructs. The reference implementation of Ruby 1.9 supports tail call optimization as an option. 

No comments: