Higher Order Functions

Rust provides Higher Order Functions (HOF). These are functions that take one or more functions and/or produce a more useful function. 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. // Declare accumulator variable
11. let mut acc = 0;
12. // Iterate: 0, 1, 2, ... to infinity
13. for n in 0.. {
14. // Square the number
15. let n_squared = n * n;

17. if n_squared >= upper {
18. // Break loop if exceeded the upper limit
19. break;
20. } else if is_odd(n_squared) {
21. // Accumulate value, if it's odd
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)                             // All natural numbers squared
30. .take_while(|&n_squared| n_squared < upper) // Below upper limit
31. .filter(|&n_squared| is_odd(n_squared))     // That are odd
32. .fold(0, |acc, n_squared| acc + n_squared); // Sum them
33. println!("functional style: {}", sum_of_squared_odd_numbers);
34. }

Option and Iterator implement their fair share of HOFs.