You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Function composition and partial application are two powerful techniques in functional programming that allow you to build complex functions from simpler ones. Both are key A-Level topics.
Function composition is the process of combining two or more functions to create a new function. The output of one function becomes the input of the next.
If f : B → C and g : A → B, then the composition (f . g) : A → C is defined as:
(f . g)(x) = f(g(x))
First apply g, then apply f to the result.
In Haskell, the composition operator is the dot (.).
-- Two simple functions
double x = x * 2
addOne x = x + 1
-- Compose them: first double, then add one
doubleAndAddOne = addOne . double
doubleAndAddOne 5 -- double 5 = 10, addOne 10 = 11
-- Compose in the other order: first add one, then double
addOneAndDouble = double . addOne
addOneAndDouble 5 -- addOne 5 = 6, double 6 = 12
Important: Composition reads right to left — in f . g, g is applied first.
Python does not have a built-in composition operator, but you can compose functions manually:
def compose(f, g):
return lambda x: f(g(x))
double = lambda x: x * 2
add_one = lambda x: x + 1
double_and_add_one = compose(add_one, double)
print(double_and_add_one(5)) # 11
-- Compose three functions
negate x = -x
double x = x * 2
addOne x = x + 1
transform = negate . addOne . double
transform 3 -- double 3 = 6, addOne 6 = 7, negate 7 = -7
Partial application is the process of fixing some arguments of a function, producing a new function that takes the remaining arguments.
In Haskell, all functions are curried by default. This means a function that appears to take multiple arguments actually takes them one at a time, returning a new function at each step.
-- add takes two arguments
add :: Int -> Int -> Int
add x y = x + y
-- Partially apply: fix the first argument to 5
addFive :: Int -> Int
addFive = add 5
addFive 3 -- Result: 8
addFive 10 -- Result: 15
The type signature Int -> Int -> Int is actually Int -> (Int -> Int) — a function that takes an Int and returns a function from Int to Int.
-- multiply is a two-argument function
multiply x y = x * y
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.