Version 8 of lambda

Updated 2004-04-22 08:35:48

Richard Suchenwirth 2002-02-14 - Lambda is the name for the letter "L" in the Greek alphabet. Since Alonzo Church's "Lambda calculus", it is also the term for anonymous functions. Consider

 f(x) = x+1

is not much different from

 g(x) = x+1

except for the f/g difference, which are both arbitrary names. The common essence of the above functions, ignoring the name, is just

 (x) = x+1

or in other words, "given x, return x+1". In Tcl, this looks like

 lambda x {expr {$x+1}}

and it's easy to implement - see Lambda in Tcl.

To have lambdas directly, one change to Tcl would be:

  • If a command name is a list of length three, with lambda as first element, bind its arguments to the second element of the list, and then evaluate the third element in that scope.

As long as we don't have this, a simple way is to make up a name for a proc:

 proc lambda {argl body} {
    set name [info level 0]
    proc $name $argl $body
    set name
 }

where the lambda definition is returned as command name.

A more functional programming way would be, using the K combinator:

 proc lambda {argl body} {K [info level 0] [proc [info level 0] $argl $body]}
 proc K {a b} {set a}

See also RPN again for "half-lambdas": only the body is the value of a function, arguments are popped from the stack, the result is pushed on the stack.


It seems like it would be pretty easy for unknown to do this automatically... RS: Yes. Good idea. Let unknown know. It would just miss the efficiency of C-coded Tcl, but with today's CPUs, that's less of a problem...


RS: While the term lambda was coined by Alonzo Church, the concept is older. I found one instance in "Funktion und Begriff", Gottlob Frege (1848-1925), Jena 1891, where he identifies functions by their Werteverlauf (value extension?), without naming them. Instead, he first puts a Greek vowel with "spiritus lenis" (looking like a superscript comma on top of the letter), and then the function "body" in parens. He then goes to show (translated to modern ASCII, and even (almost) Tcl :) that

 lambda e {expr $e**2 - 4*$e} == lambda a {expr $a * ($a - 4)}

In other words, that the two anonymous functions are identical. To prove this, one would have to iterate over all possible values of e and a (which, even with doubles, is finite, but might take a long time...)


SS: Also check Function as Values and TIP-187 [L1 ] that are both highly related to anonymous functions.


Category Concept | Arts and crafts of Tcl-Tk programming