CONCEPTS OVER SYNTAX
Recall from THINKING IN EXPRESSIONS that imperative programs are built from statements.
These statements are mechanical instructions for the computer that often have nothing to do with the problem we’re trying to solve.
Let’s read this example again:
let numbers = [1, 2, 3];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
What is the problem we’re trying to solve here?
Ultimately, we’re trying to calculate the sum of a bunch of numbers.
However, most of this program has nothing to do with the problem we’re trying to solve:
- What is
i
, and what does it have to do with summing numbers? - Is the length of the array actually relevant when summing numbers?
sum += numbers[i]
This is the only line in the entire program that is relevant to the problem we’re trying to solve. Everything else is just noise.
Let’s rewrite this in a functional style using these building blocks:
-
[1, 2, 3]
: our array of numbers -
[1, 2, 3].reduce
: a function that reduces[1, 2, 3]
into a single value -
(a, b) => a + b
: a function that adds two numbers -
0
: initial value for the reduction
[1, 2, 3].reduce((a, b) => a + b, 0)
Our functional program is simple, concise, and focused on solving the problem. It focuses on what we want out of the program, rather than how to solve it mechanically.
Abstract Data Types (ADTs)
Here are some common ADTs in functional programs, agnostic of any language or syntax:
-
Sequence
A sequence is an indefinite, ordered collection of values that allows repetition
Examples:
- All natural numbers:
1 2 3 ...
- A random number generator:
0.456 0.123 0.789 ...
- All natural numbers:
-
List:
A list is a finite, ordered collection of values that allows repetition
In other words, a list is like a finite sequence
Example: All integers between 1 and 10
-
Bag:
A bag is a finite, unordered collection of values that allows repetition
In other words, a bag is like a list where order doesn’t matter
Example:
Apple Banana Orange Banana Orange Apple
-
Set:
A set is a finite, unordered collection of values that does not allow repetition
In other words, a set is like a bag where all items are unique
Example:
Apple Banana Orange