Search code examples
rustfold

Rust: Folding a set of tuples


I'm working on a pet project and I've found myself with a HashSet of tuples. Specifically

HashSet<(String,generic_array::GenericArray<u8,generic_array::typenum::U32>, u64)>

I'd like to sum the u64 element and can do so with a for loop without issue:

for element in hashset{
        sum = sum+element.2;
    }

However, I've come across the fold function for sets and I've written:

let y = hashset.fold(0, |sum x| sum+x)

Which works, but I'm unclear on the syntax of the |sum x|. I can infer that I'm simply naming variables, but I don't understand how I would expand on this. Also how does fold know which element of the tuple to operate on?


Solution

  • You really should show a minimal, complete, and verifiable example.

    First, I'd suggest you read the Rust book. It is really good and will show you the basics of Rust, especially iterators, which seems to be your problem here.

    Also, the documentation of the fold function might help you a lot.

    I simplified your example from above, because I do not know about the generic_array::GenericArray<u8, generic_array::typenum::U32> type, so I removed it, assuming you want to summarize the u64 from the tuple:

    use std::collections::HashSet;
    
    #[allow(unused_variables)]
    fn main() {
        let values: HashSet<(String, u64)> = HashSet::new();
        let sum = values.iter().fold(0, |acc, x| acc + x.1);
    }
    

    The x.1 syntax accesses the second element (counting starts at zero) of the tuple. That'd be x.2 in your case, because you have three elements. The fold method takes an initial value (0 in my example`) and a closure.

    The closure in your example is not valid Rust code (it is missing the comma between the arguments) and it therefor won't compile. Go ahead and read how the Iterator::fold function works, you'll understand then how this works.