Skip to content

Instantly share code, notes, and snippets.

@sireliah
Last active October 23, 2020 07:26
Show Gist options
  • Select an option

  • Save sireliah/255ad7ff3ee5436b057637b7225f5017 to your computer and use it in GitHub Desktop.

Select an option

Save sireliah/255ad7ff3ee5436b057637b7225f5017 to your computer and use it in GitHub Desktop.
Rust version of Clojure condp apply expression
// (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