Tsallaka zuwa abun ciki
Justice Tech School

Lambdas and Recursion

A lambda is an unnamed function: [capture](parameters) { body }. The capture list chooses which outside variables it may use. Recursion calls a function from itself and needs a base case.

Example
auto square = [](int x) { return x * x; };
cout << square(6) << endl;
int factor = 3;
auto times = [factor](int x) { return x * factor; };
cout << times(5) << endl;
vector<int> v = {1, 2, 3, 4};
transform(v.begin(), v.end(), v.begin(), [](int x) { return x + 1; });
for (int x : v) cout << x << " ";
cout << endl;

Result

36
15
2 3 4 5 

Exercise

Start a lambda with its capture list.

auto f = () { return 1; };

Quiz Test

What does the capture list [factor] do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.