A write-up by Hadley Wickham shows the aspects of Functional Programming in R. It’s a great article for understanding both R and using functions as the core of operations in R. Three building blocks are explained:
1. Anonymous functions
2. Closures (functions written by functions)
3. Lists of functions.
In a restricted sense, functional programming means programming without mutable variables, assignments, loops and control structures.
In a wider sense, functional programming paradigm focuses on functions. When we focus on functions, we think about what is to be done rather than how.
Suppose you have to calculate sum of the squares.
int square = i*i;
sum = sum + square;
In an imperative style you would start thinking about initializing the sum variable as 0, iterating over 1 to n, squaring each number and adding these squares to the sum variable on each iteration.
There is iteration and mutable variables.
In functional thinking you would identify functions to be used.
There are three words in this program: take, map and sum. Each of these words refers to a function. The “.” simply means- call the following function and the give it, the result of current function as the argument.
The take function’s responsibility is to emit a list of integers from 1 to n. map function maps each element of this list to its squares and produces another list. sum function takes this list and returns the sum.
Each function does only one job and we solve the problem in terms of functions and not in steps.
So, functional programming is about applying function to data rather than bringing data to functions.
In a way, it’s similar to using axe(function) to cut the wood(data) rather than bringing the wood to axe.
Natural. Isn’t it?