I’ve just created a trait + blanket implementation containing functions that apply a closure to a value given the value of a second parameter is true
. I’m sure someone must have done that better than me, already. Anybody know who / where? I found this hard to google:
// trait definition with default implementation
trait ApplyIf
where
Self: Sized + Clone,
{
fn apply_if(self, modifier: impl Fn(Self) -> Self, condition: bool) -> Self {
if condition {
modifier(self)
} else {
self
}
}
fn cloned_apply_if(self: &Self, modifier: impl Fn(&Self) -> Self, condition: bool) -> Self {
if condition {
modifier(self)
} else {
self.clone()
}
}
}
// blanket implementation
impl<T: Sized + Clone> ApplyIf for T {}
// usage
fn double_odds(val: usize) -> usize {
val.apply_if(|v| v * 2, val % 2 == 1)
}
What’s nice about it is that you can chain the apply_if
calls. I used it for formatting / colorizing terminal output. An example of such usage would be
fn do_many_things_conditionally(val: usize) -> usize {
val
.apply_if(|v| v * 2, val % 2 == 1)
.apply_if(|v| v * 5, val % 5 == 3)
.apply_if(|v| v / 3, val % 9 == 0)
}