wrq
June 30, 2018, 3:36pm
1
So in theory, sum_of_n will produce a Vec where each item is the gaussian sum up to that point. I'm starting from 1 just for clarity.
So,
[gauss(1), gauss(2), gauss(3), gauss(4)] etc
[1, 3, 6, 10] etc
It seems like res is never getting those values pushed, because I don't see anything printing...?
I'm not a rust expert, so maybe I am glossing over an important detail here.
There is something printed:
()
Rust functions have to declare their return type. If nothing is specified, a function returns the empty tuple, also known as the unit type : ()
. Re-read the chapter on functions to refresh your knowledge.
fn sum_of_n(n: i32) -> Vec<i32> {
// -> Vec<i32> // should be [gauss(1), gauss(2), gauss(3) etc]
let mut res = Vec::new();
for i in 1..6 {
res.push(gauss(i));
}
res
}
I'd write this with more iterators, however:
fn sum_of_n(n: i32) -> Vec<i32> {
(1..6).map(gauss).collect()
}
The recursive implementation seems inefficient, however, so a rewrite might look like:
fn sum_of_n(n: i32) -> Vec<i32> {
let mut sum = 0;
(1..6).map(|i| {
sum += i;
sum
}).collect()
}
wrq
June 30, 2018, 3:45pm
3
Ah, I see. Wonderful, thank you so much.
I will reread that chapter right now.
Hyeonu
June 30, 2018, 6:09pm
4
Aaand this?
fn sum_of_n(n: i32) -> Vec<i32> {
(1..6).scan(0, |sum, i| { *sum += i; *sum }).collect()
}
wrq
June 30, 2018, 6:47pm
5
Yes! Great!
I ended up doing something similar with map.
Afk now, will update this post later with code for posterity.