What's everybody's opinion on using lambdas to do nested functions in C++? For example, instead of this:
static void prepare_eggs()
{
...
}
static void prepare_ham()
{
...
}
static void prepare_cheese()
{
...
}
static fry_ingredients()
{
...
}
void make_omlette()
{
prepare_eggs();
prepare_ham();
prepare_cheese();
fry_ingredients();
}
You do this:
void make_omlette()
{
auto prepare_eggs = [&]()
{
...
};
auto prepare_ham = [&]()
{
...
};
auto prepare_cheese = [&]()
{
...
};
auto fry_ingredients = [&]()
{
...
};
prepare_eggs();
prepare_ham();
prepare_cheese();
fry_ingredients();
}
Having come from the generation that learned how to code by using Pascal, nested functions make perfect sense to me. However, this usage seemed to confuse some of the less experienced developers in my group at work during a code review where I made use of lambdas in this way.
A lambda function inside a lambda function is called a nested lambda function. Python allows lambda nesting, i.e., you can create another lambda function inside a pre-existing lambda function. For nesting lambdas, you will need to define two lambda functions – an outer and an inner lambda function.
lambda functions assigned to variable names have no advantage over def functions. lambda functions can be difficult or impossible to pickle.
Use a Lambda when you need to access several services or do custom processing. As data flows through services, you use Lambdas to run custom code on that data stream. This is useful in a Kinesis Pipeline that's receiving data from things like IoT devices.
When mydoubler is called and passed with equal parameter to lambda,Lambda function will be automatically called. Lambda function are the function which are defined without a name . There for it is also called anonymous function. In this code, myfunc doesn't return anything and mydoubler is not defined.
I don't see anything wrong with nested functions per se. I use lambdas for nested functions, but only if it meets some conditions:
So in your example I would not use lambdas for reason number one.
Conceptually nested functions can be useful for the same reason why private methods in classes are useful. They enforce encapsulation and they make it easier to see the structure of the program. If a function is an implementation detail to some other function then why not make it explicitly so?
The biggest problem I see is with readability; it's more difficult to read code that has a lot of nesting and indenting. Also, people are not very comfortable with lambdas yet so resistance is expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With