Last active
September 7, 2018 08:20
-
-
Save d-plaindoux/38fd6c3c6ee27214408500c542707c9b to your computer and use it in GitHub Desktop.
Simple comprehension macro in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_export] | |
macro_rules! comprehension { | |
(($expr:expr) | $id:ident <- ($range:expr) if $cond:expr) => {{ | |
let mut result = Vec::default(); | |
for $id in $range { | |
if $cond { | |
result.push($expr); | |
} | |
} | |
result | |
}}; | |
(($expr:expr) | $id:ident <- ($range:expr)) => {{ | |
comprehension![ ($expr) | $id <- ($range) if true ] | |
}} | |
} | |
// Test | |
#[test] | |
fn it_apply_comprehension() { | |
let result = comprehension![ (x+1) | x <- (1..=2) ]; | |
assert_eq!(vec![2,3], result); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Better, I have reversed
if
construction logicIt prevents warning about unused variable when no condition is provided.