I've started learning Rust a couple of days ago, so, please bear with me.
I wanted to write a recursive function to calculate a Fibonacci number:
use std::collections::VecDeque;
use tailcall::tailcall;
#[tailcall]
fn fib(n: i32) -> i32 {
fn fib_aux(x: i32, series: VecDeque<i32>, sum: i32, counter: i32) -> i32 {
match x {
0 => 0,
1 => 1,
counter => sum,
_ => fib_aux(
x,
series.push_front(sum),
sum + series[0],
counter + 1,
),
}
}
fib_aux(n, VecDeque::from([1]), 1, 2)
}
But when I compile it I get the following message:
Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
--> src/lib.rs:14:17
|
14 | series.push_front(sum),
| ^^^^^^^^^^^^^^^^^^^^^^ expected struct `VecDeque`, found `()`
|
= note: expected struct `VecDeque<i32>`
found unit type `()`
note: method `push_front` modifies its receiver in-place
--> src/lib.rs:14:24
|
14 | series.push_front(sum),
| ------ ^^^^^^^^^^ this call modifies `series` in-place
| |
| you probably want to use this value after calling the method...
= note: ...instead of the `()` output of method `push_front`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error
Looking at the docs I see that push_front
method doesn't return a new VecDeque
, but it's just a procedure.
So, my question is, I could pass a new VecDeque
with the value sum
pre-pended to the original one?