Skip to content

Instantly share code, notes, and snippets.

@Mr-Byte
Last active August 29, 2015 14:18
Show Gist options
  • Save Mr-Byte/d6950fb107368faa05fc to your computer and use it in GitHub Desktop.
Save Mr-Byte/d6950fb107368faa05fc to your computer and use it in GitHub Desktop.
macro_rules! query {
($($tokens:tt)*) => {
query_from!($($tokens)*)
};
}
macro_rules! query_from {
(from $context:pat => $source:expr, $($remainder:tt)+) => {
query_from!($source, $context => $($remainder)+)
};
($source:expr, $context:pat => from $newContext:pat => $newSource:expr, $($remainder:tt)+) => {{
let source = $source.flat_map(|value| { let $context = value; $newSource });
query_from!(source, $newContext => $($remainder)+)
}};
($($tokens:tt)*) => {
query_operator!($($tokens)*)
};
}
macro_rules! query_operator {
($source:expr, $context:pat => where $filter:expr, $($remainder:tt)+) => {
{
let source = $source.filter(|&$context| { $filter });
query!(source, $context => $($remainder)+)
}
};
($source:expr, $context:pat => let $newContext:pat = $letValue:expr, $($remainder:tt)+) => {
{
let source = $source.map(|value| { let $context = value; (value, $letValue) });
query!(source, ($context, $newContext) => $($remainder)+)
}
};
($source:expr, $context:pat => from $($remainder:tt)+) => {
{
query_from!($source, $context => from $($remainder)+)
}
};
($($tokens:tt)*) => {
query_end!($($tokens)*)
};
}
macro_rules! query_end {
($source:expr, $context:pat => select $selector:expr) => {
$source.map(|$context| { $selector })
};
}
fn main() {
let xs = vec! [vec! [ vec! [1,2]], vec! [ vec! [3,4], vec! [5,6,7]]];
let ys = query! { from ys => xs.iter(),
where ys.len() > 1,
from zs => ys.iter(),
from z => zs.clone().into_iter(),
where z > 2,
select z };
for y in ys {
println!("{}", y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment