Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composition operator and pipe forward operator in Rust

Tags:

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?

like image 384
Phlox Midas Avatar asked Jun 11 '13 22:06

Phlox Midas


People also ask

What is a forward pipe operator?

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.

What is pipe operator?

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.


1 Answers

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.

like image 148
huon Avatar answered Oct 31 '22 04:10

huon