How to do it...

  1. Open the Cargo.toml file that has been generated earlier for you.

  2. In the bin folder, create a file called compose_functions.rs.

  3. Add the following code, and run it with cargo run --bin compose_functions:

1   #![feature(conservative_impl_trait)]
2   
3   // The compose! macro takes a variadic amount of closures and  
returns 4 // a closure that applies them all one after another 5 macro_rules! compose { 6 ( $last:expr ) => { $last }; 7 ( $head:expr, $ ($tail:expr), +) => { 8 compose_two($head, compose!($ ($tail), +)) 9 }; 10 } 11 12 // compose_two is a helper function used to 13 // compose only two closures into one 14 fn compose_two<FunOne, FunTwo, Input, Intermediate, Output>( 15 fun_one: FunOne, 16 fun_two: FunTwo, 17 ) -> impl Fn(Input) -> Output 18 where 19 FunOne: Fn(Input) -> Intermediate, 20 FunTwo: Fn(Intermediate) -> Output, 21 { 22 move |x| fun_two(fun_one(x)) 23 } 24 25 fn main() { 26 let add = |x| x + 2.0; 27 let multiply = |x| x * 3.0; 28 let divide = |x| x / 4.0; 29 // itermediate(x) returns ((x + 2) * 3) / 4 30 let intermediate = compose!(add, multiply, divide); 31 32 let subtract = |x| x - 5.0; 33 // finally(x) returns (((x + 2) * 3) / 4) - 5 34 let finally = compose!(intermediate, subtract); 35 36 println!("(((10 + 2) * 3) / 4) - 5 is: {}", finally(10.0)); 37 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.129.253