Introduction To Haskell
Function Composition

Introduction

Imagine that you have two functions. The return type of the first function is the argument type of the second. When this is true, you can create a new function by pipelining the result of the first function into the second.

Here is an example,

myOdd = not . even

Here, the not and even functions are combined to make a function that returns True if a number is odd.

WinGHCI

From the specification,

The operation functional composition combines two functions to get a new function.

Given two functions

  • f: A → B
  • g: B → C

function g o f, called the composition of g and f, is a function whose domain is A and co-domain is C.

Example

In this example, we define two functions, f and g. Function f adds 5 to its argument. Function g squares its argument.

f :: Integer->Integer
f x = x + 5

g :: Integer->Integer
g x = x^2

comp :: Integer -> Integer
comp = f.g

The comp function is the composition of functions f and g. The result of function g is pipelined to function f.

WinGHCI