macro_rules! cartesian_array_map { ($([$($queue:expr),*]),*) => { ... }; ($([$($queue:expr),*]),*; $wrapper:expr) => { ... }; (@impl initial: $initial:tt; acc: [$(($($acc:tt)*))*]; current: []; queue: []; wrapper: ; ) => { ... }; (@impl initial: $initial:tt; acc: [$(($($acc:tt)*))*]; current: []; queue: []; wrapper: $wrapper:expr; ) => { ... }; (@impl initial: $initial:tt; acc: $acc:tt; current: []; queue: [$queue_head:tt $($queue_tail:tt)*]; wrapper: $($wrapper:expr)?; ) => { ... }; (@impl initial: [$(($($initial:tt)*))*]; acc: [$($acc:tt)*]; current: [$current_head:tt $($current_tail:tt)*]; queue: $queue:tt; wrapper: $($wrapper:expr)?; ) => { ... }; }
Expand description
Same as cartesian_array!
but mapping each element.
It is useful to use this macro instead of cartesian_array!
followed by a .map
because it avoids creating an intermediate array.
Also, .map
doesn’t work in const
scenarious, while cartesian_array_map!
does.
Example
Regular use
use cartesian_array_product::cartesian_array_map;
let mapped_product = cartesian_array_map!([1, 2], [3, 4]; |a, b| a + b);
let expected = [
1 + 3,
2 + 3,
1 + 4,
2 + 4,
];
assert_eq!(mapped_product, expected);
Const use
use cartesian_array_product::cartesian_array_map;
const fn sum(a: i32, b: i32) -> i32 {
a + b
}
const mapped_product: [i32; 4] = cartesian_array_map!([1, 2], [3, 4]; sum);
const expected: [i32; 4] = [
1 + 3,
2 + 3,
1 + 4,
2 + 4,
];
assert_eq!(mapped_product, expected);
Tip: You can use caf!
to create a const anonymous function
use cartesian_array_product::{cartesian_array_map, caf};
const mapped_product: [i32; 4] = cartesian_array_map!(
[1, 2], [3, 4];
caf!(|a: i32, b: i32| -> i32 { a + b })
);
const expected: [i32; 4] = [
1 + 3,
2 + 3,
1 + 4,
2 + 4,
];
assert_eq!(mapped_product, expected);