#iterator #macro #no-std

no-std cartesian

QOL macro that creates the cartesian product of multiple iterators

3 unstable releases

0.2.1 Mar 30, 2021
0.2.0 Mar 30, 2021
0.1.0 Mar 30, 2021

#2454 in Rust patterns

Download history 109/week @ 2024-07-21 137/week @ 2024-07-28 89/week @ 2024-08-04 114/week @ 2024-08-11 97/week @ 2024-08-18 105/week @ 2024-08-25 110/week @ 2024-09-01 174/week @ 2024-09-08 85/week @ 2024-09-15 225/week @ 2024-09-22 238/week @ 2024-09-29 2920/week @ 2024-10-06 6052/week @ 2024-10-13 7218/week @ 2024-10-20 5727/week @ 2024-10-27 5131/week @ 2024-11-03

24,443 downloads per month
Used in 2 crates (via rs2glsl-macros)

MIT license

6KB
71 lines

cartesian-rs

A macro for combining iterators to the cartesian product. Using the macro it is possible to write code compacter, and use less indention space.

Writing one for-loop and iterating through the cartesian product of multiple iterators is similar to nesting for loops, in each loop iterating through one of the iterators. However, the semantics of break is changed.

Example

let (m, n, p) = (3, 3, 1);

let mut id = vec![vec![0; n]; m];
for (i, j) in cartesian!(0..m, 0..n) {
    id[i][j] = (i == j) as u32;
}

let col_vec = vec![vec![1], vec![2], vec![4]];

let mut res = vec![vec![0; p]; m];

for (i, j, k) in cartesian!(0..m, 0..n, 0..p) {
    res[i][k] += id[i][j] * col_vec[j][k];
}

assert_eq!(col_vec, res);

License

This package is licensed under the MIT license.


lib.rs:

Provides a quality of life macro cartesian! to simplify certain loops.

The macro takes up to 26 iterators as arguments and creates the cartesian product iterator over all input iterators, kind of like nested for loops.

It behaves the same as nested for loops and brings the advantage of being more compact, and simplifies breaking and continuing.

Examples

use cartesian::*;

let mut volume_grid = vec![vec![vec![0; 10]; 10]; 10];
for (x, y, z) in cartesian!(0..10, 0..10, 0..10) {
    volume_grid[x][y][z] = x * y + z;
}
let (m, n, p) = (3, 3, 1);

let mut id = vec![vec![0; n]; m];
for (i, j) in cartesian!(0..m, 0..n) {
    id[i][j] = (i == j) as u32;
}

let col_vec = vec![vec![1], vec![2], vec![4]];

let mut res = vec![vec![0; p]; m];

for (i, j, k) in cartesian!(0..m, 0..n, 0..p) {
    res[i][k] += id[i][j] * col_vec[j][k];
}

assert_eq!(col_vec, res);

No runtime deps