An idiomatic way to sum up values in a multidimensional Array

Yesterday I played around a bit with a little programming exercise:

Calculate the sum of an array which contains integers and other arrays with integers.
For example: array_sum([1,2,[3,4,[5]]]) would return 15.

Here's my Python and PHP solutions:

Coming from dynamically typed languages it was surprisingly hard to wrap my head around a strongly typed solution.
I have an idea on how to solve this in Rust, although it might not be the most idiomatic.
Therefore I'd like to hear from you what would be a "Rustic" way to solve this problem.
Since I don't want to influence you in any way I will not post my solution just yet.
Bonus points if you can make your solution generic enough to also handle other collection types.

1 Like

Here's one option that makes use of IntoIterator:

fn main() {
    println!("{}", sum(vec![vec![1, 2], vec![3], vec![4, 5, 6]]));
}

fn sum<T, U, V>(i: U) -> T
    where T: Sum,
          U: IntoIterator<Item = V>,
          V: IntoIterator<Item = T>
{
    i.into_iter().flat_map(IntoIterator::into_iter).sum()
}

It consumes the parameter, but can probably make it work with an IntoIterator that returns references.

4 Likes

Oh wow! That looks pretty good. Thanks for that @vitalyd!

This one is pretty cool.