Logo

Programming-Idioms

  • Python

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.

template<typename Pred1, typename Pred2>
auto compose(Pred1 f, Pred2 g){
  return [f,g](auto x){ return g(f(x)); };	
}
compose = lambda f, g, x: \
    lambda x: g(f(x))
def compose(f, g):
	return lambda x: g(f(x))

This is the same as for non-generic composition
(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