I encountered an issue while trying to use the reduce()
method in Rust to calculate the sum of perimeters of squares. The problem is based on a drawing where there are n + 1
squares arranged with side lengths following the Fibonacci sequence. For example, if n = 5
, the side lengths of the squares are [1, 1, 2, 3, 5, 8]. The task is to find the sum of the perimeters of these squares.
Initially, I implemented the code using the fold()
method, and it worked correctly. Here's the code snippet that uses fold()
:
fn perimeter(n: u64) -> u64 {
let mut fib = vec![1, 1];
for i in 2..=n as usize {
fib.push(fib[i - 1] + fib[i - 2]);
}
// Calculate the sum of the perimeters using the fold method
fib.iter().fold(0, |acc, val| acc + val * 4)
}
However, when I tried to refactor the code to use the reduce()
method, it failed to compile. I modified the code as follows:
fn perimeter(n: u64) -> u64 {
let mut fib = vec![1, 1];
for i in 2..=n as usize {
fib.push(fib[i - 1] + fib[i - 2]);
}
// Calculate the sum of the perimeters using the reduce method
fib.iter().reduce(|acc, val| acc + val * 4).unwrap()
}
When using the reduce() method, I encountered the following error message:
error[E0308]: mismatched types
--> src/lib.rs:8:34
|
8 | fib.iter().reduce(|acc, val| acc + val * 4).unwrap()
| ^^^^^^^^^^^^^
| |
| expected `&{integer}`, found integer
| help: consider borrowing here: `&(acc + val * 4)`
I have read the Rust documentation for reduce()
and found an example where it works correctly. Here's the example from the documentation:
let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap();
assert_eq!(reduced, 45);
// Which is equivalent to doing it with `fold`:
let folded: i32 = (1..10).fold(0, |acc, e| acc + e);
assert_eq!(reduced, folded);
I expected the code to compile successfully and produce the same result as the fold()
implementation. However, the error message suggests a mismatched type issue with the reduce()
method.
I would appreciate any insights or suggestions on how to resolve this issue and successfully use the reduce()
method to calculate the sum of perimeters of the squares. Alternatively, if there is a reason why reduce()
cannot be used in this scenario, I would like to understand it.
Thank you in advance for your help!