-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathExercises_02_Lambdas.cpp
More file actions
407 lines (329 loc) · 12.1 KB
/
Copy pathExercises_02_Lambdas.cpp
File metadata and controls
407 lines (329 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// =====================================================================================
// Exercises_02_Lambdas.cpp
// =====================================================================================
module;
#include <map> // module implementation too unstable
module modern_cpp_exercises:lambdas;
import std;
namespace Exercises_Lambdas {
namespace Exercise_01 {
static bool evenOrOdd(int val) {
if ((val % 2) == 0) {
std::cout << val << " is even." << std::endl;
return true;
}
else {
std::cout << val << " is odd." << std::endl;
return false;
}
}
struct EvenOrOdd
{
bool operator() (int val) const {
if ((val % 2) == 0) {
std::cout << val << " is even." << std::endl;
return true;
}
else {
std::cout << val << " is odd." << std::endl;
return false;
}
}
};
auto lambda = [](int val) -> bool {
if ((val % 2) == 0) {
std::cout << val << " is even." << std::endl;
return true;
}
else {
std::cout << val << " is odd." << std::endl;
return false;
}
};
static void testExercise_01a() {
// testing C-style function
int value = 14;
auto result = evenOrOdd(value);
std::cout
<< "evenOrOdd of " << value << ": "
<< std::boolalpha << result << std::endl;
// testing callable object
EvenOrOdd callableObj;
value = 15;
result = callableObj(value);
std::cout
<< "evenOrOdd of " << value << ": "
<< std::boolalpha << result << std::endl;
// testing lambda
value = 16;
result = lambda(value);
std::cout
<< "evenOrOdd of " << value << ": "
<< std::boolalpha << result << std::endl;
}
static void testExercise_01b() {
std::vector<int> values(20);
std::generate(
std::begin(values),
std::end(values),
[count = 1]() mutable { return count++; }
);
// function
std::for_each(
std::begin(values),
std::end(values),
evenOrOdd
);
// lambda
std::for_each(
std::begin(values),
std::end(values),
[] (int val) {
if ((val % 2) == 0) {
std::cout << val << " is even." << std::endl;
}
else {
std::cout << val << " is odd." << std::endl;
}
}
);
// callable object
std::for_each(
std::begin(values),
std::end(values),
EvenOrOdd{}
);
}
static void testExercise_01c() {
std::vector<int> values(20);
std::generate(
std::begin(values),
std::end(values),
[count = 1]() mutable { return count++; }
);
// 'divisor' defined within capture clause
std::for_each(
std::begin(values),
std::end(values),
[divisor = 3] (int val) {
if (!(val % divisor)) {
std::cout << val << " can be divided by " << divisor << std::endl;
}
else {
std::cout << val << " cannot be divided by " << divisor << std::endl;
}
}
);
std::cout << std::endl;
// or 'divisor' defined in outer context (scope)
int divisor = 5;
// capture context by value (reference & would work also)
std::for_each(
std::begin(values),
std::end(values),
[=] (int val) {
if (!(val % divisor)) {
std::cout << val << " can be divided by " << divisor << std::endl;
}
else {
std::cout << val << " cannot be divided by " << divisor << std::endl;
}
}
);
}
static void testExercise()
{
testExercise_01a();
testExercise_01b();
testExercise_01c();
}
}
namespace Exercise_02 {
static std::map<char, std::function<double(double, double)>> createCalculator() {
std::map<char, std::function<double(double, double)>> map;
map.insert(std::make_pair('+', [](double a, double b) { return a + b; }));
map.insert(std::make_pair('-', [](double a, double b) { return a - b; }));
map.insert(std::make_pair('*', [](double a, double b) { return a * b; }));
map.insert(std::make_pair('/', [](double a, double b) { return a / b; }));
return map;
}
// or more compact
static std::map<char, std::function<double(double, double)>> createCalculatorEx() {
std::map<char, std::function<double(double, double)>> map;
map['+'] = [](double a, double b) { return a + b; };
map['-'] = [](double a, double b) { return a - b; };
map['*'] = [](double a, double b) { return a * b; };
map['/'] = [](double a, double b) { return a / b; };
return map;
}
// or still more compact
static std::map<char, std::function<double(double, double)>> createCalculatorExEx()
{
return {
{ '+', [](double a, double b) {return a + b; } },
{ '-', [](double a, double b) {return a - b; } },
{ '*', [](double a, double b) {return a * b; } },
{ '/', [](double a, double b) {return a / b; } }
};
}
static void testExercise_02a() {
std::map<char, std::function<double(double, double)>> calculator = createCalculator();
double op1, op2;
char op;
std::cout << "Enter first Operand: ";
std::cin >> op1;
std::cout << "Enter second Operand: ";
std::cin >> op2;
std::cout << "Enter operation (+, -, *, /): ";
std::cin >> op;
// do the math
double result = calculator[op](op1, op2);
std::cout << "Result: " << op1 << ' ' << op << ' ' << op2 << " = " << result << '.' << std::endl;
};
static void testExercise_02b() {
std::map<char, std::function<double(double, double)>> calculator = createCalculator();
// do some math operations
std::cout << "1.5 + 2.7 = " << calculator['+'](1.5, 2.7) << std::endl;
std::cout << "1.5 - 2.7 = " << calculator['-'](1.5, 2.7) << std::endl;
std::cout << "1.5 * 2.7 = " << calculator['*'](1.5, 2.7) << std::endl;
std::cout << "1.5 / 2.7 = " << calculator['/'](1.5, 2.7) << std::endl;
// add a new operation
calculator.insert(std::make_pair('^', [](double a, double b) { return std::pow(a, b); }));
std::cout << "1.5 ^ 2.5 = " << calculator['^'](1.5, 2.5) << std::endl;
};
static void testExercise()
{
// testExercise_02a(); // needs console input
testExercise_02b();
}
}
namespace Exercise_03 {
static void testExercise_03a()
{
// Output:
// Variable: 1
// Variable: 2
// Variable: 3
// Variable: 1
// When the lambda is called, the lambda captures a copy of @variable.
// When the lambda increments @variable from 1 to 2 and 3, it increments its own copy, not the original value.
// But: The original value of @variable is preserved across calls to the lambda!
int variable{ 1 };
auto lambda{ [variable]() mutable {
std::cout << "Variable: " << variable << std::endl;
variable++;
}
};
// invoke lambda three times
lambda();
lambda();
lambda();
std::cout << "Variable: " << variable << std::endl << std::endl;
}
static void testExercise_03b()
{
// Output:
// 10
// 11
// 12
// 13
// 14
// 15
// 16
// 17
// 15
auto L = [val = 10]() mutable { std::cout << val++ << std::endl; };
L();
L();
L();
L();
L();
auto LC = L;
LC();
LC();
LC();
L();
}
static void testExercise_03c()
{
// Output:
// 1
// 2
// 2
// Rather than printing 1, 2, 3, the code prints 2 twice. When we created @otherCount as a copy of @count,
// we created a copy of @count in its current state. @counts i was 1, so @otherCounts i is 1 as well.
// Since @otherCount is a copy of @count, they each have their own @i.
int i{ };
// create a lambda named 'count'
auto count{ [i]() mutable { std::cout << ++i << std::endl; } };
// invoke lambda
count();
// create a copy of lambda 'count'
auto otherCount{ count };
// invoke both lambda 'count' and the copy
count();
otherCount();
std::cout << std::endl;
}
static void invoke(const std::function<void(void)>& fn)
{
fn();
}
static void testExercise_03d()
{
// Output:
// 1
// 1
// 1
// This exhibits the same problem as the prior example in a more obscure form:
// When std::function is created with a lambda,
// the std::function internally makes a copy of the lambda object.
// Thus, the call to fn() is actually being executed on the copy of our lambda, not the actual lambda.
// See also:
// https://stackoverflow.com/questions/23515058/creating-stdfunction-with-lambda-causes-superfluous-copying-of-the-lambda-obje
int i{ };
// increments and prints its local copy of @i
auto count{ [i]() mutable { std::cout << ++i << std::endl; } };
invoke(count);
invoke(count);
invoke(count);
std::cout << std::endl;
}
static void testExercise_03e()
{
// Output:
// 1
// 2
// 3
// See testExercise_03d - using 'std::function' instead of 'auto'
int i{ };
std::function<void(void)> count {
[i]() mutable {
std::cout << ++i << std::endl;
}
};
invoke(count);
invoke(count);
invoke(count);
std::cout << std::endl;
}
static void testExercise()
{
testExercise_03a();
testExercise_03b();
testExercise_03c();
testExercise_03d();
testExercise_03e();
}
}
}
void test_exercises_lambdas()
{
using namespace Exercises_Lambdas;
Exercise_01::testExercise();
Exercise_02::testExercise();
Exercise_03::testExercise();
}
// =====================================================================================
// End-of-File
// =====================================================================================