Skip to content

Instantly share code, notes, and snippets.

@MikuroXina
Created February 23, 2023 12:12
Show Gist options
  • Select an option

  • Save MikuroXina/7556f24710f9de76dc323261ce807df8 to your computer and use it in GitHub Desktop.

Select an option

Save MikuroXina/7556f24710f9de76dc323261ce807df8 to your computer and use it in GitHub Desktop.
The composition of functions in Rust.
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