Simplify expression

I have the following function:

impl Triangle {
    pub fn build<T>(sides: [T; 3]) -> Option<Triangle>
        T: PartialOrd + Copy + std::iter::Sum,
        if !sides
            .all(|x| *x < sides.iter().filter(|&y| !ptr::eq(x, y)).map(|&x| x).sum())
        //              ^PartialOrd                                ^Copy       ^Sum
            return None;
        // ...Snip...

Is it possible remove the portion .map(|&x| x) from the previous expression? It looks redundant.

You can use Iterator::copied.

Many types also support summing by reference, so with T: for<'a> Sum<&'a T> you don't need that map or copied at all.

When I remove the Copy trait and the map(..) portion, I got the following error from the compiler:

.all(|x| *x < sides.iter().filter(|&y| !ptr::eq(x, y)).sum())
                                                       ^^^ the trait `std::iter::Sum<&T>` is not implemented for `T`

Your Sum constraint would have to be updated for references like I showed. The trait is really Sum<A = Self>, where the A parameter can be any type that you want to sum, defaulting to the same as the result type.

1 Like

Oh my God, I have so much to learn ... Thank you.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.