Table of Contents
1. Introduction
What are anonymous functions?
Anonymous functions are functions we can define in-line in our code, without giving that function a name. In C#, the LINQ framework allows us to use Lambda functions, and in JavaScript and with JQuery we see anonymous functions used a lot as the result of other functions completing, or a function passed around as a parameter to some other function.
This can be confusing to read without seeing it. In software development, I've usually used these in C# to sort through or search through data to get returned data based on some criteria - without having to write a totally new function. In JQuery, it's common to make a function as a "do this once this other function is done".
What is a lambda expression?
Lambda expressions are a way we can create a function inside another function, known as an anonymous function. These anonymous functions are meant to be utilized once - where they're added in the code - and therefore we don't need to formalize a whole function declaration and definition for its logic.
Lambda expressions are new to C++11, so this isn't supported if you're working with an older codebase later on.
Review 1. True or false: To create an anonymous function you need to write a function declaration in a .h file and a definition in a .cpp file.
○ True / ○ False
2. Anonymous functions in C++
The form of an Anonymous Function in C++ looks like this:
[CAPTURE_CLAUSE] (PARAMETER_LIST) -> RETURN_TYPE { FUNCTION_BODY };
So, for example, if you need to sum two numbers but only inside a specific scope:
Example: Creating an anonymous function, calling it, and storing the result
in the result variable
void SomeOtherFunction() { // ...things happen... int result = []( int a, int b ) { return a + b; }( 1, 2 ); // Now we can work with int result // ... the rest of the function ... }
2.1. The capture clause
The form of a lambda expression is:
[ capture clause ] (parameters) -> return-type
{
definition of method
}(arguments); // function call
In the Capture Clause we specify what information the anonymous function has access to:
[&]Capture all external variables by reference[=]Capture all external variables by value[a, &b]Capture "a" by value and "b" by reference[]Capture nothing
(Description from GeeksforGeeks)
"External variables" refers to the variables in scope where the anonymous function is created. For example, in the following code, the external variables would be the records vector and the city string:
vector<Records> RetrieveData( string city ) { vector<Records> records = GetFromDatabase(); // Can put lambda expression here return records; }
If you capture them by reference the anonymous function will be able to make direct modifications to them. If they're captured by value, then the variables are copied and can change inside the anonymous function but it won't affect the original versions.
Review 2. The capture clause…
- ○ Calls the anonymous function
- ○ Specifies what the data type of the return data from the anonymous function will be
- ○ Specifies which input parameters are expected to be passed in to the anonymous function
- ○ Specifies which in-scope variables will be available within the anonymous function
Review 3. Identify the capture clause in each of the following snippets.
Snippet 1:
[]() { // Function contents }();
- ○ External variables, by value
- ○ External variables, by-reference
- ○ No capture
Snippet 2:
[&]() { // Function contents }();
- ○ External variables, by value
- ○ External variables, by-reference
- ○ No capture
Snippet 3:
[=]() { // Function contents }();
- ○ External variables, by value
- ○ External variables, by-reference
- ○ No capture
2.2. Parameters and return type
You can specify parameters and a return type for an anonymous function, though they are not required. For example, we could turn this function:
int Sum( int a, int b ) { return a + b; }
And function call:
int result = Sum( 2, 4 );
Into a lambda expression like this:
int result = [] // Capture clause ( int a, int b ) -> int // Parameters and return type { return a + b; }( 2, 4 ); // Call function
This anonymous function is all one line of code, though I've separated it onto separate lines for readability. If you wanted, you could compress it to one line:
int result = [](int a, int b) -> int { return a + b; } (2, 4);
Review 4. Given this anonymous function:
int result = [] // Capture clause ( int a, int b ) -> int // Parameters and return type { return a + b; }( num1, num2 ); // Call function
- a. What are the input parameters?
- b. What are the arguments being passed in?
- c. What is the return type?
2.3. The function body
Beyond being anonymous (having no name), the anonymous function can handle the same behaviors as a normal function. Within the opening and closing curly braces { } are where the function's logic go.
int result = [] // Capture clause ( int a, int b ) -> int // Parameters and return type { return a + b; // Function body }( num1, num2 ); // Call function
2.4. Assigning an anonymous function to a variable
Remember that we can call an anonymous function immediately by putting () at the end (as well as any required arguments):
int doubleResult = []( int num ) { return 2 * num; }( 4 ); // Call function
But if we leave off the last (), the anonymous function itself will be callable via the variable value. Its creation will look like this:
auto doubler = []( int num ) { return 2 * num; };
Then the function can be called multiple times elseware:
auto double4 = doubler( 4 ); auto double20 = doubler( 20 );
But if the point of an anonymous function is to avoid writing a declaration and definition, why would we do this? Well, perhaps the function is needed multiple times, but only in this one context.
3. Anonymous functions by example
For these next examples, let's say we have a vector<Restaurant> all_data to
look through, and a string find_me as the search term. The anonymous
functions we define would be inside another function, so let's use a shell
function like this:
3.1. Empty capture
By doing an empty capture, denoted by empty square brackets [], this means
the internal (anonymous) function does not take any variables in the current
scope. In this case, it doesn't automatically gain access to all_data or
find_me. Instead, we have to specify input parameters as the
parameter list and At the end of the anonymous function specification is
the function call, where we have to pass in the arguments.
Empty capture - don't grab any in-scope variables:
// vector<Restaurant> all_data and // string find_me are in scope vector<Restaurant> matchedData = [] // Capture clause ( vector<Restaurant> restaurants, string city ) // Parameter list -> vector<Restaurant> // Return type { // Function body vector<Restaurant> matches; for ( auto& r : restaurants ) { if ( r.m_name == name ) { matches.push_back( r ); } } return matches; } ( all_data, find_me ); // Function call return matchedData; // The matched results will be returned here
3.2. Capture variables by-value within scope
In this case, we're capturing the variables within scope using the equal sign
within the square brackets, [=]. This means that we don't need to specify a
parameter list for any items that are in this scope. Likewise, at the
function call step, there is nothing in the parentheses - no arguments being
passed in this way.
Capture-by-value:
// vector<Restaurant> all_data and // string find_me are in scope vector<Restaurant> matchedData = [=] // Capture clause () // Parameter list -> vector<Restaurant> // Return type { // Function body vector<Restaurant> matches; for ( auto& r : restaurants ) { if ( r.m_name == name ) { matches.push_back( r ); } } return matches; } (); // Function call return matchedData; // The matched results will be returned here
3.3. Capture variables by-reference within scope
In this case, we're capturing the variables within scope using the ampersand
sign within the square brackets, [&]. This means that we don't need to
specify a parameter list for any items that are in this scope. Likewise, at
the function call step, there is nothing in the parentheses - no arguments
being passed in this way. Since the variables that are currently in scope will
be captured by-reference, you can make changes to those variables within
the function body.
Capture by-reference:
// vector<Restaurant> all_data and // string find_me are in scope vector<Restaurant> matchedData; [&] // Capture clause () // Parameter list -> void // Return type { // Function body for ( auto& r : restaurants ) { if ( r.m_name == name ) { matchedData.push_back( r ); } } } (); // Function call return matchedData; // The matched results will be returned here
Review 5. Given this function:
float Average( float a, float b, float c ) { return ( a + b + c ) / 3; }
Which of these represent an equivalent anonymous function?
○ Snippet 1:
[]( float a, float b, float c ) -> int { return ( a + b + c ) / 3; };
○ Snippet 2:
[]( float a, float b, float c ) -> float { return ( a + b + c ) / 3; };
○ Snippet 3:
[&]() -> float { return ( a + b + c ) / 3; };
Which anonymous function matches?
4. Condensing the anonymous functions
Usually these would be written out much more concisely to take up less space in the code. An example of how this might look in an actual codebase are:
More condensed form:
// Print out matches []( vector<Restaurant>& data, string search ) -> void { for ( auto& d : data ) { if ( d.name.find( search ) != string::npos ) { cout << d.name << endl; } file: } }( all_restaurants, search_term );