A lambda is an anonymous function. A closure is a function that carries its scope with it. My examples here will be in Python, but they should give you an idea of the appropriate mechanisms.
print map(lambda x: x + 3, (1, 2, 3))
def makeadd(num):
def add(val):
return val + num
return add
add3 = makeadd(3)
print add3(2)
A lambda is shown in the map()
call, and add3()
is a closure.
JavaScript:
js> function(x){ return x + 3 } // lambda
function (x) {
return x + 3;
}
js> makeadd = function(num) { return function(val){ return val + num } }
function (num) {
return function (val) {return val + num;};
}
js> add3 = makeadd(3) // closure
function (val) {
return val + num;
}
js> add3(2)
5