Composing Functions into Pipelines
Introduction & Quick Recall: Building Data Pipelines
Welcome to the sixth and final unit of the course! Over the past few lessons, you have built a solid foundation in functional programming. We have explored how to treat functions as values and how to process lists using tools like *map*, *filter*, and *fold* (or *sum*).
A major goal of functional programming is to treat your code like data pipelines (an assembly line). You take data and pass it through a series of small, well-named transformations to get your final result.
Before we learn how to cleanly connect these steps, let us briefly recall how to define the small, simple functions that act as our building blocks.
Here, we have two straightforward functions. One doubles an integer, and the other increments it. While they are useful on their own, the real power of functional programming comes from chaining small steps like these together. In this lesson, we will learn how to elegantly stitch these tools into a single, highly readable pipeline without getting lost in nested parentheses.
Combining Functions with the . Operator
If we want to double a number and then increment the result, we could write it out manually for every number. However, Haskell gives us a special tool to fuse two functions together into a brand-new function. This is done using function composition via the . (dot) operator.
Here is the type signature for function composition:
The . operator represents mathematical function composition. It takes the output of one function and feeds it directly into the input of another. The right-hand function transforms an a into a b, and the left-hand function transforms that b into a c.
Let us build a new function called doubleThenIncrement by combining our two simple functions.
When you look at increment . double, it is important to understand the execution flow. In Haskell function composition, the data moves from right to left:
- The data enters the rightmost function (
double). - The result of that calculation flows to the left into the next function (
increment).
By using the . operator, we did not have to write a new manual formula. We simply glued our existing, well-tested building blocks together to create doubleThenIncrement.
