Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cartesian product match

I have two sets of incomplete types (i.e. struct names, missing generic parameters and lifetimes), and I need to have some code executed for each possible pair of combinations:

// these are my types
struct A<T> { ... }
struct B<'a, 'b, T> { ... }
struct C { ... }

struct X<T> { ... }
struct Y { ... }
struct W<'a> { ... }
struct Z<T, D> { ... }

// this is the code I need to generate
match (first_key, second_key) {
    ("a", "x") => { ... A ... X ... }
    ("a", "y") => { ... A ... Y ... }
    ("a", "w") => { ... A ... W ... }
    ("a", "z") => { ... A ... Z ... }
    ("b", "x") => { ... B ... X ... }
    ("b", "y") => { ... B ... Y ... }
    // ...
}

The structures of the first set (A, B, C) and the ones on the second set (X, Y, W, Z) have a generic parameter depending on each other (e.g. for the case ("a", "x"), the actual types that will be used are A<X> and X< A<X>::Color > ). For this reason I couldn't find any solution using generic functions or similar.

I believe that the problem could be easily solvable with a macro; something like:

macro_rules! my_code {
    ( $first_type:tt), $second_type:tt ) => {
        // ... $first_type ... $second_type ...
    }
}

product_match!( (first_key, second_key) {
    { "a" => A, "b" => B, "c" => C },
    { "x" => X, "y" => Y, "w" => W, "z" => Z }
} => my_code )

but I failed at implementing product_match after working for several hours on it already. I couldn't find any easy way to nest repetitions; I believe that the only solution is using macros to turn the lists of match cases into nested tuples of values, and then recurse over them, but I found this very difficult to implement.

Another option could be generating the code of that big match using a build script, but this solution sounds quite dirty.

Is there any easy solution to this problem that I missed? Is there any easy way to implement product_match!? How can I implement my logic?

like image 911
peoro Avatar asked Oct 17 '22 15:10

peoro


1 Answers

I think your idea of implementing a Cartesian product using macros is best.

I'm not quite sure what you want the match expression to be, so I've implemented a repeated function call instead. The macro plumbing should be much the same, however. Hopefully you can take it from here.

macro_rules! cp_inner {
    ($f: expr, $x: expr, [$($y: expr),*]) => {
        $($f($x, $y);)*
    }
}

macro_rules! cartesian_product {
    ($f: expr, [$($x: expr),*], $ys: tt) => {
        $(cp_inner!($f, $x, $ys);)*;
    }
}

fn print_pair(x: u32, y: &'static str) {
    println!("({}, {})", x, y);
}

pub fn main() {
    cartesian_product!(print_pair, [1, 2, 3], ["apple", "banana", "cherry"]);
}
like image 67
apt1002 Avatar answered Oct 20 '22 21:10

apt1002