What is lambda expressions?

In essence, a lambda expression is an anonymous function, which can be used in a context where a regular named function could be used, but where the function in question exists for a single purpose and thus should not be given a name (to avoid using up the namespace). They are most often used as a function argument for a higher-order function (that is, a function that operates on other functions, either by taking a function as a parameter or by returning a function as a value, or both). For example (in pseudo-code), if you have a function map() which applies a function to every element of a list or array,

map(increment, [1, 2, 3, 4, 5]) -> [2, 3, 4, 5, 6]

then you could have a lambda expression that squares its argument like so:

map(lambda(x) { return x * x }, [1, 2, 3, 4, 5]) -> [1, 4, 9, 16, 25]

This is exactly how the map() function in many functional languages works, in fact. To give the above example in Scheme,

(map (lambda (x) 
        (* x x))
     '(1 2 3 4 5))  

or in Haskell (if I am recalling it right):

map (\x -> x * x) [1, 2, 3, 4, 5]

(I am deliberately not giving you an example in C#, as that would be too close to doing your homework for you.)

The name comes from the lambda calculus, a model of mathematics which is built up from anonymous recursive expressions (in the mathematical sense).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.