0

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).

1

1 Answer 1

3

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];
        // ..
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, great! Thank you. Just by curiosity, do you know if there is a similar way as in python to call a function with variable number of arguments?
Rust does not have optional or variadic arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.