Thursday, September 23, 2010

LAMBDA EXPRESSIONS

Tip -  New Feature in VC10 - Lambdas

Details -  Simply put Lambda is an anonymous FUNCTOR (FUNCTOR  is explained in earlier post ).Many programming languages support the concept of an anonymous function. A lambda expression is a programming technique that is related to anonymous functions. An anonymous function is a function that has a body, but does not have a name. A lambda expression implicitly defines a function object class and constructs a function object of that class type. You can think of a lambda expression as an anonymous function that maintains state and that can access the variables that are available to the enclosing scope.Lambda expressions are flexible and can maintain state, just like function objects, and their compact syntax removes the need for a class definition, which function objects require. This is a new feature in Visual Studio 2010.

Example: ( See the sample implementation )

// 3rd Parameter is an lambda expression . 
// In earlier post we used a FUNCTOR as 3rd Parameter 
// [ ] is the lambda-introducer, which tells the compiler that a lambda expression is beginning.
 sort( v.begin(), v.end(),
             [ ](const string& left , const string& right)
                {          
                           return left.size() < right.size();
                  }
            );

Reference -
1. http://msdn.microsoft.com/en-us/library/dd293608.aspx
2. http://blogs.msdn.com/b/vcblog/archive/2008/10/28/lambdas-auto-and-static-assert-c-0x-features-in-vc10-part-1.aspx

Posted by - Vijesh Vijay

No comments:

Post a Comment