练习:迭代器方法链

In this exercise, you will need to find and use some of the provided methods in the Iterator trait to implement a complex calculation.

Copy the following code to https://play.rust-lang.org/ and make the tests pass. Use an iterator expression and collect the result to construct the return value.

  1. #![allow(unused)]
  2. fn main() {
  3. /// Calculate the differences between elements of `values` offset by `offset`,
  4. /// wrapping around from the end of `values` to the beginning.
  5. ///
  6. /// Element `n` of the result is `values[(n+offset)%len] - values[n]`.
  7. fn offset_differences<N>(offset: usize, values: Vec<N>) -> Vec<N>
  8. where
  9. N: Copy + std::ops::Sub<Output = N>,
  10. {
  11. unimplemented!()
  12. }
  13. #[test]
  14. fn test_offset_one() {
  15. assert_eq!(offset_differences(1, vec![1, 3, 5, 7]), vec![2, 2, 2, -6]);
  16. assert_eq!(offset_differences(1, vec![1, 3, 5]), vec![2, 2, -4]);
  17. assert_eq!(offset_differences(1, vec![1, 3]), vec![2, -2]);
  18. }
  19. #[test]
  20. fn test_larger_offsets() {
  21. assert_eq!(offset_differences(2, vec![1, 3, 5, 7]), vec![4, 4, -4, -4]);
  22. assert_eq!(offset_differences(3, vec![1, 3, 5, 7]), vec![6, -2, -2, -2]);
  23. assert_eq!(offset_differences(4, vec![1, 3, 5, 7]), vec![0, 0, 0, 0]);
  24. assert_eq!(offset_differences(5, vec![1, 3, 5, 7]), vec![2, 2, 2, -6]);
  25. }
  26. #[test]
  27. fn test_custom_type() {
  28. assert_eq!(
  29. offset_differences(1, vec![1.0, 11.0, 5.0, 0.0]),
  30. vec![10.0, -6.0, -5.0, 1.0]
  31. );
  32. }
  33. #[test]
  34. fn test_degenerate_cases() {
  35. assert_eq!(offset_differences(1, vec![0]), vec![0]);
  36. assert_eq!(offset_differences(1, vec![1]), vec![0]);
  37. let empty: Vec<i32> = vec![];
  38. assert_eq!(offset_differences(1, empty), vec![]);
  39. }
  40. }