Many computer programs today are written in a style called imperative programming. The programmer writes a list of steps that the computer's CPU will do one after another in order. A common analogy for imperative programs are recipes for cooking or baking food. Imperative programming came from a mathematical model called a Turing Machine, which is like a very long street with sequentially numbered mailboxes. Each mailbox contains a piece of paper with a number on it, and a very patient person drives up and down the street looking at the numbers on the pieces of paper and sometimes replacing them with new slips of paper with a different number.
So why is imperative programming popular?
- It has a concept of mutable state, which is like the ability to reuse the same mailbox multiple times by pulling out an old piece of paper and putting in a new one. Mailboxes are expensive, and so reuse is good
- Modern computers and smartphones are based on this imperative model, so the software matches the hardware and programmers can spend time optimizing the software to run very quickly and minimize use of memory
- It's prevalent and commonly taught, and it seems to be more intuitive for people and easier to learn
However, there is another major style of programming called functional programming. It's based on a separate but equivalent mathematical idea called the Lambda calculus. A Lambda calculus program is a big mathematical expression containing operators like +, −, ×, ÷, but also any other operator that you want to make up.
Functional programming is heavily in use today in the form of spreadsheets, and because of the formal proof that it is equivalent to the Turing Machine, you could emulate any software in existence with a large enough spreadsheet that contained the right forumlas.
So given the benefits of imperative programming, why would anyone be interested in functional programming?
- It has a lack of mutable state
- This makes it easier to look at a small part of a larger program and understand what the small part does without needing to understand the whole larger program
- It removes opportunities for race condition software defects
- It opens the door to automatically restarting or retrying the program after hardware failures
- It does not inherently dictate which order the computer must evaluate functions
- This removes software defects caused by imperatively specifying operations in the wrong order
- It also opens the door to automatically parallelizing software execution across multiple CPU cores and multiple networked computers
- Its subroutines, called pure functions—are ones that have no side effects and whose return values only depend on the parameters passed in
Most popular programming languages support mixing and matching the two styles. The simplest way to start doing functional programming in your language of choice is simple and gradual: Just start writing more of your code in the form of pure functions.