Browse DevX
Sign up for e-mail newsletters from DevX


Creating Unnamed Functions with the Lambda Library-2 : Page 2




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Presenting the Problem
The term a "lambda expression" originates of the mathematical field of lambda calculus. To see what kind of problems a lambda expression can solve, consider the following invocation of the transform() algorithm originally presented in a previous 10-Minute Solution:

string s="hello"; transform(s.begin(), s.end(), s.begin(), toupper);

transform's fourth argument can be any callable entity, say a functor, a bound member function or a freestanding function. Now, suppose you want to apply a different type of transformation to the string—namely mask every character with an asterisk. You want to be able to write something like this:

transform(s.begin(), s.end(), s.begin(), ='*');

Of course, this code won't compile. Instead, you have to write a full-blown function first:

int toasterisk(int original_letter) { return '*'; } And call transform() like this: transform(s.begin(), s.end(), s.begin(), toasterisk);

Using for_each() instead of transform() for such a task seems more natural:

for_each(s.begin(), s.end(), toasterisk);

But still, the third argument must be the name of a function defined elsewhere in the program. This coding style, though inevitable, is artificial and unwieldy. In some cases, it also compromises encapsulation. Take a look at how to define an unnamed function on the call site using the lambda library.

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