Logo

Programming-Idioms

  • Python
  • Rust
  • Ruby

Idiom #35 First-class function : compose

Implement a function compose (A -> C) with parameters f (A -> B) and g (B -> C), which returns the composition function g ∘ f

def compose(f, g):
    return lambda a: g(f(a))

We could have used a named function but a lambda is shorter
fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C {
    move |x| g(f(x))
}
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.
def compose(f, g)
  -> x { g.(f.(x)) }
end
(defn compose [f g]
   (comp g f))

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