Created
February 23, 2023 12:12
-
-
Save MikuroXina/7556f24710f9de76dc323261ce807df8 to your computer and use it in GitHub Desktop.
The composition of functions in Rust.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| pub fn compose<'l, X, Y, Z>( | |
| left: &'l dyn Fn(Y) -> Z | |
| ) -> Box<dyn | |
| Fn(&'l dyn Fn(X) -> Y) -> Box<dyn | |
| Fn(X) -> Z | |
| + 'l | |
| > | |
| + 'l | |
| > { | |
| Box::new(move |right| { | |
| Box::new(move |x| { | |
| left(right(x)) | |
| }) | |
| }) | |
| } | |
| #[test] | |
| fn twice_then_add_one() { | |
| let add_one = |x: u32| x + 1; | |
| let twice = |x: u32| x * 2; | |
| let res = compose(&add_one)(&twice)(4); | |
| assert_eq!(res, 9); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment