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?
The operators pipe their left-hand side values forward into expressions that appear on the right-hand side, i.e. one can replace f(x) with x %>% f() , where %>% is the (main) pipe-operator. When coupling several function calls with the pipe-operator, the benefit will become more apparent.
The pipe operator is a special operational function available under the magrittr and dplyr package (basically developed under magrittr), which allows us to pass the result of one function/argument to the other one in sequence. It is generally denoted by symbol %>% in R Programming.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With