macro_rules! chain {
(@wrap [$($prev:tt)*] [$($cur:tt)+] < $next:tt $($rest:tt)*) => { ... };
(@wrap [$($prev:tt)*] [$($cur:tt)+] <= $next:tt $($rest:tt)*) => { ... };
(@wrap [$($prev:tt)*] [$($cur:tt)+] > $next:tt $($rest:tt)*) => { ... };
(@wrap [$($prev:tt)*] [$($cur:tt)+] >= $next:tt $($rest:tt)*) => { ... };
(@wrap [$($prev:tt)*] [$($cur:tt)+] == $next:tt $($rest:tt)*) => { ... };
(@wrap [$($prev:tt)*] [$($cur:tt)+] != $next:tt $($rest:tt)*) => { ... };
(@arg_err $op:tt) => { ... };
(@wrap [$($a:tt)*] [$($b:tt)*] < ) => { ... };
(@wrap [$($a:tt)*] [$($b:tt)*] <=) => { ... };
(@wrap [$($a:tt)*] [$($b:tt)*] > ) => { ... };
(@wrap [$($a:tt)*] [$($b:tt)*] >=) => { ... };
(@wrap [$($a:tt)*] [$($b:tt)*] ==) => { ... };
(@wrap [$($a:tt)*] [$($b:tt)*] !=) => { ... };
(@wrap [$($prev:tt)*] [$($cur:tt)+]) => { ... };
(@wrap [$($prev:tt)*] [$($cur:tt)+] $next:tt $($rest:tt)*) => { ... };
(@op $a:tt $op:tt $b:tt) => { ... };
(@op $a:tt $op:tt $b:tt $($rest:tt)+) => { ... };
(@op $($rest:tt)*) => { ... };
(< $($rest:tt)*) => { ... };
(<= $($rest:tt)*) => { ... };
(> $($rest:tt)*) => { ... };
(>= $($rest:tt)*) => { ... };
(== $($rest:tt)*) => { ... };
(!= $($rest:tt)*) => { ... };
($first:tt $($rest:tt)*) => { ... };
}
Succintly chain comparison operators like in Python and Julia.
chain!
allows you to write comparisons that need to be simultaneously true
more concisely. Instead of writing a < b && b < c
, you can just write
chain!(a < b < c)
. chain!
has the added benefit that each argument is
only evaluated once, rather than being evaluated for both the left and right
comparisons. Arguments are lazily evaluated from left to right so that any
arguments after the first failing comparison are not evaluated. chain!
supports the comparison operators <
, <=
, >
, >=
, ==
, !=
in any
order.
let x = 8;
if chain!(4 < x <= 10) {
assert!(true);
}
assert!(chain!(4 == 2 * 2 == 12 / 3));