Document become
keyword by WaffleLapkin · Pull Request #113095 · rust-lang/rust (original) (raw)
I don't think you would write fib_rec like that, specifically because it re-does a lot of work.
Yes, the more comparable solution was indeed the fib_iter
to start with.
Also just a nitpick: become in fib_tail won't compile since the signatures don't match :')
Good catch!
So a fold like this could serve as an example?
pub fn fold<T, U>(init: T, mut f: impl FnMut(T, U) -> T, iter: impl IntoIterator<Item = U>) -> T { let mut iter = iter.into_iter(); match iter.next() { None => init, Some(item) => fold(f(init, item), f, iter), } }
I just tested it locally and with sufficiently large iterators it causes a stack overflow on my system whereas tail calls would prevent this by putting become
in front of the recursive fold
call. I tested the above fold with this little function:
#[test] fn test_fold() { let iterations = 100_000; let output = fold( String::new(), |mut s, n| { const HEX: [char; 16] = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', ]; s.push(HEX[n % HEX.len()]); s }, (0..).take(iterations), ); assert_eq!(output.len(), iterations); }