In computer science, function composition is an act or mechanism to combine simple functions to build more complicated ones. Like the usual composition of functions in mathematics, the result of each function is passed as the argument of the next, and the result of the last one is the result of the whole.
Programmers frequently apply functions to results of other functions, and almost all programming languages allow it. In some cases, the composition of functions is interesting as a function in its own right, to be used later. Such a function can always be defined but languages with first-class functions make it easier.
The ability to easily compose functions encourages factoring (breaking apart) functions for maintainability and code reuse. More generally, big systems might be built by composing whole programs.
Narrowly speaking, function composition applies to functions that operate on a finite amount of data, each step sequentially processing it before handing it to the next. Functions that operate on potentially infinite data (a stream or other codata) are known as filters, and are instead connected in a pipeline, which is analogous to function composition and can execute concurrently.
For example, suppose we have two functions and, as in and . Composing them means we first compute, and then use to compute . Here is the example in the C language:
The steps can be combined if we don't give a name to the intermediate result:
Despite differences in length, these two implementations compute the same result. The second implementation requires only one line of code and is colloquially referred to as a "highly composed" form. Readability and hence maintainability is one advantage of highly composed forms, since they require fewer lines of code, minimizing a program's "surface area".[1] DeMarco and Lister empirically verify an inverse relationship between surface area and maintainability.[2] On the other hand, it may be possible to overuse highly composed forms. A nesting of too many functions may have the opposite effect, making the code less maintainable.
In a stack-based language, functional composition is even more natural: it is performed by concatenation, and is usually the primary method of program design. The above example in Forth: g fWhich will take whatever was on the stack before, apply g, then f, and leave the result on the stack. See postfix composition notation for the corresponding mathematical notation.
Now suppose that the combination of calling f on the result of g is frequently useful, and which we want to name foo to be used as a function in its own right.
In most languages, we can define a new function implemented by composition. Example in C:
(the long form with intermediates would work as well.) Example in Forth:
: foo g f ;
In languages such as C, the only way to create a new function is to define it in the program source, which means that functions can't be composed at run time. An evaluation of an arbitrary composition of predefined functions, however, is possible:
typedef int FXN(int);
int f(int x) int g(int x) int h(int x)
int eval(FXN *fs[], int size, int x)
int main
In functional programming languages, function composition can be naturally expressed as a higher-order function or operator. In other programming languages you can write your own mechanisms to perform function composition.
In Haskell, the example given above becomes: foo = f . gusing the built-in composition operator (.) which can be read as f after g or g composed with f.
The composition operator itself can be defined in Haskell using a lambda expression:
Variants of Lisp, especially Scheme, the interchangeability of code and data together with the treatment of functions lend themselves extremely well for a recursive definition of a variadic compositional operator.
(define givebang (compose string->symbol add-a-bang symbol->string))
(givebang 'set) ;
APL
∘
. This higher-order function extends function composition to dyadic application of the left side function such that A f∘g B
is A f g B
.Additionally, you can define function composition:
In dialect that does not support inline definition using braces, the traditional definition is available:
Raku like Haskell has a built in function composition operator, the main difference is it is spelled as ∘
or o
.
Also like Haskell you could define the operator yourself. In fact the following is the Raku code used to define it in the Rakudo implementation.
proto sub infix:<∘> (&?, &?) is equiv(&[~]) is assoc
multi sub infix:<∘> # allows `[∘] @array` to work when `@array` is emptymulti sub infix:<∘> (&f) # allows `[∘] @array` to work when `@array` has one elementmulti sub infix:<∘> (&f, &g --> Block)
my &infix:
Nim supports uniform function call syntax, which allows for arbitrary function composition through the method syntax .
operator.[3]
echo foo(5).bar(6).bazecho baz(bar(6, foo(5)))
In Python, a way to define the composition for any group of functions, is using reduce function (use functools.reduce in Python 3):
from functools import reducefrom typing import Callable
def compose(*funcs) -> Callableint, int]: """Compose a group of functions (f(g(h(...)))) into a single composite func.""" return reduce(lambda f, g: lambda x: f(g(x)), funcs)
f = lambda x: x + 1g = lambda x: x * 2h = lambda x: x - 3
print(compose(f, g, h)(10))
In JavaScript we can define it as a function which takes two functions f and g, and produces a function:
// Alternatively, using the rest operator and lambda expressions in ES2015const compose = (...fs) => (x) => fs.reduceRight((acc, f) => f(acc), x)
In C# we can define it as an Extension method which takes Funcs f and g, and produces a new Func:
public static Func
Languages like Ruby let you construct a binary operator yourself:
f = ->(x) g = ->(x) (f + g).call(12) # => 13824However, a native function composition operator was introduced in Ruby 2.6:[4]
x + 2 |
x * 3 |
Notions of composition, including the principle of compositionality and composability, are so ubiquitous that numerous strands of research have separately evolved. The following is a sampling of the kind of research in which the notion of composition is central.
Whole programs or systems can be treated as functions, which can be readily composed if their inputs and outputs are well-defined. Pipelines allowing easy composition of filters were so successful that they became a design pattern of operating systems.
Imperative procedures with side effects violate referential transparency and therefore are not cleanly composable. However if one considers the "state of the world" before and after running the code as its input and output, one gets a clean function. Composition of such functions corresponds to running the procedures one after the other. The monad formalism uses this idea to incorporate side effects and input/output (I/O) into functional languages.