Logo

Programming-Idioms

  • Python
  • Lua

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

function compose(f,g)
   return function(x)
      return g(f(x))
   end
end
def compose(f, g):
    return lambda a: g(f(a))

We could have used a named function but a lambda is shorter
(defn compose [f g]
   (comp g f))

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