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. }
  4. fn main() {
  5. println!("Find the sum of all the squared odd numbers under 1000");
  6. let upper = 1000;
  7. // Imperative approach
  8. // Declare accumulator variable
  9. let mut acc = 0;
  10. // Iterate: 0, 1, 2, ... to infinity
  11. for n in 0.. {
  12. // Square the number
  13. let n_squared = n * n;
  14. if n_squared >= upper {
  15. // Break loop if exceeded the upper limit
  16. break;
  17. } else if is_odd(n_squared) {
  18. // Accumulate value, if it's odd
  19. acc += n_squared;
  20. }
  21. }
  22. println!("imperative style: {}", acc);
  23. // Functional approach
  24. let sum_of_squared_odd_numbers: u32 =
  25. (0..).map(|n| n * n) // All natural numbers squared
  26. .take_while(|&n_squared| n_squared < upper) // Below upper limit
  27. .filter(|&n_squared| is_odd(n_squared)) // That are odd
  28. .fold(0, |acc, n_squared| acc + n_squared); // Sum them
  29. println!("functional style: {}", sum_of_squared_odd_numbers);
  30. }

Option
and
Iterator
implement their fair share of HOFs.