Composing functions
Because we have now learned how to return arbitrary closures with no overhead, we can combine that with macros that accept any number of parameters (Chapter 1, Learning the Basics; Accepting a variable number of arguments) to create an easy way to chain actions as you would be used to in functional languages such as Haskell.
How to do it...
Open the
Cargo.toml
file that has been generated earlier for you.In the
bin
folder, create a file calledcompose_functions.rs
.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...