高阶函数

Rust 提供了高阶函数(Higher Order Function, HOF)。执行一个或多个函数来产生一个用处更大的函数。HOF 和惰性迭代器(lazy iterator)给 Rust 带来了函数式的风格(英文原文:HOFs and lazy iterators give Rust its functional flavor.)。

1. fn is_odd(n: u32) -> bool {
2. n % 2 == 1
3. }

5. fn main() {
6. println!("Find the sum of all the squared odd numbers under 1000");
7. let upper = 1000;

9. // 命令式方式(imperative approach)
10. // 声明累加器变量
11. let mut acc = 0;
12. // 重复:0,1, 2, ... 到无穷大
13. for n in 0.. {
14. // 数字的平方
15. let n_squared = n * n;

17. if n_squared >= upper {
18. // 若大于上限(upper limit)则退出循环
19. break;
20. } else if is_odd(n_squared) {
21. // 如果是奇数就累加值
22. acc += n_squared;
23. }
24. }
25. println!("imperative style: {}", acc);

27. // 函数式方式(functional approach)
28. let sum_of_squared_odd_numbers: u32 =
29. (0..).map(|n| n * n)             // 所有自然数的平方
30. .take_while(|&n| n < upper) // 小于上限
31. .filter(|&n| is_odd(n))     // 为奇数
32. .fold(0, |sum, i| sum + i); // 最后其后
33. println!("functional style: {}", sum_of_squared_odd_numbers);
34. }

Option 和 迭代器 实现了它们自己的高阶函数(英语原文:Option and Iterator implement their fair share of HOFs.)。