Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • 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 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).
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.
(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