Skip to content

Instantly share code, notes, and snippets.

@madwareru
Last active March 4, 2020 06:50
Show Gist options
  • Select an option

  • Save madwareru/f69183337b1a90926aa052b40af229c4 to your computer and use it in GitHub Desktop.

Select an option

Save madwareru/f69183337b1a90926aa052b40af229c4 to your computer and use it in GitHub Desktop.
macro_rules! make_ident_tup {
($i:ident) => {$i};
($i:ident, $($irest:ident),+) => {($i, make_ident_tup!($($irest),+))}
}
macro_rules! cross_join {
( $lhs:expr ) => { $lhs };
( $lhs:expr, $($rhss:expr),+) => {($lhs).flat_map(
|x| (cross_join! ($($rhss),+)).map( move |y| (x, y)))}
}
macro_rules! compre {
( $ex:expr;$($ids:ident),+ <- [$($start_ends:expr),+]) => {
cross_join! ($($start_ends),+).map(|make_ident_tup!($($ids),+)|{ $ex })
};
( $ex:expr; $($ids:ident),+ <- [$($start_ends:expr),+]; $filter_ex:expr ) => {
cross_join! ($($start_ends),+).filter_map(|make_ident_tup!($($ids),+)|{
if $filter_ex { Some($ex) } else { None } })
};
($key:expr => $ex:expr;$($ids:ident),+ <- [$($start_ends:expr),+]) => {
cross_join! ($($start_ends),+).map(|make_ident_tup!($($ids),+)|{ ($key, $ex) })
};
($key:expr => $ex:expr; $($ids:ident),+ <- [$($start_ends:expr),+]; $filter_ex:expr ) => {
cross_join! ($($start_ends),+).filter_map(|make_ident_tup!($($ids),+)|{
if $filter_ex { Some(($key, $ex)) } else { None } })
};
}
let simple = compre![x * 2; x <- [1..10]];
let in_circle = compre![
(x, y);
x, y <- [-10..=10, -10..=10];
x*x + y*y <= 64
];
let triples = compre![
(x, y, z);
x, y, z <- [-30..=30, -30..=30, -30..=30];
x*x + y*y == z*z
];
let infinite_quatros = compre! {
(x, y, z, w);
x, y, z, w <- [0.., 0.., 0.., 0..];
x*x + y*y + z*z == w*w
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment