Last active
October 23, 2020 07:26
-
-
Save sireliah/255ad7ff3ee5436b057637b7225f5017 to your computer and use it in GitHub Desktop.
Rust version of Clojure condp apply expression
This file contains hidden or 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
| // (condp apply [2 3] | |
| // = "eq" | |
| // < "lt" | |
| // > "gt") | |
| // ;;=> "lt" | |
| macro_rules! condp_apply { | |
| ( $input:tt, {$($func:tt: $r:tt),*} ) => { | |
| { | |
| let mut result: &str = "other"; | |
| $( | |
| if $func($input) { | |
| result = $r; | |
| } | |
| )* | |
| result | |
| } | |
| }; | |
| } | |
| fn fun_a(value: &str) -> bool { | |
| value == "A" | |
| } | |
| fn fun_b(value: &str) -> bool { | |
| value == "B" | |
| } | |
| fn main() { | |
| let input = "A"; | |
| let result: &str = condp_apply!( | |
| input, | |
| { | |
| fun_a: "A", | |
| fun_b: "B", | |
| fun_b: "V", | |
| fun_b: "C" | |
| } | |
| ); | |
| println!("{:?}", result); | |
| } | |
| #[cfg(test)] | |
| mod tests { | |
| use super::*; | |
| #[test] | |
| fn test_apply_a() { | |
| let result: &str = condp_apply!( | |
| "A", | |
| { | |
| fun_a: "A", | |
| fun_b: "B" | |
| }); | |
| assert_eq!(result, "A"); | |
| } | |
| #[test] | |
| fn test_apply_other() { | |
| let result: &str = condp_apply!( | |
| "Z", | |
| { | |
| fun_a: "A", | |
| fun_b: "B" | |
| }); | |
| assert_eq!(result, "other"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment