Trying to make a recursive flatten function

I’ve found a way that utilizes some clever type inference. Basically, it works as long as you know what item type you’re expecting.

// implementation of `deep_flatten()` omitted

fn i_want_i32s(i: impl Iterator<Item=i32>) {
    println!("got: {:?}", i.collect::<Vec<_>>());
}

fn main() {
    let x = vec![1,2,3].into_iter();
    let y = vec![vec![],vec![1,2],vec![3,4]].into_iter();
    let z = vec![vec![],vec![vec![1],vec![2,3]],vec![vec![4,5,6],vec![7]]].into_iter();
    i_want_i32s(x.deep_flatten());
    i_want_i32s(y.deep_flatten());
    i_want_i32s(z.deep_flatten());
}

Output:

got: [1, 2, 3]
got: [1, 2, 3, 4]
got: [1, 2, 3, 4, 5, 6, 7]

(click here to see the implementation)

@nop_thread you might be interested in this as well.

14 Likes