Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Lambda Functions Are Ready for Prime Time

Experts predict that 2009 will be the year of the functional programming paradigm. The revised and enhanced C++0x lambda expressions syntax provides you with exactly the right tools for painless functional programming. Learn how lambda expressions can boost your code and eliminate tedious manual coding.




Full Text Search: The Key to Better Natural Language Queries for NoSQL in Node.js

our years ago, I presented a pioneer proposal for adding lambda expressions to standards C++. The lambda proposal has since undergone significant revisions and enhancements. In their new form, C++0x lambda expressions and closures enable you to write unnamed function definitions at the place of call in a concise and convenient manner. The following sections will present the new syntax of C++0x lambda expressions.

You need a nameless function defined at the place of call. In C++03, the only way to do that is to define a function object manually. Alas, this is tedious and not well-suited for creating a one-time function object used "on the fly."

Use the new C++0x lambda function syntax to create a nameless local function conveniently.

Presenting The Problem

Suppose you want to find the first employee whose salary is within a specified range from a sequence of employees. The find_if algorithm comes in handy:

double min_salary=1000; std::find_if(emps.begin(), emps.end(), within(min_salary, 1.5*min_salary));

Your attention is drawn to the third argument of find_if which is a function object of type within. Defining this class is laborious, as the following code demonstrates:

class within { double low, high; public: within(double l, double h) : low(l), high(h) { } bool operator()(const employee& emp) { return emp.salary() >= low && emp.salary() < high; } };

Although within is used only once, there's no escape from writing this full-blown class with its data members, constructor, overloaded operator() and finally, instantiating it in the argument list of the find_if call above. You certainly don't want to repeat this tedium every time you use an algorithm! Why not let the compiler generate the code for the function class automatically? That's exactly what lambda expressions are all about.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date