Logo

Programming-Idioms

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

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

#include <functional>
std::function<C (A)> compose(B (&f)(A), C (&g)(B))
{
    return [&f, &g](A a){return g(f(a));};
}

auto fn = compose(f, g);

using lambda
(defn compose [f g]
   (comp g f))

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