Composition Everywhere


Watch The Power of Composition

By "composition," we mean, "Assemble a few low-level reusable pieces into a higher-level piece." Here are some examples:

  • (Classic example) Legos. Using small blocks of plastic, people can create all sorts of interesting things.
  • Furniture. Using wood, metal, fabric, glass, and nails, people can create tables, chairs, desks, cabinets, etc.

Composition makes FP code easy to refactor because we can always reassemble the smaller pieces into something new or different.

But what kinds of things do we compose? In Functional Programming, we compose types (called algebraic data types) and functions.

Composing Types Algebraically

Algebraic Data Types (ADTs) use Algebra to define the total number of values a given type (i.e. named Set) can have.

There are two videos worth watching in this regard. The table and visualizations that follow merely summarize their points, except for the ideas behind the List and Tree types in the second video.

NameMath OperatorLogic OperatorPureScript TypeIdea
Product Typex * yANDTuple"One value from type x AND one value from type y"
Sum Typex + yOREither"One value from type x OR one value from type y"
Exponential Typey^x???InputType -> OutputType???

Composing Types

Composing Functions

Similar to types, functions also compose but in a slightly different way. Look over the below image and then watch the video at the end (if you haven't seen it already).

Composing Functions

Video link: Logging a function's name each time it is called: migrating an "object-oriented paradigm" solution to an "functional paradigm" solution