Functional Programming – Mental Models and Real-World Metaphors

functional programmingobject-oriented

Does anyone have a good mental model or metaphor for functional programming which references something in the real world?

Object Oriented programing intuitively makes sense to me. There are things that have properties and sometimes they also can do stuff or perform calculations on their properties (methods). (Ex: Car, Shape, Cat).

I bear functional programming no ill will whatsoever and I am not interested in a debate about the virtues of the two. I just need a metaphor or mental model to work with as I have with Object Oriented programming.

What are some good mental models or real world metaphors for programming in a functional paradigm? There is something about functions composed of functions processing functions which leaves one without a firm place to stand and cogitate.

Best Answer

Functional programming is all about gluing smaller functions together to achieve your results. A decent mental model (for me, at least) is an assembly line. Each function that gets composed is one more step in the assembly process. Consider this function here:

smallest  = head . sort

In Haskell, this function will return the smallest element in a list. The assembly line first sorts the input, then returns the first element (assuming it's sorted least to greatest.) If we wanted to only get the smallest even value, then we can change the assembly line to look like the following:

smallestEven = head . sort . filter even

It's just one more step on the conveyor belt.

In a nutshell, functions just describe the steps taken to convert the raw input (the parts) into the processed good (the output.)

Related Topic