rustvariadic-functionsrust-itertools

Calling variadic function with iterator in Rust


A variadic function takes a variable number of arguments of same type. Macro function !product from Itertools package are one of those and I'd like to compute it with a vector of ranges.

Example usage of !product is following where each argument is a Range

use itertools::iproduct;

// Iterate over the coordinates of a 4 x 4 x 4 grid
// from (0, 0, 0), (0, 0, 1), .., (0, 1, 0), (0, 1, 1), .. etc until (3, 3, 3)
for (i, j, k) in iproduct!(0..4, 0..4, 0..4) {
    // ..
}

How can I call iproduct with an iterator or a vector where each element will become each argument into iproduct? For instance

use std::ops::Range;

let ranges : Vec<Range<i64>> = vec![
    Range {start: 5, end: 10}, 
    Range {start: 0, end: 10}, 
    Range {start: -2, end: 3}
];

// How to call here properly??
for (i, j, k) in iproduct!(ranges) {
    // ..
}

Side note: For instance in python, one would call the function using the star sign before the variable: product(*ranges).


Solution

  • I think you're looking for Itertools::multi_cartesian_product

    use itertools::Itertools;
    use std::ops::Range;
    
    fn main() {
        let ranges: Vec<Range<i64>> = vec![
            5..10,
            0..10,
            -2..3,
        ];
    
        // How to call here properly??
        for v in ranges.into_iter().multi_cartesian_product() {
            let i = v[0];
            let j = v[1];
            let k = v[2];
            // ..
        }
    }