Above we focused on functions to help in reducing repetition or setting sub-goals. However, in Chapter 2 we briefly remarked that there is a functional paradigm to programming. In this paradigm, instead of expressing commands as a set of instructions followed line by line, they are expressed as functions that call other functions to solve the problems. Sometimes this can be an easier way to express the problem as functions than to think of them as a line-by-line instruction. A classic example of this is the Fibonancci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . After the first three values, the values are sums of the two previous values: , and . Calculating this series could be completed with some kind of for-loop. Alternatively, we could define it as a function (see Code Example 8.10). The definition of the function explicates that the th value (or what is returned at the function) is the sum of two previous values, unless or .
Code example 8.10 is a common strategy in functional programming: calling the function again within the function to create repetition. This is known as recursion. Sometimes this approach can clarify cases where we otherwise need to do difficult structure repetitions. For example, the search on networks could be replaced by two simple commands:
Another way to use more functional programming is to apply functions to all elements of the lists. For example, when increasing all items of a list by one, you actually apply function to all items on the list; let be the first item, then the second item and so on until the function has been applied to all items in the list. Code Example 8.12 shows how to use a map to apply a function to all items in the list. The example also shows how a filter can be used to easily remove unwanted elements from the list. In filter, the function defines the inclusion criteria. Sometimes, the reduce command may be similarly helpful if the aim is to transform a list into a single variable. In this case, the function has two inputs: previous results of reduce and the most recent item. Reduce applies the function to the two of them and stores the new result to be used in the next step of reduce. The third element is examined together with the output of reduce at the first two functions. These short-hand functions can help in various tasks related to data management, but mastering them is not required to writing clean and understandable code.