Repository navigation
Expand file tree
/
Copy path08_lambda_functional.candle
More file actions
535 lines (421 loc) · 11.5 KB
/
Copy path08_lambda_functional.candle
File metadata and controls
535 lines (421 loc) · 11.5 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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
/// Candle 语言 Lambda 和函数式编程模板
/// 展示 Lambda 表达式、闭包、高阶函数等特性
// ==================== Lambda 基础 ====================
/// Lambda 表达式(匿名函数)
void lambdaBasics() {
print("=== Lambda 基础 ===\n");
// 简单 Lambda
// (参数) => 表达式
// (int x) => x * 2
// 带代码块的 Lambda
// (int x) => {
// int result = x * 2;
// return result;
// }
print("Lambda 是匿名函数,可以赋值给变量或作为参数传递\n\n");
}
// ==================== Lambda 赋值给变量 ====================
void lambdaVariables() {
print("=== Lambda 赋值给变量 ===\n");
// 定义函数类型的变量(如果支持)
// Function<int, int> square = (int x) => x * x;
// int result = square(5);
// print("5 的平方: ");
// print(result);
// print("\n");
print("Lambda 可以赋值给函数类型变量\n\n");
}
// ==================== 高阶函数:接收函数作为参数 ====================
/// 对列表每个元素应用函数
List<int> mapList(List<int> items, int function(int item)) {
List<int> result = List<int>();
for (int item in items) {
result.add(function(item));
}
return result;
}
/// 过滤列表
List<int> filterList(List<int> items, bool predicate(int item)) {
List<int> result = List<int>();
for (int item in items) {
if (predicate(item)) {
result.add(item);
}
}
return result;
}
/// 累积计算(reduce)
int reduceList(List<int> items, int accumulator(int a, int b), int initial) {
int result = initial;
for (int item in items) {
result = accumulator(result, item);
}
return result;
}
void higherOrderFunctions() {
print("=== 高阶函数 ===\n");
List<int> numbers = List<int>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
// 定义辅助函数
int square(int x) {
return x * x;
}
bool isEven(int x) {
return x % 2 == 0;
}
int add(int a, int b) {
return a + b;
}
// Map: 对每个元素平方
List<int> squared = mapList(numbers, square);
print("Squared: ");
for (int num in squared) {
print(num);
print(" ");
}
print("\n");
// Filter: 过滤出偶数
List<int> evens = filterList(numbers, isEven);
print("Evens: ");
for (int num in evens) {
print(num);
print(" ");
}
print("\n");
// Reduce: 求和
int sum = reduceList(numbers, add, 0);
print("Sum: ");
print(sum);
print("\n\n");
}
// ==================== 闭包:捕获外部变量 ====================
void closureExample() {
print("=== 闭包示例 ===\n");
int multiplier = 10;
// 闭包捕获外部变量 multiplier
int multiply(int x) {
return x * multiplier;
}
print("5 * 10 = ");
print(multiply(5));
print("\n");
// 修改外部变量
multiplier = 20;
print("5 * 20 = ");
print(multiply(5));
print("\n\n");
}
// ==================== 闭包与可变捕获 ====================
void mutableClosure() {
print("=== 可变闭包 ===\n");
int counter = 0;
// 闭包修改外部变量
void increment() {
counter = counter + 1;
}
int getCounter() {
return counter;
}
increment();
increment();
increment();
print("Counter: ");
print(getCounter());
print("\n\n");
}
// ==================== 返回函数的函数 ====================
// 函数工厂:返回函数的函数
// Function<int, int> makeMultiplier(int factor) {
// return (int x) => x * factor;
// }
void functionFactory() {
print("=== 函数工厂 ===\n");
// Function<int, int> double = makeMultiplier(2);
// Function<int, int> triple = makeMultiplier(3);
// print("double(5) = ");
// print(double(5));
// print("\n");
// print("triple(5) = ");
// print(triple(5));
// print("\n");
print("函数可以返回其他函数\n\n");
}
// ==================== 柯里化(Currying)====================
void curryingExample() {
print("=== 柯里化 ===\n");
// 柯里化:将多参数函数转换为单参数函数链
// Function<int, Function<int, int>> curriedAdd =
// (int a) => (int b) => a + b;
// Function<int, int> add5 = curriedAdd(5);
// print("add5(10) = ");
// print(add5(10));
// print("\n");
print("柯里化将多参数函数转换为嵌套的单参数函数\n\n");
}
// ==================== 函数组合 ====================
void functionComposition() {
print("=== 函数组合 ===\n");
int addOne(int x) {
return x + 1;
}
int square(int x) {
return x * x;
}
// 函数组合:f(g(x))
int composed(int x) {
return square(addOne(x));
}
print("composed(5) = square(addOne(5)) = square(6) = ");
print(composed(5));
print("\n\n");
}
// ==================== 惰性求值(如果支持)====================
void lazyEvaluation() {
print("=== 惰性求值 ===\n");
// 惰性求值:延迟计算直到需要结果
// Lazy<int> lazyValue = () => {
// print("Computing...\n");
// return 42;
// };
// print("Before access\n");
// int value = lazyValue.value; // 此时才计算
// print("Value: ");
// print(value);
// print("\n");
print("惰性求值延迟计算直到需要结果\n\n");
}
// ==================== 递归 Lambda ====================
void recursiveLambda() {
print("=== 递归 Lambda ===\n");
// 定义递归函数
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
print("5! = ");
print(factorial(5));
print("\n");
// 斐波那契数列
int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
print("fibonacci(10) = ");
print(fibonacci(10));
print("\n\n");
}
// ==================== 实用函数式工具 ====================
class FunctionalUtils {
/// forEach: 对每个元素执行操作
static void forEach<T>(List<T> items, void action(T item)) {
for (T item in items) {
action(item);
}
}
/// any: 是否有元素满足条件
static bool any<T>(List<T> items, bool predicate(T item)) {
for (T item in items) {
if (predicate(item)) {
return true;
}
}
return false;
}
/// all: 是否所有元素满足条件
static bool all<T>(List<T> items, bool predicate(T item)) {
for (T item in items) {
if (!predicate(item)) {
return false;
}
}
return true;
}
/// find: 查找第一个满足条件的元素
static T? find<T>(List<T> items, bool predicate(T item)) {
for (T item in items) {
if (predicate(item)) {
return item;
}
}
return null;
}
/// take: 获取前 n 个元素
static List<T> take<T>(List<T> items, int n) {
List<T> result = List<T>();
int count = 0;
for (T item in items) {
if (count >= n) {
break;
}
result.add(item);
count = count + 1;
}
return result;
}
/// skip: 跳过前 n 个元素
static List<T> skip<T>(List<T> items, int n) {
List<T> result = List<T>();
int count = 0;
for (T item in items) {
if (count >= n) {
result.add(item);
}
count = count + 1;
}
return result;
}
}
void functionalUtils() {
print("=== 函数式工具 ===\n");
List<int> numbers = List<int>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
void printNum(int x) {
print(x);
print(" ");
}
bool isEven(int x) {
return x % 2 == 0;
}
bool greaterThanThree(int x) {
return x > 3;
}
// forEach
print("forEach: ");
FunctionalUtils.forEach<int>(numbers, printNum);
print("\n");
// any
print("Any even? ");
print(FunctionalUtils.any<int>(numbers, isEven));
print("\n");
// all
print("All > 3? ");
print(FunctionalUtils.all<int>(numbers, greaterThanThree));
print("\n");
// take
List<int> first3 = FunctionalUtils.take<int>(numbers, 3);
print("First 3: ");
FunctionalUtils.forEach<int>(first3, printNum);
print("\n");
// skip
List<int> afterFirst2 = FunctionalUtils.skip<int>(numbers, 2);
print("Skip 2: ");
FunctionalUtils.forEach<int>(afterFirst2, printNum);
print("\n\n");
}
// ==================== 综合示例:数据处理管道 ====================
void dataPipeline() {
print("=== 数据处理管道 ===\n");
// 原始数据
List<int> data = List<int>();
data.add(1);
data.add(2);
data.add(3);
data.add(4);
data.add(5);
data.add(6);
data.add(7);
data.add(8);
data.add(9);
data.add(10);
int square(int x) {
return x * x;
}
bool isEven(int x) {
return x % 2 == 0;
}
int add(int a, int b) {
return a + b;
}
// 处理管道:过滤偶数 -> 平方 -> 求和
List<int> evens = filterList(data, isEven);
List<int> squared = mapList(evens, square);
int sum = reduceList(squared, add, 0);
print("偶数平方和: ");
print(sum);
print("\n");
print("\n=== Lambda 和函数式编程演示完成 ===\n");
}
// ==================== 主函数 ====================
int main() {
print("=== Candle Lambda 和函数式编程演示 ===\n\n");
// 1. Lambda 基础
lambdaBasics();
// 2. Lambda 变量
lambdaVariables();
// 3. 高阶函数
higherOrderFunctions();
// 4. 闭包
closureExample();
// 5. 可变闭包
mutableClosure();
// 6. 函数工厂
functionFactory();
// 7. 柯里化
curryingExample();
// 8. 函数组合
functionComposition();
// 9. 惰性求值
lazyEvaluation();
// 10. 递归 Lambda
recursiveLambda();
// 11. 函数式工具
functionalUtils();
// 12. 数据处理管道
dataPipeline();
return 0;
}
// ==================== 函数式编程总结 ====================
/*
函数式编程核心概念:
1. Lambda 表达式(匿名函数)
- 语法: (参数) => 表达式
- 语法: (参数) => { 代码块 }
- 可以赋值给变量
- 可以作为参数传递
2. 高阶函数
- 接收函数作为参数
- 返回函数作为结果
- 常见模式: map, filter, reduce
3. 闭包
- Lambda 捕获外部变量
- 可以访问和修改外部作用域
- 创建有状态的函数
4. 不可变性
- 避免修改原始数据
- 创建新数据而非修改旧数据
- 函数无副作用(纯函数)
5. 函数组合
- 将小函数组合成大函数
- f(g(x)) 或 compose(f, g)
- 构建复杂逻辑的清晰方式
6. 常用函数式操作
- map: 转换每个元素
- filter: 过滤满足条件的元素
- reduce: 累积计算
- forEach: 遍历执行
- any/all: 检查条件
- find: 查找元素
7. 函数式编程优势
- 代码简洁清晰
- 易于测试和调试
- 支持并行计算
- 减少副作用和状态管理
8. 应用场景
- 数据转换和处理
- 集合操作
- 事件处理
- 异步编程
- 算法实现
*/