Composition operator and pipe forward operator in Rust
rust
Solution
There is no such operator built-in, but it's not particularly hard to define:
use std::ops::Shr;
struct Wrapped<T>(T);
impl<A, B, F> Shr<F> for Wrapped<A>
where
F: FnOnce(A) -> B,
{
type Output = Wrapped<B>;
fn shr(self, f: F) -> Wrapped<B> {
Wrapped(f(self.0))
}
}
fn main() {
let string = Wrapped(1) >> (|x| x + 1) >> (|x| 2 * x) >> (|x: i32| x.to_string());
println!("{}", string.0);
}
// prints `4`
The `Wrapped` new-type struct is purely to allow the `Shr` instance, because otherwise we would have to implement it on a generic (i.e. `impl<A, B> Shr<...> for A`) and that doesn't work.
Note that idiomatic Rust would call this the method `map` instead of using an operator. See `Option::map` for a canonical example.
Problem
Do both the composition and pipe forward operators (like in other languages) exist in Rust? If so, what do they look like and one should one be preferred to the other? If one does not exist, why is this operator not needed?