Search code examples
rustflatmap

Mysterious behavior from flat_map


The result of

println!("{:?}", (1..4).flat_map(|x| x*2..x*3).collect::<Vec<usize>>())

Is [2, 4, 5, 6, 7, 8], while I would expect [2,3,4,5,6,6,7,8,9,8,9,10,11,12].

Why do I get this result?


Solution

  • This has nothing to do with flat_map but with std::ops::Range, which is defined to be "inclusively below and exclusively above". That is, in a 1..4-range the highest value will be 3, not 4. What you are looking for is std::ops::RangeInclusive, which you'll have to use two times in your code:

    fn main() {
        // Notice that
        assert!(!(1..4).contains(&4));
        // but
        assert!((1..=4).contains(&4));
    
        assert_eq!(
            (1..=4).flat_map(|x| x * 2..=x * 3).collect::<Vec<usize>>(),
            vec![2, 3, 4, 5, 6, 6, 7, 8, 9, 8, 9, 10, 11, 12]
        )
    }