Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Rust

Idiom #36 First-class function : generic composition

Implement a function compose which returns composition function g ∘ f for any functions f and g having exactly 1 parameter.

fn compose<'a, A, B, C, G, F>(f: F, g: G) -> Box<Fn(A) -> C + 'a>
	where F: 'a + Fn(A) -> B, G: 'a + Fn(B) -> C
{
	Box::new(move |x| g(f(x)))
}

Unfortunately, you'll need to implement another two variants if you care about FnMut and FnOnce. Also, for now, you need to box the returned function. In the future, this shouldn't be necessary.
fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C {
    move |x| g(f(x))
}
(comp g f)

Function composition is already a function in Clojure's core API. It has no restriction on numbers of parameters.

New implementation...
< >
programming-idioms.org