The imperative way
We keep contrasting FP with the imperative style of programming. What do we mean by imperative style, though?
The imperative programming style is embodied by a sequence of commands modifying a program's state. A simple example of this is a for loop. Consider the following pseudo code snippet to print all the elements of an array:
x = [1,2,3,4...] // an array, x.size tells the number of array elements for( int i = 0; i < x.size; ++i ) { println(x[i]) }
Here is a pictorial rendering of the concepts:
As the figure shows, the for loop establishes an initial state by setting the variable i
to 0
. The variable is incremented every time the loop is repeated; this is what we mean by the state being modified. We keep reading and modifying the state, that is, the loop variable, until there are no elements left in the array.
FP advocates staying away from any state modification. It gives us tools so we don't worry about how to loop over a collection; instead, we focus on what we need to do with each element of the collection.