The RangeBounds
trait offers a contains
method which... I am not much a fan of.
I typically favor not getting hung up on syntax, but I just find it hard to read:
!(0.0..=1.0).contains(&x)
In descending order of importance:
- Yoda notation: I need to reach the end of the expression to learn which variable is being concerned (
x
) when that's the most important part, really. - Blending: that
!
next to(
really blends in, making it harder to notice. - Noise: an extra set of parentheses (around the range) and an extra
&
, just boilerplate that needs to be skipped.
I was glad to learn with the 1.73 release that I am not the only one who is not a fan. Though I had no solution to offer.
/u/kibwen did, however, offer a fairly compelling alternative:
!x.within(0.0..=1.0)
This actually solves all the issues I had above, which I honestly didn't think was possible:
x
is first, immediately denoting which variable we're interested in.!
stands out quite a bit more.- No extra set of parentheses, no extra
&
.
And here I am, thinking that it would be a worthwhile addition to the PartialOrd
trait:
fn within<R>(&self, range: R) -> bool
where
// Somehow reproduce the bounds of RangeBounds::contains
R: RangeBounds<Rhs>,
Rhs: PartialOrd<Self>,
{
range.contains(self)
}
Pure syntactic sugar, really, yet oh so sweet.
Comparison of various syntaxes, side to side:
if scale < 0.0 || scale > 1.0
if scale < 0.0 || 1.0 < scale
if !(0.0 <= scale && scale <= 1.0)
if !RangeBounds::contains(0.0..=1.0, &scale)
if !(0.0..=1.0).contains(&scale)
if !scale.within(0.0..=1.0)