Logo

Programming-Idioms

  • Python
  • Go

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.

func compose[T, U, V any](f func(T) U, g func(U) V) func(T) V {
	return func(x T) V {
		return g(f(x))
	}
}

compose is generic, it accepts any type parameters T, U, V.
func composeIntFuncs(f func(int) int, g func(int) int) func(int) int {
	return func(x int) int {
		return g(f(x))
	}
}

These specific functions take and return concrete types.

It could be done with an empty interface, but that would discard static type checks (the implementations of f and g can still be type-checked, though).
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